Browse Source

Fixes #1331: Added support for using '*' to specify verb filters for all actions.

tags/2.0.0-beta
Qiang Xue 11 years ago
parent
commit
13c6b99814
  1. 31
      framework/yii/web/VerbFilter.php

31
framework/yii/web/VerbFilter.php

@ -51,6 +51,20 @@ class VerbFilter extends Behavior
* you add an entry with the action id as array key and an array of * you add an entry with the action id as array key and an array of
* allowed methods (e.g. GET, HEAD, PUT) as the value. * allowed methods (e.g. GET, HEAD, PUT) as the value.
* If an action is not listed all request methods are considered allowed. * If an action is not listed all request methods are considered allowed.
*
* You can use '*' to stand for all actions. When an action is explicitly
* specified, it takes precedence over the specification given by '*'.
*
* For example,
*
* ~~~
* [
* 'create' => ['get', 'post'],
* 'update' => ['get', 'put', 'post'],
* 'delete' => ['post', 'delete'],
* '*' => ['get'],
* ]
* ~~~
*/ */
public $actions = []; public $actions = [];
@ -73,15 +87,24 @@ class VerbFilter extends Behavior
{ {
$action = $event->action->id; $action = $event->action->id;
if (isset($this->actions[$action])) { if (isset($this->actions[$action])) {
$verbs = $this->actions[$action];
} elseif (isset($this->actions['*'])) {
$verbs = $this->actions['*'];
} else {
return $event->isValid;
}
$verb = Yii::$app->getRequest()->getMethod(); $verb = Yii::$app->getRequest()->getMethod();
$allowed = array_map('strtoupper', $this->actions[$action]); $allowed = array_map('strtoupper', $verbs);
if (!in_array($verb, $allowed)) { if (!in_array($verb, array_map('strtoupper', $verbs))) {
$event->isValid = false; $event->isValid = false;
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7
Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed)); Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed));
throw new HttpException(405, 'Method Not Allowed. This url can only handle the following request methods: ' . implode(', ', $allowed)); throw new HttpException(405, Yii::t('yii', 'Method Not Allowed. This url can only handle the following request methods: {methods}.', [
} 'methods' => implode(', ', $allowed),
]));
} }
return $event->isValid; return $event->isValid;
} }
} }

Loading…
Cancel
Save