Completed
Push — unique-validator-fix ( 963824...d331b7 )
by Alexander
29:51 queued 14:14
created

UrlRule::createUrl()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0144

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 11
cts 12
cp 0.9167
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 13
nc 7
nop 3
crap 5.0144
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\rest;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\Inflector;
13
use yii\web\CompositeUrlRule;
14
use yii\web\UrlRule as WebUrlRule;
15
use yii\web\UrlRuleInterface;
16
17
/**
18
 * UrlRule is provided to simplify the creation of URL rules for RESTful API support.
19
 *
20
 * The simplest usage of UrlRule is to declare a rule like the following in the application configuration,
21
 *
22
 * ```php
23
 * [
24
 *     'class' => 'yii\rest\UrlRule',
25
 *     'controller' => 'user',
26
 * ]
27
 * ```
28
 *
29
 * The above code will create a whole set of URL rules supporting the following RESTful API endpoints:
30
 *
31
 * - `'PUT,PATCH users/<id>' => 'user/update'`: update a user
32
 * - `'DELETE users/<id>' => 'user/delete'`: delete a user
33
 * - `'GET,HEAD users/<id>' => 'user/view'`: return the details/overview/options of a user
34
 * - `'POST users' => 'user/create'`: create a new user
35
 * - `'GET,HEAD users' => 'user/index'`: return a list/overview/options of users
36
 * - `'users/<id>' => 'user/options'`: process all unhandled verbs of a user
37
 * - `'users' => 'user/options'`: process all unhandled verbs of user collection
38
 *
39
 * You may configure [[only]] and/or [[except]] to disable some of the above rules.
40
 * You may configure [[patterns]] to completely redefine your own list of rules.
41
 * You may configure [[controller]] with multiple controller IDs to generate rules for all these controllers.
42
 * For example, the following code will disable the `delete` rule and generate rules for both `user` and `post` controllers:
43
 *
44
 * ```php
45
 * [
46
 *     'class' => 'yii\rest\UrlRule',
47
 *     'controller' => ['user', 'post'],
48
 *     'except' => ['delete'],
49
 * ]
50
 * ```
51
 *
52
 * The property [[controller]] is required and should represent one or multiple controller IDs.
53
 * Each controller ID should be prefixed with the module ID if the controller is within a module.
54
 * The controller ID used in the pattern will be automatically pluralized (e.g. `user` becomes `users`
55
 * as shown in the above examples).
56
 *
57
 * For more details and usage information on UrlRule, see the [guide article on rest routing](guide:rest-routing).
58
 *
59
 * @author Qiang Xue <[email protected]>
60
 * @since 2.0
61
 */
62
class UrlRule extends CompositeUrlRule
63
{
64
    /**
65
     * @var string the common prefix string shared by all patterns.
66
     */
67
    public $prefix;
68
    /**
69
     * @var string the suffix that will be assigned to [[\yii\web\UrlRule::suffix]] for every generated rule.
70
     */
71
    public $suffix;
72
    /**
73
     * @var string|array the controller ID (e.g. `user`, `post-comment`) that the rules in this composite rule
74
     * are dealing with. It should be prefixed with the module ID if the controller is within a module (e.g. `admin/user`).
75
     *
76
     * By default, the controller ID will be pluralized automatically when it is put in the patterns of the
77
     * generated rules. If you want to explicitly specify how the controller ID should appear in the patterns,
78
     * you may use an array with the array key being as the controller ID in the pattern, and the array value
79
     * the actual controller ID. For example, `['u' => 'user']`.
80
     *
81
     * You may also pass multiple controller IDs as an array. If this is the case, this composite rule will
82
     * generate applicable URL rules for EVERY specified controller. For example, `['user', 'post']`.
83
     */
84
    public $controller;
85
    /**
86
     * @var array list of acceptable actions. If not empty, only the actions within this array
87
     * will have the corresponding URL rules created.
88
     * @see patterns
89
     */
90
    public $only = [];
91
    /**
92
     * @var array list of actions that should be excluded. Any action found in this array
93
     * will NOT have its URL rules created.
94
     * @see patterns
95
     */
96
    public $except = [];
97
    /**
98
     * @var array patterns for supporting extra actions in addition to those listed in [[patterns]].
99
     * The keys are the patterns and the values are the corresponding action IDs.
100
     * These extra patterns will take precedence over [[patterns]].
101
     */
102
    public $extraPatterns = [];
103
    /**
104
     * @var array list of tokens that should be replaced for each pattern. The keys are the token names,
105
     * and the values are the corresponding replacements.
106
     * @see patterns
107
     */
108
    public $tokens = [
109
        '{id}' => '<id:\\d[\\d,]*>',
110
    ];
111
    /**
112
     * @var array list of possible patterns and the corresponding actions for creating the URL rules.
113
     * The keys are the patterns and the values are the corresponding actions.
114
     * The format of patterns is `Verbs Pattern`, where `Verbs` stands for a list of HTTP verbs separated
115
     * by comma (without space). If `Verbs` is not specified, it means all verbs are allowed.
116
     * `Pattern` is optional. It will be prefixed with [[prefix]]/[[controller]]/,
117
     * and tokens in it will be replaced by [[tokens]].
118
     */
119
    public $patterns = [
120
        'PUT,PATCH {id}' => 'update',
121
        'DELETE {id}' => 'delete',
122
        'GET,HEAD {id}' => 'view',
123
        'POST' => 'create',
124
        'GET,HEAD' => 'index',
125
        '{id}' => 'options',
126
        '' => 'options',
127
    ];
128
    /**
129
     * @var array the default configuration for creating each URL rule contained by this rule.
130
     */
131
    public $ruleConfig = [
132
        'class' => 'yii\web\UrlRule',
133
    ];
134
    /**
135
     * @var bool whether to automatically pluralize the URL names for controllers.
136
     * If true, a controller ID will appear in plural form in URLs. For example, `user` controller
137
     * will appear as `users` in URLs.
138
     * @see controller
139
     */
140
    public $pluralize = true;
141
142
143
    /**
144
     * @inheritdoc
145
     */
146 11
    public function init()
147
    {
148 11
        if (empty($this->controller)) {
149
            throw new InvalidConfigException('"controller" must be set.');
150
        }
151
152 11
        $controllers = [];
153 11
        foreach ((array) $this->controller as $urlName => $controller) {
154 11
            if (is_int($urlName)) {
155 11
                $urlName = $this->pluralize ? Inflector::pluralize($controller) : $controller;
156
            }
157 11
            $controllers[$urlName] = $controller;
158
        }
159 11
        $this->controller = $controllers;
160
161 11
        $this->prefix = trim($this->prefix, '/');
162
163 11
        parent::init();
164 11
    }
165
166
    /**
167
     * @inheritdoc
168
     */
169 11
    protected function createRules()
170
    {
171 11
        $only = array_flip($this->only);
172 11
        $except = array_flip($this->except);
173 11
        $patterns = $this->extraPatterns + $this->patterns;
174 11
        $rules = [];
175 11
        foreach ($this->controller as $urlName => $controller) {
0 ignored issues
show
Bug introduced by
The expression $this->controller of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
176 11
            $prefix = trim($this->prefix . '/' . $urlName, '/');
177 11
            foreach ($patterns as $pattern => $action) {
178 11
                if (!isset($except[$action]) && (empty($only) || isset($only[$action]))) {
179 11
                    $rules[$urlName][] = $this->createRule($pattern, $prefix, $controller . '/' . $action);
180
                }
181
            }
182
        }
183
184 11
        return $rules;
185
    }
186
187
    /**
188
     * Creates a URL rule using the given pattern and action.
189
     * @param string $pattern
190
     * @param string $prefix
191
     * @param string $action
192
     * @return UrlRuleInterface
193
     */
194 11
    protected function createRule($pattern, $prefix, $action)
195
    {
196 11
        $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
197 11
        if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
198 11
            $verbs = explode(',', $matches[1]);
199 11
            $pattern = isset($matches[4]) ? $matches[4] : '';
200
        } else {
201 11
            $verbs = [];
202
        }
203
204 11
        $config = $this->ruleConfig;
205 11
        $config['verb'] = $verbs;
206 11
        $config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
207 11
        $config['route'] = $action;
208 11
        if (!empty($verbs) && !in_array('GET', $verbs)) {
209 11
            $config['mode'] = WebUrlRule::PARSING_ONLY;
210
        }
211 11
        $config['suffix'] = $this->suffix;
212
213 11
        return Yii::createObject($config);
214
    }
215
216
    /**
217
     * @inheritdoc
218
     */
219 1
    public function parseRequest($manager, $request)
220
    {
221 1
        $pathInfo = $request->getPathInfo();
222 1
        foreach ($this->rules as $urlName => $rules) {
223 1
            if (strpos($pathInfo, $urlName) !== false) {
224 1
                foreach ($rules as $rule) {
0 ignored issues
show
Bug introduced by
The expression $rules of type object<yii\web\UrlRuleInterface> is not traversable.
Loading history...
225
                    /* @var $rule WebUrlRule */
226 1
                    $result = $rule->parseRequest($manager, $request);
227 1
                    if (YII_DEBUG) {
228 1
                        Yii::trace([
229 1
                            'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
230
                            'match' => $result !== false,
231 1
                            'parent' => self::className(),
232 1
                        ], __METHOD__);
233
                    }
234 1
                    if ($result !== false) {
235 1
                        return $result;
236
                    }
237
                }
238
            }
239
        }
240
241 1
        return false;
242
    }
243
244
    /**
245
     * @inheritdoc
246
     */
247 9
    public function createUrl($manager, $route, $params)
248
    {
249 9
        $this->createStatus = WebUrlRule::CREATE_STATUS_SUCCESS;
250 9
        foreach ($this->controller as $urlName => $controller) {
0 ignored issues
show
Bug introduced by
The expression $this->controller of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
251 9
            if (strpos($route, $controller) !== false) {
252
                /* @var $rules UrlRuleInterface[] */
253 9
                $rules = $this->rules[$urlName];
254 9
                $url = $this->iterateRules($rules, $manager, $route, $params);
255 9
                if ($url !== false) {
256 9
                    return $url;
257
                }
258
            } else {
259 4
                $this->createStatus |= WebUrlRule::CREATE_STATUS_ROUTE_MISMATCH;
260
            }
261
        }
262
263 9
        if ($this->createStatus === WebUrlRule::CREATE_STATUS_SUCCESS) {
264
            // create status was not changed - there is no rules configured
265
            $this->createStatus = WebUrlRule::CREATE_STATUS_PARSING_ONLY;
266
        }
267 9
        return false;
268
    }
269
}
270