SmsMessageJob.php 2.16 KB
<?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,
        ]);
    }
}