forked from deepziyu/yii2-fast-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathController.php
303 lines (277 loc) · 8.35 KB
/
Controller.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
<?php
namespace deepziyu\yii\rest;
use Yii;
use yii\data\ActiveDataProvider;
use yii\base\InlineAction;
use yii\data\Pagination;
use yii\web\Request;
use yii\web\BadRequestHttpException;
use yii\validators\Validator;
use yii\base\DynamicModel;
use yii\base\Model;
use deepziyu\yii\rest\ApiException;
use yii\web\User;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\auth\HttpBearerAuth;
/**
* Class Controller
* @property Request $request The request component.
* @property User $user The user model.
* @property boolean $enableAuth 是否开启用户认证
* @package deepziyu\yii\rest
*/
class Controller extends \yii\rest\Controller
{
public $request;
public $user;
public $enableCsrfValidation = false;
public $enableAuth = false;
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
public function init()
{
parent::init();
$this->user = Yii::$app->user->identity;
$this->request = Yii::$app->getRequest();
}
public function behaviors()
{
$behaviors = parent::behaviors();
if($this->enableAuth){
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBasicAuth::className(),
QueryParamAuth::className(),
HttpBearerAuth::className(),
],
'optional' => $this->authOptional()
];
}
return $behaviors;
}
/**
* 默认的action为空
* @return array
*/
public function actions()
{
return [];
}
/**
* 参数的检验规则
* 次方法返回的预设规则将在beforeAction事件中被校验
* - 简单示例:
* ```php
* return [
* //设置 indexAction()的rule
* 'index' => [
* ['param1','string','min'=>1,'max'=>6],
* ['param2','integer'],
* ];
* ];
* ```
* - 可以用 * 号通配所有的actions
* ```php
* return [
* '*' => [
* ['user_id','integer']//所有的user_id都将被IntegerVa校验
* ];
* ];
* ```
* - 可以 指定到某个 model 的 rules
* ```php
* return [
* //设置并唯一用 YouModel::rules() 检验路由 index
* 'index' => 'app\modes\YouModel';
* ];
* ```
* - 更多检验器的设置方法见
* http://www.yiichina.com/doc/guide/2.0/input-
*
* @return array
*/
public function rules()
{
return [];
}
/**
* 不需要验证用户令牌actionID
* 当$this->$enableAuth == true时,此方法定义除外,所有的ation将被验证用户认证令牌是否正确。
* @return array
*/
public function authOptional()
{
return [];
}
/**
* 获取api-config
* @return mixed
*/
public static function getConfig()
{
return require(__DIR__ . '/api.config.php');
}
/**
* action参数注入
* @param \yii\base\Action $action
* @param array $params
* @return array
* @throws BadRequestHttpException
* @throws ApiException
*/
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$params = array_merge($params, $this->request->getBodyParams());
$rule = $this->getRule($action);
if ($rule) {
if($rule instanceof Model){
$model = $rule;
$model->load($params,'');
}else{
$model = DynamicModel::validateData($params, $rule);
}
$model->validate();
if ($model->hasErrors()) {
throw new ApiException(422, $model);
}
$params = array_replace($params, $model->getAttributes());
}
$args = [];
$missing = [];
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (array_key_exists($name, $params)) {
if ($param->isArray()) {
$args[] = (array)$params[$name];
} elseif (!is_array($params[$name])) {
$args[] = $params[$name];
} else {
throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
'param' => $name,
]));
}
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $params[$name] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
if (!empty($missing)) {
throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
'params' => implode(', ', $missing),
]));
}
$this->actionParams = $params;
return $args;
}
/**
* 获取action对应的rule规则
* @param \yii\base\Action $action $action
* @return array|\yii\base\Model
*/
protected function getRule($action)
{
$rules = $this->rules();
$commonRule = isset($rules['*']) ? $rules['*'] : [];
$uniqueRule = isset($rules[$action->id]) ? $rules[$action->id] : [];
if (is_string($uniqueRule) || (is_array($uniqueRule) && isset($uniqueRule['class']))) {
/* @var $model \yii\base\Model */
$model = Yii::createObject($uniqueRule);
//$uniqueRule = $model->rules();
return $model;
}
return array_merge($commonRule, $uniqueRule);
}
/**
* 设置expand
* 详见 \yii\base\Model::toArray() 的介绍
* @param Model $expand
*/
public function setExpand($expand)
{
$params = Yii::$app->request->getQueryParams();
if (!is_array($expand)) {
$expand = [$expand];
}
if (isset($params['expand'])) {
$params['expand'] .= ',' . implode(',', $expand);
} else {
$params['expand'] = implode(',', $expand);
}
Yii::$app->request->setQueryParams($params);
}
/**
* 简单构造一个 DataProvider 用以返回数据
* @param $query
* @return ActiveDataProvider
*/
public function getActiveDataProvider($query)
{
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if ($dataProvider->models) {
foreach ($dataProvider->models as $key => $m) {
if (isset($m->_id)) {
$m->_id = (string)$m->_id;
}else{
break;
}
}
}
return $dataProvider;
}
/**
* @param $action
* @return bool
* @throws Exception
* @throws \yii\web\BadRequestHttpException
*/
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
/**
* 记录日志,比如
Yii::info('请求地址:' . $this->request->absoluteUrl, 'request');
Yii::info('请求数据:' . \yii\helpers\Json::encode($this->request->getBodyParams()), 'request');
*/
} else {
return false;
}
return true;
}
/**
* @param \yii\base\Action $action
* @param mixed $result
* @return array|mixed
* @throws \deepziyu\yii\rest\ApiException
*/
public function afterAction($action, $result)
{
$response = Yii::$app->getResponse();
$response->format = 'json';
if ($result instanceof Model && $result->hasErrors()) {
throw new \deepziyu\yii\rest\ApiException(422, $result);
}
$result = parent::afterAction($action, $result);
$code = $response->getStatusCode();
$result = [
'code' => $code,
'data' => $result,
'message' => $response->statusText
];
//记录日志比如:
//Yii::info('请求返回结果:' . \yii\helpers\Json::encode($result), 'response');
return $result;
}
}