<?php

namespace App\Lib;

use Illuminate\Support\Facades\Redis;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

class Captcha
{
    private static $builder;

    public static function getCaptcha($codeLength, $width, $height) {
        // 包含的字符
        $chars = '23456789abcefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';

        $builder = new PhraseBuilder($codeLength, $chars);
        $captcha = new CaptchaBuilder(null, $builder);

        // 生成验证码
        self::$builder = $captcha->build($width, $height, $font = null);

        // base64 image
        $image = self::getImage();

        // uniqueId
        $uniqueId = uniqid('captcha_', true) . mt_rand(100000,999999);

        $value = $captcha->getPhrase();

        return ['image' => $image, 'unique_id' => $uniqueId, 'value' => $value];
    }

    private static function getImage($quality = 9) {
        return 'data:image/png;base64,' . base64_encode(self::get($quality));
    }

    private static function get($quality) {
        ob_start();
        imagepng(self::$builder->getContents(), null, $quality);
        return ob_get_clean();
    }

    public static function checkCaptcha($uniqueId, $code) {
        $result = [
            'res' => false,
            'msg' => '校验通过',
        ];

        if (mb_strlen($uniqueId) != 37 || mb_strlen($code) < 4 || mb_strlen($code) > 9){
            $result['msg'] = '验证码异常';
            return $result;
        }

        $cacheCode = Redis::get($uniqueId);
        if (empty($cacheCode)) {
            $result['code'] = 10010;
            $result['msg'] = '验证码已失效';
            return $result;
        }

        if (strtolower($code) != $cacheCode) {
            $result['code'] = 10010;
            $result['msg'] = '验证码不正确';
            return $result;
        }

//        Redis::del($uniqueId);
        $result['res'] = true;
        return $result;
    }

}
















