Passed
Pull Request — master (#153)
by ignace nyamagana
02:16
created

UriTemplate::expandVariable()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 7

Importance

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