83 lines
1.7 KiB
PHP
83 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Exceptions\BizException;
|
|
use Illuminate\Contracts\Cache\Repository as Cache;
|
|
|
|
class CaptchaService
|
|
{
|
|
/**
|
|
* @var string
|
|
*/
|
|
protected $cachePrefix = 'captchas_';
|
|
|
|
/**
|
|
* @param \Illuminate\Contracts\Cache\Repository $cache
|
|
*/
|
|
public function __construct(
|
|
protected Cache $cache,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* 将验证码存入缓存中
|
|
*
|
|
* @param string $key
|
|
* @param string $phrase
|
|
* @param integer $ttl
|
|
* @return void
|
|
*/
|
|
public function put(string $key, string $phrase, int $ttl = 300): void
|
|
{
|
|
$this->cache->put($this->cacheKey($key), $phrase, $ttl);
|
|
}
|
|
|
|
/**
|
|
* 校验验证码是否正确
|
|
*
|
|
* @param string $key
|
|
* @param string $phrase
|
|
* @return bool
|
|
*/
|
|
public function testPhrase(string $key, string $phrase): bool
|
|
{
|
|
if ($phrase === '') {
|
|
return false;
|
|
}
|
|
|
|
$value = (string) $this->cache->pull(
|
|
$this->cacheKey($key)
|
|
);
|
|
|
|
return strtolower($value) === strtolower($phrase);
|
|
}
|
|
|
|
/**
|
|
* 校验验证码是否正确
|
|
*
|
|
* @param string $key
|
|
* @param string $phrase
|
|
* @return void
|
|
*
|
|
* @throws \App\Exceptions\BizException
|
|
*/
|
|
public function validatePhrase(string $key, string $phrase): void
|
|
{
|
|
if (! $this->testPhrase($key, $phrase)) {
|
|
throw new BizException(__('Invalid captcha'));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 生成验证码缓存的 key
|
|
*
|
|
* @param string $key
|
|
* @return string
|
|
*/
|
|
protected function cacheKey(string $key): string
|
|
{
|
|
return $this->cachePrefix.$key;
|
|
}
|
|
}
|