Files
xk-api-yii/admin/components/BaseAdminController.php

381 lines
11 KiB
PHP
Raw Normal View History

2024-09-19 11:32:39 +08:00
<?php
namespace admin\components;
use admin\behaviors\PageFilterBehavior;
use admin\components\UI\Event;
use admin\foundation\Cors;
use admin\models\Admin;
use admin\models\Config;
use common\helpers\FakeId;
use common\models\AuthRole;
use common\models\AuthRule;
use Yii;
use yii\base\Arrayable;
use yii\base\DynamicModel;
use yii\base\InvalidArgumentException;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\data\DataProviderInterface;
use yii\data\Pagination;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use common\core\TokenAuth;
use yii\base\Controller;
use yii\web\Response;
use function Symfony\Component\String\b;
/**
* 这里注意是继承 yii\rest\ActiveController 因为源码中已经帮我们实现了index/update等方法
* 以及其访问规则verbs()等,
* 其他可参考http://www.yiichina.com/doc/guide/2.0/rest-controllers
*
* 权限采用最简单的QueryParamAuth方式
* 用户角色权限比较复杂,这里没有做
*
* @package api\modules\v1\controllers
*/
class BaseAdminController extends Controller
{
public $field = [];//重定义格式
public $listkey = 'list';
public $pagekey = 'pagination';
public $extend_result = [];
public $layout = 'arco.layout.php';
public $enableCsrfValidation = false;
//beforeAction 注入
protected $mallId;//商城ID
protected $supplierId;//供应商ID
// 不需进行token权限认证的方法
public $optional = [];
public $user;
/**
* ---------------------------------------
* 构造方法
*
* @throws \Throwable
* @throws \yii\base\InvalidConfigException
* @author hlf <phphome@qq.com> 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 <phphome@qq.com> 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;
}
}