UrlRule::createRules()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 4
nop 0
dl 0
loc 16
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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|null 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((string)$this->prefix, '/');
162
163 11
        parent::init();
164
    }
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) {
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
        $config['suffix'] = $this->suffix;
209
210 11
        return Yii::createObject($config);
211
    }
212
213
    /**
214
     * {@inheritdoc}
215
     */
216 1
    public function parseRequest($manager, $request)
217
    {
218 1
        $pathInfo = $request->getPathInfo();
219
        if (
220 1
            $this->prefix !== ''
221 1
            && strpos($this->prefix, '<') === false
0 ignored issues
show
Bug introduced by
It seems like $this->prefix can also be of type null; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

221
            && strpos(/** @scrutinizer ignore-type */ $this->prefix, '<') === false
Loading history...
222 1
            && strpos($pathInfo . '/', $this->prefix . '/') !== 0
223
        ) {
224 1
            return false;
225
        }
226
227 1
        foreach ($this->rules as $urlName => $rules) {
228 1
            if (strpos($pathInfo, $urlName) !== false) {
229 1
                foreach ($rules as $rule) {
230
                    /** @var WebUrlRule $rule */
231 1
                    $result = $rule->parseRequest($manager, $request);
232 1
                    if (YII_DEBUG) {
233 1
                        Yii::debug([
234 1
                            'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
235 1
                            'match' => $result !== false,
236 1
                            'parent' => self::class,
237 1
                        ], __METHOD__);
238
                    }
239 1
                    if ($result !== false) {
240 1
                        return $result;
241
                    }
242
                }
243
            }
244
        }
245
246 1
        return false;
247
    }
248
249
    /**
250
     * {@inheritdoc}
251
     */
252 9
    public function createUrl($manager, $route, $params)
253
    {
254 9
        $this->createStatus = WebUrlRule::CREATE_STATUS_SUCCESS;
255 9
        foreach ($this->controller as $urlName => $controller) {
256 9
            if (strpos($route, $controller) !== false) {
257
                /** @var UrlRuleInterface[] $rules */
258 9
                $rules = $this->rules[$urlName];
259 9
                $url = $this->iterateRules($rules, $manager, $route, $params);
260 9
                if ($url !== false) {
261 9
                    return $url;
262
                }
263
            } else {
264 4
                $this->createStatus |= WebUrlRule::CREATE_STATUS_ROUTE_MISMATCH;
265
            }
266
        }
267
268 9
        if ($this->createStatus === WebUrlRule::CREATE_STATUS_SUCCESS) {
269
            // create status was not changed - there is no rules configured
270
            $this->createStatus = WebUrlRule::CREATE_STATUS_PARSING_ONLY;
271
        }
272
273 9
        return false;
274
    }
275
}
276