Commit 13c6b998 by Qiang Xue

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

parent 1d0bc00c
...@@ -51,6 +51,20 @@ class VerbFilter extends Behavior ...@@ -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 ...@@ -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])) {
$verb = Yii::$app->getRequest()->getMethod(); $verbs = $this->actions[$action];
$allowed = array_map('strtoupper', $this->actions[$action]); } elseif (isset($this->actions['*'])) {
if (!in_array($verb, $allowed)) { $verbs = $this->actions['*'];
$event->isValid = false; } else {
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7 return $event->isValid;
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));
}
} }
$verb = Yii::$app->getRequest()->getMethod();
$allowed = array_map('strtoupper', $verbs);
if (!in_array($verb, array_map('strtoupper', $verbs))) {
$event->isValid = false;
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7
Yii::$app->getResponse()->getHeaders()->set('Allow', 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;
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment