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

UriTemplate::decodeReserved()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 7
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 13
ccs 4
cts 4
cp 1
crap 1
rs 10
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\UriInterface;
17
use League\Uri\Exceptions\UriTemplateException;
18
use function array_filter;
19
use function array_keys;
20
use function explode;
21
use function gettype;
22
use function implode;
23
use function is_array;
24
use function is_bool;
25
use function is_scalar;
26
use function is_string;
27
use function method_exists;
28
use function preg_match;
29
use function preg_match_all;
30
use function preg_replace_callback;
31
use function rawurlencode;
32
use function sprintf;
33
use function strpos;
34
use function substr;
35
use const PREG_SET_ORDER;
36
37
/**
38
 * Expands URI templates.
39
 *
40
 * @link http://tools.ietf.org/html/rfc6570
41
 *
42
 * Based on GuzzleHttp\UriTemplate class which is removed from Guzzle7.
43
 * @see https://github.com/guzzle/guzzle/blob/6.5/src/UriTemplate.php
44
 */
45
final class UriTemplate implements UriTemplateInterface
46
{
47
    private const REGEXP_EXPRESSION = '/\{
48
        (?<expression>
49
            (?<operator>[\.\/;\?&\=,\!@\|\+#])?
50
            (?<variables>[^\}]+)
51
        )
52
    \}/x';
53
54
    private const REGEXP_VARSPEC = '/^
55
        (?<name>(?:[A-z0-9_\.]|%[0-9a-fA-F]{2})+)
56
        (?<modifier>\:(?<position>\d+)|\*)?
57
    $/x';
58
59
    private const RESERVED_OPERATOR = '=,!@|';
60
61
    private const OPERATOR_HASH_LOOKUP = [
62
        ''  => ['prefix' => '',  'joiner' => ',', 'query' => false],
63
        '+' => ['prefix' => '',  'joiner' => ',', 'query' => false],
64
        '#' => ['prefix' => '#', 'joiner' => ',', 'query' => false],
65
        '.' => ['prefix' => '.', 'joiner' => '.', 'query' => false],
66
        '/' => ['prefix' => '/', 'joiner' => '/', 'query' => false],
67
        ';' => ['prefix' => ';', 'joiner' => ';', 'query' => true],
68
        '?' => ['prefix' => '?', 'joiner' => '&', 'query' => true],
69
        '&' => ['prefix' => '&', 'joiner' => '&', 'query' => true],
70
    ];
71
72
    /**
73
     * @var string
74
     */
75
    private $template;
76
77
    /**
78
     * @var array
79
     */
80
    private $defaultVariables;
81
82
    /**
83
     * @var array
84
     */
85
    private $variablesNames;
86
87
    /**
88
     * @var array
89
     */
90
    private $expressions;
91
92
    /**
93
     * @var UriInterface|null
94
     */
95
    private $uri;
96
97
    /**
98
     * @var array Variables to use in the template expansion
99
     */
100
    private $variables;
101
102
    /**
103
     * @param object|string $template a string or an object with the __toString method
104
     *
105
     * @throws \TypeError           if the template is not a string or an object with the __toString method
106
     * @throws UriTemplateException if the template syntax is invalid
107
     */
108 236
    public function __construct($template, array $defaultVariables = [])
109
    {
110 236
        $this->template = $this->filterTemplate($template);
111 234
        $this->defaultVariables = $defaultVariables;
112 234
        $this->parseExpressions();
113 180
    }
114
115
    /**
116
     * @param object|string $template a string or an object with the __toString method
117
     *
118
     * @throws \TypeError if the template is not a string or an object with the __toString method
119
     */
120 236
    private function filterTemplate($template): string
121
    {
122 236
        if (!is_string($template) && !method_exists($template, '__toString')) {
123 2
            throw new \TypeError(sprintf('The template must be a string or a stringable object %s given.', gettype($template)));
124
        }
125
126 234
        return (string) $template;
127
    }
128
129
    /**
130
     * Parse the template expressions.
131
     *
132
     * @throw SyntaxError if the template syntax is invalid
133
     */
134 234
    private function parseExpressions(): void
135
    {
136 234
        $this->expressions = [];
137 234
        $this->variablesNames = [];
138 234
        if (false === strpos($this->template, '{') && false === strpos($this->template, '}')) {
139 4
            $this->uri = Uri::createFromString($this->template);
140
141 4
            return;
142
        }
143
144 230
        $res = preg_match_all(self::REGEXP_EXPRESSION, $this->template, $matches, PREG_SET_ORDER);
145 230
        if (0 === $res) {
146 4
            throw UriTemplateException::dueToInvalidTemplate($this->template);
147
        }
148
149 226
        $variables = [];
150 226
        foreach ($matches as $found) {
151 226
            $found = $found + ['operator' => ''];
152 226
            [$variables, $parsedExpression] = $this->parseVariables($found, $variables);
153 180
            $this->expressions[$found['expression']] = [
154 180
                'operator' => $found['operator'],
155 180
                'variables' => $parsedExpression,
156 180
                'joiner' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['joiner'],
157 180
                'prefix' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['prefix'],
158 180
                'query' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['query'],
159
            ];
160
        }
161
162 176
        $this->variablesNames = array_keys($variables);
163 176
    }
164
165
    /**
166
     * Checks the expression conformance to RFC6570.
167
     *
168
     * @throws UriTemplateException if the expression does not conform to RFC6570
169
     */
170 226
    private function parseVariables(array $parts, array $variables): array
171
    {
172 226
        if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
173 6
            throw UriTemplateException::dueToUsingReservedOperator($parts['expression']);
174
        }
175
176 220
        $parsed = [];
177 220
        foreach (explode(',', $parts['variables']) as $varSpec) {
178 220
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $matches)) {
179 44
                throw UriTemplateException::dueToInvalidVariableSpecification($varSpec, $parts['expression']);
180
            }
181
182 184
            $matches += ['modifier' => '', 'position' => ''];
183
184 184
            if ('' !== $matches['position']) {
185 28
                $matches['position'] = (int) $matches['position'];
186 28
                $matches['modifier'] = ':';
187
            }
188
189 184
            $variables[$matches['name']] = 1;
190
191 184
            $parsed[] = $matches;
192
        }
193
194 180
        return [$variables, $parsed];
195
    }
196
197
    /**
198
     * {@inheritDoc}
199
     */
200 4
    public function getTemplate(): string
201
    {
202 4
        return $this->template;
203
    }
204
205
    /**
206
     * {@inheritDoc}
207
     */
208 8
    public function getVariableNames(): array
209
    {
210 8
        return $this->variablesNames;
211
    }
212
213
    /**
214
     * {@inheritDoc}
215
     */
216 2
    public function withTemplate($template): UriTemplateInterface
217
    {
218 2
        $template = $this->filterTemplate($template);
219 2
        if ($template === $this->template) {
220 2
            return $this;
221
        }
222
223 2
        $clone = clone $this;
224 2
        $clone->template = $template;
225 2
        $clone->parseExpressions();
226
227 2
        return $clone;
228
    }
229
230
    /**
231
     * {@inheritDoc}
232
     */
233 6
    public function getDefaultVariables(): array
234
    {
235 6
        return $this->defaultVariables;
236
    }
237
238
    /**
239
     * {@inheritDoc}
240
     */
241 2
    public function withDefaultVariables(array $defaultDefaultVariables): UriTemplateInterface
242
    {
243 2
        if ($defaultDefaultVariables === $this->defaultVariables) {
244 2
            return $this;
245
        }
246
247 2
        $clone = clone $this;
248 2
        $clone->defaultVariables = $defaultDefaultVariables;
249
250 2
        return $clone;
251
    }
252
253
    /**
254
     * @throws UriTemplateException if the variable contains nested array values
255
     */
256 164
    public function expand(array $variables = []): UriInterface
257
    {
258 164
        if (null !== $this->uri) {
259 2
            return $this->uri;
260
        }
261
262 162
        $this->variables = $variables + $this->defaultVariables;
263
264
        /** @var string $uri */
265 162
        $uri = preg_replace_callback(self::REGEXP_EXPRESSION, [$this, 'expandMatch'], $this->template);
266
267 154
        return Uri::createFromString($uri);
268
    }
269
270
    /**
271
     * Expands the found expressions.
272
     *
273
     * @throws UriTemplateException if the variables is an array and a ":" modifier needs to be applied
274
     * @throws UriTemplateException if the variables contains nested array values
275
     */
276 162
    private function expandMatch(array $matches): string
277
    {
278 162
        $expression = $this->expressions[$matches['expression']];
279
280 162
        $joiner = $expression['joiner'];
281 162
        $useQuery = $expression['query'];
282
283 162
        $parts = [];
284 162
        foreach ($expression['variables'] as $part) {
285 162
            $parts[] = $this->expandExpression($part, $expression['operator'], $joiner, $useQuery);
286
        }
287
288 154
        $expanded = implode($joiner, array_filter($parts));
289 154
        $prefix = $expression['prefix'];
290 154
        if ('' !== $expanded && '' !== $prefix) {
291 102
            return $prefix.$expanded;
292
        }
293
294 62
        return $expanded;
295
    }
296
297
    /**
298
     * Expands an expression.
299
     *
300
     * @throws UriTemplateException if the variables is an array and a ":" modifier needs to be applied
301
     * @throws UriTemplateException if the variables contains nested array values
302
     */
303 162
    private function expandExpression(array $value, string $operator, string $joiner, bool $useQuery): string
304
    {
305 162
        $expanded = '';
306 162
        if (!isset($this->variables[$value['name']])) {
307 6
            return $expanded;
308
        }
309
310 158
        $variable = $this->normalizeVariable($this->variables[$value['name']]);
311 156
        $actualQuery = $useQuery;
312 156
        if (is_string($variable)) {
313 84
            $expanded = self::expandString($variable, $value, $operator);
0 ignored issues
show
Bug Best Practice introduced by
The method League\Uri\UriTemplate::expandString() is not static, but was called statically. ( Ignorable by Annotation )

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

313
            /** @scrutinizer ignore-call */ 
314
            $expanded = self::expandString($variable, $value, $operator);
Loading history...
314 86
        } elseif (is_array($variable)) {
0 ignored issues
show
introduced by
The condition is_array($variable) is always true.
Loading history...
315 86
            [$expanded, $actualQuery] = self::expandList($variable, $value, $operator, $joiner, $useQuery);
0 ignored issues
show
Bug Best Practice introduced by
The method League\Uri\UriTemplate::expandList() is not static, but was called statically. ( Ignorable by Annotation )

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

315
            /** @scrutinizer ignore-call */ 
316
            [$expanded, $actualQuery] = self::expandList($variable, $value, $operator, $joiner, $useQuery);
Loading history...
316
        }
317
318 152
        if (!$actualQuery) {
319 114
            return $expanded;
320
        }
321
322 46
        if ('&' !== $joiner && '' === $expanded) {
323 2
            return $value['name'];
324
        }
325
326 46
        return $value['name'].'='.$expanded;
327
    }
328
329
    /**
330
     * @param mixed $var the value to be expanded
331
     *
332
     * @throws \TypeError if the type is not supported
333
     */
334 158
    private function normalizeVariable($var)
335
    {
336 158
        if (is_array($var)) {
337 86
            return $var;
338
        }
339
340 86
        if (is_bool($var)) {
341 2
            return true === $var ? '1' : '0';
342
        }
343
344 84
        if (is_scalar($var) || method_exists($var, '__toString')) {
345 82
            return (string) $var;
346
        }
347
348 2
        throw new \TypeError(sprintf('The variables must be a scalar or a stringable object `%s` given', gettype($var)));
349
    }
350
351
    /**
352
     * Expands an expression using a string value.
353
     */
354 84
    private function expandString(string $variable, array $value, string $operator): string
355
    {
356 84
        if (':' === $value['modifier']) {
357 22
            $variable = substr($variable, 0, $value['position']);
358
        }
359
360 84
        $expanded = rawurlencode($variable);
361 84
        if ('+' === $operator || '#' === $operator) {
362 32
            return $this->decodeReserved($expanded);
363
        }
364
365 60
        return $expanded;
366
    }
367
368
    /**
369
     * Expands an expression using a list of values.
370
     *
371
     * @throws UriTemplateException if the variables is an array and a ":" modifier needs to be applied
372
     * @throws UriTemplateException if the variables contains nested array values
373
     *
374
     * @return array{0:string, 1:bool}
375
     */
376 86
    private function expandList(array $variable, array $value, string $operator, string $joiner, bool $useQuery): array
377
    {
378 86
        if ([] === $variable) {
379 4
            return ['', false];
380
        }
381
382 82
        $isAssoc = $this->isAssoc($variable);
383 82
        $pairs = [];
384 82
        if (':' === $value['modifier']) {
385 4
            throw UriTemplateException::dueToUnableToProcessValueListWithPrefix($value['name']);
386
        }
387
388
        /** @var string $key */
389 78
        foreach ($variable as $key => $var) {
390 78
            if ($isAssoc) {
391 38
                if (is_array($var)) {
392 2
                    throw UriTemplateException::dueToNestedListOfValue($key);
393
                }
394
395 36
                $key = rawurlencode((string) $key);
396
            }
397
398 76
            $var = rawurlencode((string) $var);
399 76
            if ('+' === $operator || '#' === $operator) {
400 16
                $var = $this->decodeReserved($var);
401
            }
402
403 76
            if ('*' === $value['modifier']) {
404 44
                if ($isAssoc) {
405 20
                    $var = $key.'='.$var;
406 24
                } elseif ($key > 0 && $useQuery) {
407 12
                    $var = $value['name'].'='.$var;
408
                }
409
            }
410
411 76
            $pairs[$key] = $var;
412
        }
413
414 76
        if ('*' === $value['modifier']) {
415 44
            if ($isAssoc) {
416
                // Don't prepend the value name when using the explode
417
                // modifier with an associative array.
418 20
                $useQuery = false;
419
            }
420
421 44
            return [implode($joiner, $pairs), $useQuery];
422
        }
423
424 38
        if ($isAssoc) {
425
            // When an associative array is encountered and the
426
            // explode modifier is not set, then the result must be
427
            // a comma separated list of keys followed by their
428
            // respective values.
429 16
            foreach ($pairs as $offset => &$data) {
430 16
                $data = $offset.','.$data;
431
            }
432
433 16
            unset($data);
434
        }
435
436 38
        return [implode(',', $pairs), $useQuery];
437
    }
438
439
    /**
440
     * Determines if an array is associative.
441
     *
442
     * This makes the assumption that input arrays are sequences or hashes.
443
     * This assumption is a tradeoff for accuracy in favor of speed, but it
444
     * should work in almost every case where input is supplied for a URI
445
     * template.
446
     */
447 82
    private function isAssoc(array $array): bool
448
    {
449 82
        return [] !== $array && 0 !== array_keys($array)[0];
450
    }
451
452
    /**
453
     * Removes percent encoding on reserved characters (used with + and # modifiers).
454
     */
455 48
    private function decodeReserved(string $str): string
456
    {
457 48
        static $delimiters = [
458
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
459
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
460
        ];
461
462 48
        static $delimiters_encoded = [
463
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
464
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
465
        ];
466
467 48
        return str_replace($delimiters_encoded, $delimiters, $str);
468
    }
469
}
470