Passed
Pull Request — master (#153)
by ignace nyamagana
01:42
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\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 240
    public function __construct($template, array $defaultVariables = [])
112
    {
113 240
        $this->template = $this->filterTemplate($template);
114 238
        $this->defaultVariables = $defaultVariables;
115
116 238
        $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 240
    private function filterTemplate($template): string
125
    {
126 240
        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 238
        return (string) $template;
131
    }
132
133
    /**
134
     * Parse the template expressions.
135
     *
136
     * @throws TemplateCanNotBeExpanded if the template syntax is invalid
137
     */
138 238
    private function parseExpressions(): void
139
    {
140 238
        $this->expressions = [];
141 238
        $this->variableNames = [];
142 238
        $this->uri = null;
143
144
        /** @var string $remainder */
145 238
        $remainder = preg_replace(self::REGEXP_EXPRESSION, '', $this->template);
146 238
        if (false !== strpos($remainder, '{') || false !== strpos($remainder, '}')) {
147 6
            throw TemplateCanNotBeExpanded::dueToInvalidTemplate($this->template);
148
        }
149
150 232
        preg_match_all(self::REGEXP_EXPRESSION, $this->template, $matches, PREG_SET_ORDER);
151 232
        $variables = [];
152 232
        foreach ($matches as $found) {
153 228
            $found = $found + ['operator' => ''];
154 228
            [$variables, $parsedExpression] = $this->parseVariables($found, $variables);
155 180
            $this->expressions[$found['expression']] = [
156 180
                'operator' => $found['operator'],
157 180
                'variables' => $parsedExpression,
158 180
                'joiner' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['joiner'],
159 180
                'prefix' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['prefix'],
160 180
                'query' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['query'],
161
            ];
162
        }
163
164 180
        $this->variableNames = array_keys($variables);
165 180
    }
166
167
    /**
168
     * Checks the expression conformance to RFC6570.
169
     *
170
     * @throws TemplateCanNotBeExpanded if the expression does not conform to RFC6570
171
     */
172 228
    private function parseVariables(array $parts, array $variables): array
173
    {
174 228
        if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
175 6
            throw TemplateCanNotBeExpanded::dueToUsingReservedOperator($parts['expression']);
176
        }
177
178 222
        $parsed = [];
179 222
        foreach (explode(',', $parts['variables']) as $varSpec) {
180 222
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $matches)) {
181 46
                throw TemplateCanNotBeExpanded::dueToInvalidVariableSpecification($varSpec, $parts['expression']);
182
            }
183
184 184
            $matches += ['modifier' => '', 'position' => ''];
185 184
            if ('' !== $matches['position']) {
186 28
                $matches['position'] = (int) $matches['position'];
187 28
                $matches['modifier'] = ':';
188
            }
189
190 184
            $variables[$matches['name']] = 1;
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->variableNames;
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 TemplateCanNotBeExpanded if the variable contains nested array values
255
     * @throws UriException             if the resulting expansion can not be converted to a UriInterface instance
256
     */
257 164
    public function expand(array $variables = []): UriInterface
258
    {
259 164
        if ([] === $this->expressions) {
260 2
            $this->uri = $this->uri ?? Uri::createFromString($this->template);
261
262 2
            return $this->uri;
263
        }
264
265 162
        $this->variables = $variables + $this->defaultVariables;
266
267
        /** @var string $uri */
268 162
        $uri = preg_replace_callback(self::REGEXP_EXPRESSION, [$this, 'expandExpression'], $this->template);
269
270 154
        return Uri::createFromString($uri);
271
    }
272
273
    /**
274
     * Expands the found expressions.
275
     *
276
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
277
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
278
     */
279 162
    private function expandExpression(array $matches): string
280
    {
281 162
        $expression = $this->expressions[$matches['expression']];
282
283 162
        $joiner = $expression['joiner'];
284 162
        $useQuery = $expression['query'];
285
286 162
        $parts = [];
287 162
        foreach ($expression['variables'] as $variable) {
288 162
            $parts[] = $this->expandVariable($variable, $expression['operator'], $joiner, $useQuery);
289
        }
290
291 154
        $expanded = implode($joiner, array_filter($parts));
292 154
        $prefix = $expression['prefix'];
293 154
        if ('' !== $expanded && '' !== $prefix) {
294 102
            return $prefix.$expanded;
295
        }
296
297 62
        return $expanded;
298
    }
299
300
    /**
301
     * Expands an expression.
302
     *
303
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
304
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
305
     */
306 162
    private function expandVariable(array $value, string $operator, string $joiner, bool $useQuery): string
307
    {
308 162
        $expanded = '';
309 162
        if (!isset($this->variables[$value['name']])) {
310 6
            return $expanded;
311
        }
312
313 158
        $variable = $this->normalizeVariable($this->variables[$value['name']]);
314 156
        $arguments = [$variable, $value, $operator];
315 156
        $method = 'expandString';
316 156
        $actualQuery = $useQuery;
317 156
        if (is_array($variable)) {
318 86
            $arguments[] = $joiner;
319 86
            $arguments[] = $useQuery;
320 86
            $method = 'expandList';
321
        }
322
323 156
        $expanded = $this->$method(...$arguments);
324 152
        if (is_array($expanded)) {
325 80
            [$expanded, $actualQuery] = $expanded;
326
        }
327
328 152
        if (!$actualQuery) {
329 114
            return $expanded;
330
        }
331
332 46
        if ('&' !== $joiner && '' === $expanded) {
333 2
            return $value['name'];
334
        }
335
336 46
        return $value['name'].'='.$expanded;
337
    }
338
339
    /**
340
     * @param mixed $var the value to be expanded
341
     *
342
     * @throws \TypeError if the type is not supported
343
     */
344 158
    private function normalizeVariable($var)
345
    {
346 158
        if (is_array($var)) {
347 86
            return $var;
348
        }
349
350 86
        if (is_bool($var)) {
351 2
            return true === $var ? '1' : '0';
352
        }
353
354 84
        if (is_scalar($var) || method_exists($var, '__toString')) {
355 82
            return (string) $var;
356
        }
357
358 2
        throw new \TypeError(sprintf('The variables must be a scalar or a stringable object `%s` given', gettype($var)));
359
    }
360
361
    /**
362
     * Expands an expression using a string value.
363
     */
364 84
    private function expandString(string $variable, array $value, string $operator): string
365
    {
366 84
        if (':' === $value['modifier']) {
367 22
            $variable = substr($variable, 0, $value['position']);
368
        }
369
370 84
        $expanded = rawurlencode($variable);
371 84
        if ('+' === $operator || '#' === $operator) {
372 32
            return $this->decodeReserved($expanded);
373
        }
374
375 60
        return $expanded;
376
    }
377
378
    /**
379
     * Expands an expression using a list of values.
380
     *
381
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
382
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
383
     *
384
     * @return array{0:string, 1:bool}
385
     */
386 86
    private function expandList(array $variable, array $value, string $operator, string $joiner, bool $useQuery): array
387
    {
388 86
        if ([] === $variable) {
389 4
            return ['', false];
390
        }
391
392 82
        $isAssoc = $this->isAssoc($variable);
393 82
        $pairs = [];
394 82
        if (':' === $value['modifier']) {
395 4
            throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($value['name']);
396
        }
397
398
        /** @var string $key */
399 78
        foreach ($variable as $key => $var) {
400 78
            if ($isAssoc) {
401 38
                if (is_array($var)) {
402 2
                    throw TemplateCanNotBeExpanded::dueToNestedListOfValue($key);
403
                }
404
405 36
                $key = rawurlencode((string) $key);
406
            }
407
408 76
            $var = rawurlencode((string) $var);
409 76
            if ('+' === $operator || '#' === $operator) {
410 16
                $var = $this->decodeReserved($var);
411
            }
412
413 76
            if ('*' === $value['modifier']) {
414 44
                if ($isAssoc) {
415 20
                    $var = $key.'='.$var;
416 24
                } elseif ($key > 0 && $useQuery) {
417 12
                    $var = $value['name'].'='.$var;
418
                }
419
            }
420
421 76
            $pairs[$key] = $var;
422
        }
423
424 76
        if ('*' === $value['modifier']) {
425 44
            if ($isAssoc) {
426
                // Don't prepend the value name when using the explode
427
                // modifier with an associative array.
428 20
                $useQuery = false;
429
            }
430
431 44
            return [implode($joiner, $pairs), $useQuery];
432
        }
433
434 38
        if ($isAssoc) {
435
            // When an associative array is encountered and the
436
            // explode modifier is not set, then the result must be
437
            // a comma separated list of keys followed by their
438
            // respective values.
439 16
            foreach ($pairs as $offset => &$data) {
440 16
                $data = $offset.','.$data;
441
            }
442
443 16
            unset($data);
444
        }
445
446 38
        return [implode(',', $pairs), $useQuery];
447
    }
448
449
    /**
450
     * Determines if an array is associative.
451
     *
452
     * This makes the assumption that input arrays are sequences or hashes.
453
     * This assumption is a tradeoff for accuracy in favor of speed, but it
454
     * should work in almost every case where input is supplied for a URI
455
     * template.
456
     */
457 82
    private function isAssoc(array $array): bool
458
    {
459 82
        return [] !== $array && 0 !== array_keys($array)[0];
460
    }
461
462
    /**
463
     * Removes percent encoding on reserved characters (used with + and # modifiers).
464
     */
465 48
    private function decodeReserved(string $str): string
466
    {
467 48
        static $delimiters = [
468
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
469
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
470
        ];
471
472 48
        static $delimiters_encoded = [
473
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
474
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
475
        ];
476
477 48
        return str_replace($delimiters_encoded, $delimiters, $str);
478
    }
479
}
480