2020/5/21 * --------------------------------------- */ public function init() { parent::init(); // 多语言,需要在http header中设置 app-language:zh-CN //Yii::$app->language = Yii::$app->request->getHeaders()->get('app-language'); //'en-US'; Yii::$app->params['web'] = Config::lists(); } /** * --------------------------------------- * 行为 * * @return array * * @author hlf 2020/5/21 * --------------------------------------- */ final public function behaviors() { $behaviors = parent::behaviors(); $newBehaviors = []; $newBehaviors['corsFilter'] = [ 'class' => Cors::class, ]; // $newBehaviors['pageFilter'] = [ // 'class' => PageFilterBehavior::class,//如果不是接口请求直接返回布局页面 // 'allowActions'=>[ // 'debug/*','gii/*' // ] // ]; foreach ($behaviors as $k => $v) { $newBehaviors[$k] = $v; } //unset($behaviors['authenticator']); //删掉,保持先cors,后authenticator // 设置认证方式,接口才认证 $newBehaviors['authenticator'] = [ 'class' => HttpBearerAuth::class, 'optional' => $this->optional, ]; return $newBehaviors; } public function beforeAction($action) { $ret = parent::beforeAction($action); // TODO: Change the autogenerated stub //不同角色权限 if (!Yii::$app->user->isGuest) { /** @var Admin $admin */ $admin = Yii::$app->user->identity; $this->mallId = $this->supplierId = 0; switch ($admin->role) { //角色1为官方管理,2为市场专员,3为客服,4为供应商管理,5为业务员,6为门店管理 case 1: //官方管理 $this->mallId = FakeId::decodeId($this->get("mallId", 0)); $this->supplierId = FakeId::decodeId($this->get("supplierId", 0)); break; case 2: case 3: //@todo 根据绑定关系 $this->mallId = 0; $this->supplierId = 0; break; case 4: $this->mallId = 0; $this->supplierId = $admin->supplier_id; break; case 5: $this->mallId = 0; $this->supplierId = $admin->supplier_id; break; case 6: $this->supplierId = 0; $this->mallId = $admin->mall_id; break; } Yii::$app->mallId = $this->mallId; Yii::$app->supplierId = $this->supplierId; } return $ret; } public function create($query, $post) { $pagination = []; $defaultPageSize = 10; if (isset($post['page'])) { $pagination['page'] = (int)$post['page']; } if (isset($post['limit'])) { $defaultPageSize = (int)$post['limit']; } return new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'defaultPageSize' => $defaultPageSize, 'params' => $pagination ] ]); } /** * 当前登陆用户ID * @return int|string */ public function getCurrentUserId() { return Yii::$app->user->identity->getId(); } /** * 取post参数 * @param $name * @param $defaultValue * @return array|mixed */ public function post($name = null, $defaultValue = null) { return Yii::$app->request->post($name, $defaultValue); } /** * 取get参数 * @param $name * @param $defaultValue * @return array|mixed */ public function get($name = null, $defaultValue = null) { return Yii::$app->request->get($name, $defaultValue); } /** * 参数验证 * @param $data * @param $rules * @return DynamicModel|\stdClass * @throws */ public function requestValidate($data, $rules) { foreach ($rules as $rule) { if (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type foreach ((array)$rule[0] as $r) { if (!isset($data[$r])) { $data[$r] = null; } } } } $validate = DynamicModel::validateData($data, $rules); if ($validate->hasErrors()) { throw new InvalidArgumentException(current($validate->getFirstErrors())); } return $validate; } public function serializeData($data) { if (Yii::$app->response->format == Response::FORMAT_RAW) { return $data; } if ($data instanceof Model && $data->hasErrors()) { throw new InvalidArgumentException('参数错误。' . implode('', $data->getFirstErrors())); // $data = $this->serializeModelErrors($data); } elseif ($data instanceof Arrayable) { $data = $this->serializeModel($data); } elseif ($data instanceof DataProviderInterface) { $data = $this->serializeDataProvider($data); } elseif ($data === null) { $data = []; } return array_merge($this->extend_result, $data); } protected function serializeDataProvider($dataProvider) { if (!empty($this->field)) { $models = ArrayHelper::toArray($dataProvider->getModels(), $this->field); } else { $models = array_values($dataProvider->getModels()); $models = $this->serializeModels($models); } $pagination = $dataProvider->getPagination(); $result = [ $this->listkey => $models, ]; if ($pagination !== false) { return array_merge($result, $this->serializePagination($pagination)); } return $result; } /** * Serializes a model object. * @param Arrayable $model * @return array the array representation of the model */ protected function serializeModel($model) { return $model->toArray(); } protected function serializeModels(array $models) { foreach ($models as $i => $model) { if ($model instanceof Arrayable) { $models[$i] = $model->toArray(); } elseif (is_array($model)) { $models[$i] = ArrayHelper::toArray($model); } } return $models; } protected function serializePagination($pagination) { return [ //$this->pagekey => [ 'total' => $pagination->totalCount, 'totalPage' => $pagination->getPageCount(), 'pageSize' => $pagination->getPageSize(), //], ]; } final public function afterAction($action, $result) { $result = parent::afterAction($action, $result); return $this->serializeData($result); } public function createUrl($params) { return Yii::$app->urlManager->createUrl($params); } /** * 前端事件 * @param array $model * @param $type * @param $name * @return false|void */ public function callbackEvent($models, $key, $type) { $event = new Event(get_called_class()); if (!empty($models)) { foreach ($models as $model) { $event->add($type, $model[$key], $model); } } else { //没有的话默认刷新事件 $event->add($type, $key, []); } $this->extend_result['__event'] = $event->render()['__event']; } public function render($view, $params = []) { Yii::$app->response->format = Response::FORMAT_RAW; $this->layout = false;//去掉布局 return parent::render($view, $params); // TODO: Change the autogenerated stub } public function getErrorMsg($model = null) { if (!$model) { $model = $this; } $msg = isset($model->errors) ? current($model->errors)[0] : '数据异常!'; return $msg; } public function actionCheckAuth() { $user_id = Yii::$app->user->identity; $path = 'Admin/' . Yii::$app->requestedRoute; $path = explode('/', $path); foreach ($path as $value) { $v = ucfirst($value); $arr[] = $v; } $new_path = implode('/', $arr); $AuthRule = AuthRule::find()->where(['path' => $new_path])->one(); if (!$AuthRule) throw new Exception('权限不存在!!!'); if ($AuthRule->status == 0) { throw new Exception('该权限已被禁用'); } $AuthRole = AuthRole::find()->where(['rule_id' => $AuthRule->id, 'role_id' => $user_id->role])->one(); if (!$AuthRole) { throw new Exception('您没有:' . $AuthRule->title . '的权限'); } if ($AuthRole->status == 0) { throw new Exception('您的'.$AuthRule->title.'权限已被禁用'); } return $AuthRule; } }