fulinqingjie/app/Rules/CaptchaRule.php

44 lines
1014 B
PHP
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Rules;
use App\Services\CaptchaService;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\App;
class CaptchaRule implements ValidationRule
{
/**
* @var string 验证码类型键名
*/
protected string $key;
/**
* @var bool 验证后是否销毁
*/
protected bool $destroy;
public function __construct(string $key = 'default', bool $destroy = true)
{
$this->key = $key;
}
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
//
// 从容器获取 Service便于测试和依赖注入
$captchaService = App::make(CaptchaService::class);
if (!$captchaService->testPhrase($this->key, $value)) {
$fail('验证码错误,请重新输入');
}
}
}