<?php
namespace App\Base;

use App\Exception\custom\SignException;
use Helpers\ApiResponse;
use Yaf\Controller_Abstract;
use Helpers\Aes;

abstract class Base extends Controller_Abstract
{
    use ApiResponse;

    /**
     * 前置操作方法列表
     *
     *  protected $beforeActionList = [
     *      'first',                                //在所有方法前执行
     *      'second' =>  ['except'=>'hello'],       //在除了hello以外的其它方法之前执行
     *      'three'  =>  ['only'=>'hello,data']     //只在hello,data方法前执行
     *  ];
     *
     * @var array $beforeActionList
     * @access protected
     */
    protected $beforeActionList = [];

    protected $params;

    public function init(){
        $this->setParam();
        // 前置操作方法
        if (!empty($this->beforeActionList)) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ? $this->beforeAction($options) : $this->beforeAction($method, $options);
            }
        }
    }

    /**
     * 前置操作
     * @access protected
     * @param string $method 前置操作方法名
     * @param array $options 调用参数 ['only'=>[...]] 或者['except'=>[...]]
     */
    private function beforeAction($method, $options = [])
    {
        $action = $this->getRequest()->getActionName();
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }
            if (!in_array($action, $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }
            if (in_array($action, $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }


    /**
     * 验签
     */
    public function checkAes(){
        $data = $this->getRequest()->getRequest();
        if (! Aes::checkSign($data)) {
            throw new SignException(["cus"=>0]);
        }
    }

    private function setParam()
    {
        $params = $this->getRequest()->getRequest();
        unset($params['s']);
        $this->params = $params;
    }
}
