<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace common\behaviors;

use Yii;
use yii\base\Action;
use yii\base\ActionFilter;
use yii\di\Instance;
use yii\web\ForbiddenHttpException;

/**
 * 客户滤器
 *
 * 过滤 当前自己负责的和下属负责的区域的客户
 * 
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class CustomerFilter extends ActionFilter
{
	/**
     * @var class 当前操作所属模型
     */
	public $model;

	/**
     * @var char 父级数据名
     */
	public $pk = 'parent_id';

    /**
     * @var string 错误提示
     */
    public $errorInfo = '该类别存在子类，无法删除';

	/**
	 * @var callable 指定当规则需要拒绝相关访问时,应该调用哪个 PHP callable 对象
	 *
	 * 使用格式如下：
	 * ~~~
     * function ($rule, $action)
     * ~~~
	 */
	public $denyCallback;

	/**
	 * @var array 访问规则
	 */
    public $rules = [
        'actions' => ['delete'],
        'allow' => true,
        'roles' => ['@']
    ];

    public function beforeAction($action)
    {
        $id = Yii::$app->request->get('id');
        $this->getModel($action);
        if (isset($id) && call_user_func([$this->model, 'findOne'], [$this->pk => $id])) {
            if (isset($this->denyCallback)) {
                call_user_func($this->denyCallback, null, $action);
            } else {
                $this->denyAccess();
            }
            return false;
        } else {
            return true;    
        }
    }

    /**
     * 默认规则拒绝时的操作
     * 
     * @throws ForbiddenHttpException 显示出错信息
     */
    protected function denyAccess()
    {
        throw new ForbiddenHttpException(Yii::t('yii', $this->errorInfo));
    }

    /**
     * 获取当前操作所属模型
     */
    protected function getModel($action)
    {
        if ($this->model == null) {
            $controllerId = $action->controller->id;
            $modelName = '';
            //如果控制器id包含-,则模型名称为-分隔的单词的首字母大写拼接而成
            if (false !== strpos($controllerId, '-')) {
                $words = explode('-', $controllerId);
                foreach ($words as $word) {
                    $modelName .= ucwords($word);
                }
            } else {
                $modelName = ucwords($action->controller->id);
            }
            $this->model = $action->controller->module->id == 'home' ? 'home\models\\' . $modelName : 'home\modules\\' . $action->controller->module->id . '\\models\\' . $modelName;
        }
    }
}
