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

290
            /** @scrutinizer ignore-call */ 
291
            $expanded = self::expandString($variable, $value, $operator);
Loading history...
291 86
        } elseif (is_array($variable)) {
0 ignored issues
show
introduced by
The condition is_array($variable) is always true.
Loading history...
292 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

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