SmsMessageJob.php
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace App\Jobs;
use App\Models\SystemSmsLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Overtrue\EasySms\PhoneNumber;
class SmsMessageJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public PhoneNumber $phoneNumber;
public array $data;
public function __construct(PhoneNumber $phoneNumber, array $data = [])
{
$this->phoneNumber = $phoneNumber;
$this->data = $data;
if (isset($data['content'], $data['data']) && is_array($data['data'])) {
$params = collect();
Arr::map($data['data'], static fn(string $value, string $key) => $params->put('${' . $key . '}', $value));
$this->data['content'] = str_replace($params->keys()->toArray(), $params->values()->toArray(), $data['content']);
}
}
public function handle(): void
{
try {
$results = app('easy-sms')->send($this->phoneNumber, $this->data);
} catch (NoGatewayAvailableException $exception) {
$results = $exception->getResults();
}
foreach ($results as $result) {
$this->saveLog(
$result['gateway'],
Arr::except($this->data, 'data'),
isset($result['exception']) ? data_get($result, 'exception.raw') : $result['result'],
$result['status']
);
}
}
/**
* @param string $gateway
* @param array $content
* @param array $result
* @param string $status
* @return void
*/
private function saveLog(string $gateway, array $content, array $result, string $status = 'success'): void
{
SystemSmsLog::query()->create([
'gateway' => $gateway,
'phone' => $this->phoneNumber->getUniversalNumber(),
'content' => $content,
'result' => $result,
'status' => $status,
]);
}
}