<?php
namespace common\helpers;

use yii\caching\Cache;
use yii\captcha\CaptchaAction;

class CodeImgGenerate extends CaptchaAction
{
    private $verifycode;

    public function __construct($id, $controller)
    {
        parent::__construct($id, $controller);
        $this->init();
        // 更多api请访问yii\captcha\CaptchaAction类文档
        // 这里可以初始化默认样式
        $this->maxLength = 4;            // 最大显示个数
        $this->minLength = 4;            // 最少显示个数
        $this->backColor = 0x000000;     // 背景颜色
        $this->foreColor = 0x00ff00;     // 字体颜色
        $this->width = 100;               // 宽度
        $this->height = 58;              // 高度
        $this->backColor = Util::captcha_color(1);    // 背景颜色
        $this->foreColor = Util::captcha_color(2);    // 字体颜色
        $this->padding  = 0;                          // 间距
        $this->offset = 4;                            // 字符之间的偏移量
    }

    /**
     * [返回图片二进制]
     * @return [type] [description]
     */
    public function inline()
    {
        return $this->renderImage($this->getPhrase());
    }

    /**
     * [返回图片验证码]
     * @return [type] [description]
     */
    public function getPhrase()
    {
        if(!$this->verifycode){
        }
            $this->verifycode = (string)rand(1234, 9999);
            \Yii::$app->cache->set($this->getSessionKey() . '/' . $this->verifycode, $this->verifycode);

        return $this->verifycode;
    }

    public function validate($input, $caseSensitive = false)
    {
        $code = \Yii::$app->cache->get($this->getSessionKey() . '/' . $input);
        $valid = strcasecmp($input, $code) === 0;

        return $valid;
    }
}
?>