From 13c6b998146221a522a201c0dd0d210ce3d840e9 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Tue, 26 Nov 2013 16:28:55 -0500 Subject: [PATCH] Fixes #1331: Added support for using '*' to specify verb filters for all actions. --- framework/yii/web/VerbFilter.php | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/framework/yii/web/VerbFilter.php b/framework/yii/web/VerbFilter.php index c3235a6..e673bae 100644 --- a/framework/yii/web/VerbFilter.php +++ b/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 * allowed methods (e.g. GET, HEAD, PUT) as the value. * 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 = []; @@ -73,15 +87,24 @@ class VerbFilter extends Behavior { $action = $event->action->id; if (isset($this->actions[$action])) { - $verb = Yii::$app->getRequest()->getMethod(); - $allowed = array_map('strtoupper', $this->actions[$action]); - if (!in_array($verb, $allowed)) { - $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, 'Method Not Allowed. This url can only handle the following request methods: ' . implode(', ', $allowed)); - } + $verbs = $this->actions[$action]; + } elseif (isset($this->actions['*'])) { + $verbs = $this->actions['*']; + } else { + return $event->isValid; } + + $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; } }