Completed
Pull Request — master (#153)
by ignace nyamagana
01:55
created

UriTemplate   F

Complexity

Total Complexity 66

Size/Duplication

Total Lines 463
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 10
Bugs 0 Features 1
Metric Value
eloc 163
c 10
b 0
f 1
dl 0
loc 463
ccs 161
cts 161
cp 1
rs 3.12
wmc 66

18 Methods

Rating   Name   Duplication   Size   Complexity  
A getTemplate() 0 3 1
A normalizeValue() 0 15 6
A withTemplate() 0 12 2
A expandExpression() 0 19 4
A filterVariables() 0 7 1
A expandString() 0 12 4
A decodeReserved() 0 13 1
B expandVariable() 0 31 7
A parseVariableSpecification() 0 26 6
A withDefaultVariables() 0 11 2
A getVariableNames() 0 3 1
A expand() 0 20 3
A isAssoc() 0 3 2
A getDefaultVariables() 0 3 1
C expandList() 0 61 16
A __construct() 0 6 1
A filterTemplate() 0 7 3
A parseExpressions() 0 27 5

How to fix   Complexity   

Complex Class

Complex classes like UriTemplate often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UriTemplate, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * League.Uri (https://uri.thephpleague.com)
5
 *
6
 * (c) Ignace Nyamagana Butera <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace League\Uri;
15
16
use League\Uri\Contracts\UriException;
17
use League\Uri\Contracts\UriInterface;
18
use League\Uri\Contracts\UriTemplateInterface;
19
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
20
use function array_filter;
21
use function array_keys;
22
use function explode;
23
use function gettype;
24
use function implode;
25
use function in_array;
26
use function is_array;
27
use function is_bool;
28
use function is_scalar;
29
use function is_string;
30
use function method_exists;
31
use function preg_match;
32
use function preg_match_all;
33
use function preg_replace;
34
use function preg_replace_callback;
35
use function rawurlencode;
36
use function sprintf;
37
use function strpos;
38
use function substr;
39
use const ARRAY_FILTER_USE_KEY;
40
use const PREG_SET_ORDER;
41
42
/**
43
 * Expands URI templates.
44
 *
45
 * @link http://tools.ietf.org/html/rfc6570
46
 *
47
 * Based on GuzzleHttp\UriTemplate class which is removed from Guzzle7.
48
 * @see https://github.com/guzzle/guzzle/blob/6.5/src/UriTemplate.php
49
 */
50
final class UriTemplate implements UriTemplateInterface
51
{
52
    private const REGEXP_EXPRESSION = '/\{
53
        (?<expression>
54
            (?<operator>[\.\/;\?&\=,\!@\|\+#])?
55
            (?<variables>[^\}]*)
56
        )
57
    \}/x';
58
59
    private const REGEXP_VARSPEC = '/^
60
        (?<name>(?:[A-z0-9_\.]|%[0-9a-fA-F]{2})+)
61
        (?<modifier>\:(?<position>\d+)|\*)?
62
    $/x';
63
64
    private const RESERVED_OPERATOR = '=,!@|';
65
66
    private const OPERATOR_HASH_LOOKUP = [
67
        ''  => ['prefix' => '',  'joiner' => ',', 'query' => false],
68
        '+' => ['prefix' => '',  'joiner' => ',', 'query' => false],
69
        '#' => ['prefix' => '#', 'joiner' => ',', 'query' => false],
70
        '.' => ['prefix' => '.', 'joiner' => '.', 'query' => false],
71
        '/' => ['prefix' => '/', 'joiner' => '/', 'query' => false],
72
        ';' => ['prefix' => ';', 'joiner' => ';', 'query' => true],
73
        '?' => ['prefix' => '?', 'joiner' => '&', 'query' => true],
74
        '&' => ['prefix' => '&', 'joiner' => '&', 'query' => true],
75
    ];
76
77
    /**
78
     * @var string
79
     */
80
    private $template;
81
82
    /**
83
     * @var array<string,string|array>
84
     */
85
    private $defaultVariables;
86
87
    /**
88
     * @var string[]
89
     */
90
    private $variableNames;
91
92
    /**
93
     * @var array<string, array{operator: string, variables: array<array{name: string, modifier: string, position: string}>, joiner: string, prefix: string, query: bool}>
94
     */
95
    private $expressions;
96
97
    /**
98
     * @var UriInterface|null
99
     */
100
    private $uri;
101
102
    /**
103
     * @var array<string,string|array>
104
     */
105
    private $variables;
106
107
    /**
108
     * @param object|string $template a string or an object with the __toString method
109
     *
110
     * @throws \TypeError               if the template is not a string or an object with the __toString method
111
     * @throws TemplateCanNotBeExpanded if the template syntax is invalid
112
     */
113 244
    public function __construct($template, array $defaultVariables = [])
114
    {
115 244
        $this->template = $this->filterTemplate($template);
116 242
        $this->parseExpressions();
117
118 182
        $this->defaultVariables = $this->filterVariables($defaultVariables);
119 182
    }
120
121
    /**
122
     * @param object|string $template a string or an object with the __toString method
123
     *
124
     * @throws \TypeError if the template is not a string or an object with the __toString method
125
     */
126 244
    private function filterTemplate($template): string
127
    {
128 244
        if (!is_string($template) && !method_exists($template, '__toString')) {
129 2
            throw new \TypeError(sprintf('The template must be a string or a stringable object %s given.', gettype($template)));
130
        }
131
132 242
        return (string) $template;
133
    }
134
135
    /**
136
     * Parses the template expressions.
137
     *
138
     * @throws TemplateCanNotBeExpanded if the template syntax is invalid
139
     */
140 242
    private function parseExpressions(): void
141
    {
142 242
        $this->uri = null;
143
        /** @var string $remainder */
144 242
        $remainder = preg_replace(self::REGEXP_EXPRESSION, '', $this->template);
145 242
        if (false !== strpos($remainder, '{') || false !== strpos($remainder, '}')) {
146 6
            throw TemplateCanNotBeExpanded::dueToMalformedExpression($this->template);
147
        }
148
149 236
        preg_match_all(self::REGEXP_EXPRESSION, $this->template, $expressions, PREG_SET_ORDER);
150 236
        $this->expressions = [];
151 236
        $foundVariables = [];
152 236
        foreach ($expressions as $expression) {
153 232
            if (isset($this->expressions[$expression['expression']])) {
154 2
                continue;
155
            }
156
157
            /** @var array{expression:string, operator:string, variables:string} $expression */
158 232
            $expression = $expression + ['operator' => ''];
159 232
            [$parsedVariables, $foundVariables] = $this->parseVariableSpecification($expression, $foundVariables);
160 182
            $this->expressions[$expression['expression']] = [
161 182
                'operator' => $expression['operator'],
162 182
                'variables' => $parsedVariables,
163 182
            ] + self::OPERATOR_HASH_LOOKUP[$expression['operator']];
164
        }
165
166 182
        $this->variableNames = array_keys($foundVariables);
167 182
    }
168
169
    /**
170
     * Parses a variable specification in conformance to RFC6570.
171
     *
172
     * @param array{expression:string, operator:string, variables:string} $expression
173
     * @param array<string,int>                                           $foundVariables
174
     *
175
     * @throws TemplateCanNotBeExpanded if the expression does not conform to RFC6570
176
     *
177
     * @return array{0:array<array{name:string, modifier:string, position:string}>, 1:array<string,int>}
178
     */
179 232
    private function parseVariableSpecification(array $expression, array $foundVariables): array
180
    {
181 232
        $parsedVariableSpecification = [];
182 232
        if ('' !== $expression['operator'] && false !== strpos(self::RESERVED_OPERATOR, $expression['operator'])) {
183 6
            throw TemplateCanNotBeExpanded::dueToUsingReservedOperator($expression['expression']);
184
        }
185
186 226
        foreach (explode(',', $expression['variables']) as $varSpec) {
187 226
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $parsed)) {
188 48
                throw TemplateCanNotBeExpanded::dueToMalformedVariableSpecification($varSpec, $expression['expression']);
189
            }
190
191 186
            $parsed += ['modifier' => '', 'position' => ''];
192 186
            if ('' !== $parsed['position']) {
193 28
                $parsed['position'] = (int) $parsed['position'];
194 28
                $parsed['modifier'] = ':';
195
            }
196
197 186
            $foundVariables[$parsed['name']] = 1;
198 186
            $parsedVariableSpecification[] = $parsed;
199
        }
200
201
        /** @var array{0:array<array{name:string, modifier:string, position:string}>, 1:array<string,int>} $result */
202 182
        $result = [$parsedVariableSpecification, $foundVariables];
203
204 182
        return $result;
205
    }
206
207
    /**
208
     * Filter out the value whose key is not a valid variable name for the given template.
209
     */
210 182
    private function filterVariables(array $variables): array
211
    {
212
        $filter = function ($key): bool {
213 170
            return in_array($key, $this->variableNames, true);
214 182
        };
215
216 182
        return array_filter($variables, $filter, ARRAY_FILTER_USE_KEY);
217
    }
218
219
    /**
220
     * {@inheritDoc}
221
     */
222 4
    public function getTemplate(): string
223
    {
224 4
        return $this->template;
225
    }
226
227
    /**
228
     * {@inheritDoc}
229
     */
230 8
    public function getVariableNames(): array
231
    {
232 8
        return $this->variableNames;
233
    }
234
235
    /**
236
     * {@inheritDoc}
237
     */
238 2
    public function withTemplate($template): UriTemplateInterface
239
    {
240 2
        $template = $this->filterTemplate($template);
241 2
        if ($template === $this->template) {
242 2
            return $this;
243
        }
244
245 2
        $clone = clone $this;
246 2
        $clone->template = $template;
247 2
        $clone->parseExpressions();
248
249 2
        return $clone;
250
    }
251
252
    /**
253
     * {@inheritDoc}
254
     */
255 6
    public function getDefaultVariables(): array
256
    {
257 6
        return $this->defaultVariables;
258
    }
259
260
    /**
261
     * {@inheritDoc}
262
     */
263 2
    public function withDefaultVariables(array $defaultDefaultVariables): UriTemplateInterface
264
    {
265 2
        $defaultDefaultVariables = $this->filterVariables($defaultDefaultVariables);
266 2
        if ($defaultDefaultVariables === $this->defaultVariables) {
267 2
            return $this;
268
        }
269
270 2
        $clone = clone $this;
271 2
        $clone->defaultVariables = $defaultDefaultVariables;
272
273 2
        return $clone;
274
    }
275
276
    /**
277
     * @throws TemplateCanNotBeExpanded if the variable contains nested array values
278
     * @throws UriException             if the resulting expansion can not be converted to a UriInterface instance
279
     */
280 166
    public function expand(array $variables = []): UriInterface
281
    {
282 166
        if ([] === $this->expressions) {
283 2
            $this->uri = $this->uri ?? Uri::createFromString($this->template);
284
285 2
            return $this->uri;
286
        }
287
288 164
        $this->variables = $this->filterVariables($variables + $this->defaultVariables);
289 164
        if ([] === $this->variables) {
290
            /** @var string $uri */
291 2
            $uri = preg_replace(self::REGEXP_EXPRESSION, '', $this->template);
292
293 2
            return Uri::createFromString($uri);
294
        }
295
296
        /** @var string $uri */
297 162
        $uri = preg_replace_callback(self::REGEXP_EXPRESSION, [$this, 'expandExpression'], $this->template);
298
299 154
        return Uri::createFromString($uri);
300
    }
301
302
    /**
303
     * Expands the found expressions.
304
     *
305
     * @param array{expression:string, operator: string, variables:string} $foundExpression
306
     *
307
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
308
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
309
     */
310 162
    private function expandExpression(array $foundExpression): string
311
    {
312 162
        $expression = $this->expressions[$foundExpression['expression']];
313 162
        $joiner = $expression['joiner'];
314 162
        $useQuery = $expression['query'];
315
316 162
        $parts = [];
317
        /** @var array{name:string, modifier:string, position:string} $variable */
318 162
        foreach ($expression['variables'] as $variable) {
319 162
            $parts[] = $this->expandVariable($variable, $expression['operator'], $joiner, $useQuery);
320
        }
321
322 154
        $expanded = implode($joiner, array_filter($parts));
323 154
        $prefix = $expression['prefix'];
324 154
        if ('' !== $expanded && '' !== $prefix) {
325 102
            return $prefix.$expanded;
326
        }
327
328 62
        return $expanded;
329
    }
330
331
    /**
332
     * Expands an expression.
333
     *
334
     * @param array{name:string, modifier:string, position:string} $variable
335
     *
336
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
337
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
338
     */
339 162
    private function expandVariable(array $variable, string $operator, string $joiner, bool $useQuery): string
340
    {
341 162
        $expanded = '';
342 162
        if (!isset($this->variables[$variable['name']])) {
343 4
            return $expanded;
344
        }
345
346 160
        $variableValue = $this->normalizeValue($this->variables[$variable['name']]);
347 158
        $arguments = [$variableValue, $variable, $operator];
348 158
        $method = 'expandString';
349 158
        $actualQuery = $useQuery;
350 158
        if (is_array($variableValue)) {
351 86
            $arguments[] = $joiner;
352 86
            $arguments[] = $useQuery;
353 86
            $method = 'expandList';
354
        }
355
356 158
        $expanded = $this->$method(...$arguments);
357 154
        if (is_array($expanded)) {
358 80
            [$expanded, $actualQuery] = $expanded;
359
        }
360
361 154
        if (!$actualQuery) {
362 116
            return $expanded;
363
        }
364
365 46
        if ('&' !== $joiner && '' === $expanded) {
366 2
            return $variable['name'];
367
        }
368
369 46
        return $variable['name'].'='.$expanded;
370
    }
371
372
    /**
373
     * @param mixed $var the value to be expanded
374
     *
375
     * @throws \TypeError if the type is not supported
376
     *
377
     * @return string|array
378
     */
379 160
    private function normalizeValue($var)
380
    {
381 160
        if (is_array($var)) {
382 86
            return $var;
383
        }
384
385 88
        if (is_bool($var)) {
386 2
            return true === $var ? '1' : '0';
387
        }
388
389 86
        if (is_scalar($var) || method_exists($var, '__toString')) {
390 84
            return (string) $var;
391
        }
392
393 2
        throw new \TypeError(sprintf('The variables must be a scalar or a stringable object `%s` given', gettype($var)));
394
    }
395
396
    /**
397
     * Expands an expression using a string value.
398
     */
399 86
    private function expandString(string $value, array $variable, string $operator): string
400
    {
401 86
        if (':' === $variable['modifier']) {
402 22
            $value = substr($value, 0, $variable['position']);
403
        }
404
405 86
        $expanded = rawurlencode($value);
406 86
        if ('+' === $operator || '#' === $operator) {
407 32
            return $this->decodeReserved($expanded);
408
        }
409
410 62
        return $expanded;
411
    }
412
413
    /**
414
     * Expands an expression using a list of values.
415
     *
416
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
417
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
418
     *
419
     * @return array{0:string, 1:bool}
420
     */
421 86
    private function expandList(array $value, array $variable, string $operator, string $joiner, bool $useQuery): array
422
    {
423 86
        if ([] === $value) {
424 4
            return ['', false];
425
        }
426
427 82
        $isAssoc = $this->isAssoc($value);
428 82
        $pairs = [];
429 82
        if (':' === $variable['modifier']) {
430 4
            throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($variable['name']);
431
        }
432
433
        /** @var string $key */
434 78
        foreach ($value as $key => $var) {
435 78
            if ($isAssoc) {
436 38
                if (is_array($var)) {
437 2
                    throw TemplateCanNotBeExpanded::dueToNestedListOfValue($key);
438
                }
439
440 36
                $key = rawurlencode((string) $key);
441
            }
442
443 76
            $var = rawurlencode((string) $var);
444 76
            if ('+' === $operator || '#' === $operator) {
445 16
                $var = $this->decodeReserved($var);
446
            }
447
448 76
            if ('*' === $variable['modifier']) {
449 44
                if ($isAssoc) {
450 20
                    $var = $key.'='.$var;
451 24
                } elseif ($key > 0 && $useQuery) {
452 12
                    $var = $variable['name'].'='.$var;
453
                }
454
            }
455
456 76
            $pairs[$key] = $var;
457
        }
458
459 76
        if ('*' === $variable['modifier']) {
460 44
            if ($isAssoc) {
461
                // Don't prepend the value name when using the explode
462
                // modifier with an associative array.
463 20
                $useQuery = false;
464
            }
465
466 44
            return [implode($joiner, $pairs), $useQuery];
467
        }
468
469 38
        if ($isAssoc) {
470
            // When an associative array is encountered and the
471
            // explode modifier is not set, then the result must be
472
            // a comma separated list of keys followed by their
473
            // respective values.
474 16
            foreach ($pairs as $offset => &$data) {
475 16
                $data = $offset.','.$data;
476
            }
477
478 16
            unset($data);
479
        }
480
481 38
        return [implode(',', $pairs), $useQuery];
482
    }
483
484
    /**
485
     * Determines if an array is associative.
486
     *
487
     * This makes the assumption that input arrays are sequences or hashes.
488
     * This assumption is a tradeoff for accuracy in favor of speed, but it
489
     * should work in almost every case where input is supplied for a URI
490
     * template.
491
     */
492 82
    private function isAssoc(array $array): bool
493
    {
494 82
        return [] !== $array && 0 !== array_keys($array)[0];
495
    }
496
497
    /**
498
     * Removes percent encoding on reserved characters (used with + and # modifiers).
499
     */
500 48
    private function decodeReserved(string $str): string
501
    {
502 48
        static $delimiters = [
503
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
504
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
505
        ];
506
507 48
        static $delimiters_encoded = [
508
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
509
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
510
        ];
511
512 48
        return str_replace($delimiters_encoded, $delimiters, $str);
513
    }
514
}
515