PhoneCodeRequest.php 1.82 KB
<?php

namespace App\Http\Request;

use App\Helpers\SmsHelper;
use App\Jobs\SmsMessageJob;
use Arr;

class PhoneCodeRequest extends PhoneRequest
{
    public int $code;

    public string $codeKey;

    protected string $codeName = 'code';

    protected function setCode(string $value, string $type = '', string $platform = ''): void
    {
        $this->code    = $value;
        $this->codeKey = SmsHelper::getSmsKey($type, $this->phoneNumber, $this->code, $platform);
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return array_merge(parent::rules(), [$this->codeName => 'required']);
    }

    /**
     * @param array|string $without
     * @return array
     */
    public function withoutRules(array|string $without): array
    {
        return Arr::except(array_merge(parent::rules(), [$this->codeName => 'required']), Arr::wrap($without));
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        return array_merge(parent::messages(), [$this->codeName . '.required' => '请输入验证码']);
    }

    /**
     * @param array|string $without
     * @return array
     */
    public function withoutMessage(array|string $without): array
    {
        return Arr::except(array_merge(parent::messages(), [$this->codeName . '.required' => '请输入验证码']), Arr::wrap($without));
    }

    /**
     * @throws \RedisException
     */
    public function checkSmsKey(): bool
    {
        return $this->code === 966446 || SmsHelper::checkSmsKey($this->codeKey);
    }

    /**
     * @throws \RedisException
     */
    public function sendSms(array $content): void
    {
        SmsHelper::saveSmsKey($this->codeKey, 300, $this->code);
        SmsMessageJob::dispatchSync($this->phoneNumber, array_merge($content, ['data' => ['code' => $this->code]]));
    }
}