Completed
Pull Request — master (#153)
by ignace nyamagana
02:17
created

UriTemplate::expandList()   C

Complexity

Conditions 16
Paths 71

Size

Total Lines 61
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 16

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 16
eloc 29
c 3
b 0
f 0
nc 71
nop 5
dl 0
loc 61
ccs 30
cts 30
cp 1
crap 16
rs 5.5666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Exceptions\SyntaxError;
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
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{pattern:string, 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 array{noExpression:UriInterface|null, noVariables:UriInterface|null}
99
     */
100
    private $cache;
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 6
    public function __construct($template, array $defaultVariables = [])
114
    {
115 6
        $this->template = $this->filterTemplate($template);
116
117 4
        $this->parseExpressions();
118
119 4
        $this->defaultVariables = $this->filterVariables($defaultVariables);
120 4
    }
121
122
    /**
123
     * {@inheritDoc}
124
     */
125 2
    public static function __set_state(array $properties): self
126
    {
127 2
        return new self($properties['template'], $properties['defaultVariables']);
128
    }
129
130
    /**
131
     * @param object|string $template a string or an object with the __toString method
132
     *
133
     * @throws \TypeError if the template is not a string or an object with the __toString method
134
     */
135 4
    private function filterTemplate($template): string
136
    {
137 4
        if (!is_string($template) && !method_exists($template, '__toString')) {
138 2
            throw new \TypeError(sprintf('The template must be a string or a stringable object %s given.', gettype($template)));
139
        }
140
141 2
        return (string) $template;
142
    }
143
144
    /**
145
     * Parses the template expressions.
146
     *
147
     * @throws SyntaxError if the template syntax is invalid
148
     */
149 70
    private function parseExpressions(): void
150
    {
151 70
        $this->cache = ['noExpression' => null, 'noVariables' => null];
152
        /** @var string $remainder */
153 70
        $remainder = preg_replace(self::REGEXP_EXPRESSION, '', $this->template);
154 70
        if (false !== strpos($remainder, '{') || false !== strpos($remainder, '}')) {
155 6
            throw new SyntaxError('The submitted template "'.$this->template.'" contains invalid expressions.');
156
        }
157
158 64
        preg_match_all(self::REGEXP_EXPRESSION, $this->template, $expressions, PREG_SET_ORDER);
159 64
        $this->expressions = [];
160 64
        $foundVariables = [];
161 64
        foreach ($expressions as $expression) {
162 62
            if (isset($this->expressions[$expression['expression']])) {
163 2
                continue;
164
            }
165
166
            /** @var array{expression:string, operator:string, variables:string, pattern:string} $expression */
167 62
            $expression = $expression + ['operator' => '', 'pattern' => '{'.$expression['expression'].'}'];
168 62
            [$parsedVariables, $foundVariables] = $this->parseVariableSpecification($expression, $foundVariables);
169 12
            $this->expressions[$expression['expression']] = ['variables' => $parsedVariables] + $expression + self::OPERATOR_HASH_LOOKUP[$expression['operator']];
170
        }
171
172 10
        $this->variableNames = array_keys($foundVariables);
173 10
    }
174
175
    /**
176
     * Parses a variable specification in conformance to RFC6570.
177
     *
178
     * @param array{expression:string, operator:string, variables:string, pattern:string} $expression
179
     * @param array<string,int>                                                           $foundVariables
180
     *
181
     * @throws SyntaxError if the expression does not conform to RFC6570
182
     *
183
     * @return array{0:array<array{name:string, modifier:string, position:string}>, 1:array<string,int>}
184
     */
185 60
    private function parseVariableSpecification(array $expression, array $foundVariables): array
186
    {
187 60
        $parsedVariableSpecification = [];
188 60
        if ('' !== $expression['operator'] && false !== strpos(self::RESERVED_OPERATOR, $expression['operator'])) {
189 6
            throw new SyntaxError('The operator used in the expression "'.$expression['pattern'].'" is reserved.');
190
        }
191
192 54
        foreach (explode(',', $expression['variables']) as $varSpec) {
193 54
            if ('' === $varSpec) {
194 2
                throw new SyntaxError('No variable specification was included in the expression "'.$expression['pattern'].'".');
195
            }
196
197 52
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $parsed)) {
198 46
                throw new SyntaxError('The variable specification "'.$varSpec.'" included in the expression "'.$expression['pattern'].'" is invalid.');
199
            }
200
201 14
            $parsed += ['modifier' => '', 'position' => ''];
202 14
            if ('' !== $parsed['position']) {
203 2
                $parsed['position'] = (int) $parsed['position'];
204 2
                $parsed['modifier'] = ':';
205
            }
206
207 14
            $foundVariables[$parsed['name']] = 1;
208 14
            $parsedVariableSpecification[] = $parsed;
209
        }
210
211
        /** @var array{0:array<array{name:string, modifier:string, position:string}>, 1:array<string,int>} $result */
212 10
        $result = [$parsedVariableSpecification, $foundVariables];
213
214 10
        return $result;
215
    }
216
217
    /**
218
     * Filter out the value whose key is not a valid variable name for the given template.
219
     */
220 8
    private function filterVariables(array $variables): array
221
    {
222
        $filter = function ($key): bool {
223 8
            return in_array($key, $this->variableNames, true);
224 8
        };
225
226 8
        return array_filter($variables, $filter, ARRAY_FILTER_USE_KEY);
227
    }
228
229
    /**
230
     * The template string.
231
     */
232 2
    public function getTemplate(): string
233
    {
234 2
        return $this->template;
235
    }
236
237
    /**
238
     * Returns the names of the variables in the template, in order.
239
     *
240
     * @return string[]
241
     */
242 8
    public function getVariableNames(): array
243
    {
244 8
        return $this->variableNames;
245
    }
246
247
    /**
248
     * Returns a new instance with the updated template.
249
     *
250
     * This method MUST retain the state of the current instance, and return
251
     * an instance that contains the modified template value.
252
     *
253
     * @param object|string $template a string or an object with the __toString method
254
     *
255
     * @throws SyntaxError if the new template is invalid
256
     */
257 2
    public function withTemplate($template): self
258
    {
259 2
        $template = $this->filterTemplate($template);
260 2
        if ($template === $this->template) {
261 2
            return $this;
262
        }
263
264 2
        $clone = clone $this;
265 2
        $clone->template = $template;
266 2
        $clone->parseExpressions();
267
268 2
        return $clone;
269
    }
270
271
    /**
272
     * Returns the default values used to expand the template.
273
     *
274
     * The returned list only contains variables whose name is part of the current template.
275
     *
276
     * @return array<string,string|array>
277
     */
278 2
    public function getDefaultVariables(): array
279
    {
280 2
        return $this->defaultVariables;
281
    }
282
283
    /**
284
     * Returns a new instance with the updated default variables.
285
     *
286
     * This method MUST retain the state of the current instance, and return
287
     * an instance that contains the modified default variables.
288
     *
289
     * If present, variables whose name is not part of the current template
290
     * possible variable names are removed.
291
     *
292
     */
293 2
    public function withDefaultVariables(array $defaultDefaultVariables): self
294
    {
295 2
        $defaultDefaultVariables = $this->filterVariables($defaultDefaultVariables);
296 2
        if ($defaultDefaultVariables === $this->defaultVariables) {
297 2
            return $this;
298
        }
299
300 2
        $clone = clone $this;
301 2
        $clone->defaultVariables = $defaultDefaultVariables;
302
303 2
        return $clone;
304
    }
305
306
    /**
307
     * @throws TemplateCanNotBeExpanded if the variable contains nested array values
308
     * @throws UriException             if the resulting expansion can not be converted to a UriInterface instance
309
     */
310 154
    public function expand(array $variables = []): UriInterface
311
    {
312 154
        if ([] === $this->expressions) {
313 2
            $this->cache['noExpression'] = $this->cache['noExpression'] ?? Uri::createFromString($this->template);
314
315 2
            return $this->cache['noExpression'];
316
        }
317
318 152
        $this->variables = $this->filterVariables($variables) + $this->defaultVariables;
319 152
        if ([] === $this->variables) {
320 2
            $this->cache['noVariables'] = $this->cache['noVariables'] ?? Uri::createFromString(
321 2
                preg_replace(self::REGEXP_EXPRESSION, '', $this->template)
322
            );
323
324 2
            return $this->cache['noVariables'];
325
        }
326
327
        /** @var string $uri */
328 150
        $uri = preg_replace_callback(self::REGEXP_EXPRESSION, [$this, 'expandExpression'], $this->template);
329
330 150
        return Uri::createFromString($uri);
331
    }
332
333
    /**
334
     * Expands a single expression.
335
     *
336
     * @param array{expression:string, operator: string, variables:string} $foundExpression
337
     *
338
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
339
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
340
     */
341 146
    private function expandExpression(array $foundExpression): string
342
    {
343 146
        $expression = $this->expressions[$foundExpression['expression']];
344 146
        $joiner = $expression['joiner'];
345 146
        $useQuery = $expression['query'];
346
347 146
        $parts = [];
348
        /** @var array{name:string, modifier:string, position:string} $variable */
349 146
        foreach ($expression['variables'] as $variable) {
350 146
            $parts[] = $this->expandVariable($variable, $expression['operator'], $joiner, $useQuery);
351
        }
352
353
        $nullFilter = static function ($value): bool {
354 146
            return null !== $value && '' !== $value;
355 146
        };
356
357 146
        $expanded = implode($joiner, array_filter($parts, $nullFilter));
358 146
        $prefix = $expression['prefix'];
359 146
        if ('' !== $expanded && '' !== $prefix) {
360 96
            return $prefix.$expanded;
361
        }
362
363 54
        return $expanded;
364
    }
365
366
    /**
367
     * Expands an expression.
368
     *
369
     * @param array{name:string, modifier:string, position:string} $variable
370
     *
371
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
372
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
373
     */
374 146
    private function expandVariable(array $variable, string $operator, string $joiner, bool $useQuery): string
375
    {
376 146
        $expanded = '';
377 146
        if (!isset($this->variables[$variable['name']])) {
378 4
            return $expanded;
379
        }
380
381 144
        $value = $this->normalizeValue($this->variables[$variable['name']]);
382 144
        $arguments = [$value, $variable, $operator];
383 144
        $method = 'expandString';
384 144
        $actualQuery = $useQuery;
385 144
        if (is_array($value)) {
386 74
            $arguments[] = $joiner;
387 74
            $arguments[] = $useQuery;
388 74
            $method = 'expandList';
389
        }
390
391 144
        $expanded = $this->$method(...$arguments);
392 144
        if (is_array($expanded)) {
393 74
            [$expanded, $actualQuery] = $expanded;
394
        }
395
396 144
        if (!$actualQuery) {
397 108
            return $expanded;
398
        }
399
400 38
        if ('&' !== $joiner && '' === $expanded) {
401 2
            return $variable['name'];
402
        }
403
404 38
        return $variable['name'].'='.$expanded;
405
    }
406
407
    /**
408
     * @param mixed $value the value to be expanded
409
     *
410
     * @throws \TypeError if the type is not supported
411
     *
412
     * @return string|array
413
     */
414 8
    private function normalizeValue($value)
415
    {
416 8
        if (is_array($value)) {
417 4
            return $value;
418
        }
419
420 8
        if (is_bool($value)) {
421 2
            return true === $value ? '1' : '0';
422
        }
423
424 6
        if (is_scalar($value) || method_exists($value, '__toString')) {
425 4
            return (string) $value;
426
        }
427
428 2
        throw new \TypeError(sprintf('The variables must be a scalar or a stringable object `%s` given', gettype($value)));
429
    }
430
431
    /**
432
     * Expands an expression using a string value.
433
     */
434 76
    private function expandString(string $value, array $variable, string $operator): string
435
    {
436 76
        if (':' === $variable['modifier']) {
437 22
            $value = substr($value, 0, $variable['position']);
438
        }
439
440 76
        $expanded = rawurlencode($value);
441 76
        if ('+' === $operator || '#' === $operator) {
442 26
            return $this->decodeReserved($expanded);
443
        }
444
445 52
        return $expanded;
446
    }
447
448
    /**
449
     * Expands an expression using a list of values.
450
     *
451
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
452
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
453
     *
454
     * @return array{0:string, 1:bool}
455
     */
456 82
    private function expandList(array $value, array $variable, string $operator, string $joiner, bool $useQuery): array
457
    {
458 82
        if ([] === $value) {
459 4
            return ['', false];
460
        }
461
462 78
        $isAssoc = $this->isAssoc($value);
463 78
        $pairs = [];
464 78
        if (':' === $variable['modifier']) {
465 4
            throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($variable['name']);
466
        }
467
468
        /** @var string $key */
469 74
        foreach ($value as $key => $var) {
470 74
            if ($isAssoc) {
471 38
                if (is_array($var)) {
472 2
                    throw TemplateCanNotBeExpanded::dueToNestedListOfValue($key);
473
                }
474
475 36
                $key = rawurlencode((string) $key);
476
            }
477
478 72
            $var = rawurlencode((string) $var);
479 72
            if ('+' === $operator || '#' === $operator) {
480 16
                $var = $this->decodeReserved($var);
481
            }
482
483 72
            if ('*' === $variable['modifier']) {
484 40
                if ($isAssoc) {
485 20
                    $var = $key.'='.$var;
486 20
                } elseif ($key > 0 && $useQuery) {
487 8
                    $var = $variable['name'].'='.$var;
488
                }
489
            }
490
491 72
            $pairs[$key] = $var;
492
        }
493
494 72
        if ('*' === $variable['modifier']) {
495 40
            if ($isAssoc) {
496
                // Don't prepend the value name when using the explode
497
                // modifier with an associative array.
498 20
                $useQuery = false;
499
            }
500
501 40
            return [implode($joiner, $pairs), $useQuery];
502
        }
503
504 34
        if ($isAssoc) {
505
            // When an associative array is encountered and the
506
            // explode modifier is not set, then the result must be
507
            // a comma separated list of keys followed by their
508
            // respective values.
509 16
            foreach ($pairs as $offset => &$data) {
510 16
                $data = $offset.','.$data;
511
            }
512
513 16
            unset($data);
514
        }
515
516 34
        return [implode(',', $pairs), $useQuery];
517
    }
518
519
    /**
520
     * Determines if an array is associative.
521
     *
522
     * This makes the assumption that input arrays are sequences or hashes.
523
     * This assumption is a tradeoff for accuracy in favor of speed, but it
524
     * should work in almost every case where input is supplied for a URI
525
     * template.
526
     */
527 70
    private function isAssoc(array $array): bool
528
    {
529 70
        return [] !== $array && 0 !== array_keys($array)[0];
530
    }
531
532
    /**
533
     * Removes percent encoding on reserved characters (used with + and # modifiers).
534
     */
535 42
    private function decodeReserved(string $str): string
536
    {
537 42
        static $delimiters = [
538
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
539
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
540
        ];
541
542 42
        static $delimitersEncoded = [
543
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
544
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
545
        ];
546
547 42
        return str_replace($delimitersEncoded, $delimiters, $str);
548
    }
549
}
550