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

UriTemplate::getDefaultVariables()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 in_array;
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 UriInterface|null
89
     */
90
    private $uri;
91
92
    /**
93
     * @var array Variables to use in the template expansion
94
     */
95
    private $variables;
96
97
    /**
98
     * @param object|string $template a string or an object with the __toString method
99
     *
100
     * @throws \TypeError           if the template is not a string or an object with the __toString method
101
     * @throws UriTemplateException if the template syntax is invalid
102
     */
103 228
    public function __construct($template, array $defaultVariables = [])
104
    {
105 228
        $this->template = $this->filterTemplate($template);
106 226
        $this->variablesNames = $this->extractVariables();
107 172
        if ([] === $this->variablesNames) {
108 2
            $this->uri = Uri::createFromString($template);
109
        }
110 172
        $this->defaultVariables = $defaultVariables;
111 172
    }
112
113
    /**
114
     * @param object|string $template a string or an object with the __toString method
115
     *
116
     * @throws \TypeError if the template is not a string or an object with the __toString method
117
     */
118 228
    private function filterTemplate($template): string
119
    {
120 228
        if (!is_string($template) && !method_exists($template, '__toString')) {
121 2
            throw new \TypeError(sprintf('The template must be a string or a stringable object %s given.', gettype($template)));
122
        }
123
124 226
        return (string) $template;
125
    }
126
127
    /**
128
     * Extracts the variable name from the template.
129
     *
130
     * @throw SyntaxError if the template syntax is invalid
131
     *
132
     * @return string[]
133
     */
134 226
    private function extractVariables(): array
135
    {
136 226
        if (false === strpos($this->template, '{') && false === strpos($this->template, '}')) {
137 2
            return [];
138
        }
139
140 224
        $res = preg_match_all(self::REGEXP_EXPRESSION, $this->template, $matches, PREG_SET_ORDER);
141 224
        if (0 === $res) {
142 4
            throw UriTemplateException::dueToInvalidTemplate($this->template);
143
        }
144
145 220
        $variables = [];
146 220
        foreach ($matches as $expression) {
147 220
            $variables = $this->validateExpression($expression, $variables);
148
        }
149
150 170
        return $variables;
151
    }
152
153
    /**
154
     * Checks the expression conformance to RFC6570.
155
     *
156
     * @throws UriTemplateException if the expression does not conform to RFC6570
157
     */
158 220
    private function validateExpression(array $parts, array $variables): array
159
    {
160 220
        if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
161 6
            throw UriTemplateException::dueToUsingReservedOperator($parts['expression']);
162
        }
163
164 214
        foreach (explode(',', $parts['variables']) as $varSpec) {
165 214
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $matches)) {
166 44
                throw UriTemplateException::dueToInvalidVariableSpecification($varSpec, $parts['expression']);
167
            }
168
169 178
            if (!in_array($matches['name'], $variables, true)) {
170 178
                $variables[] = $matches['name'];
171
            }
172
        }
173
174 174
        return $variables;
175
    }
176
177
    /**
178
     * {@inheritDoc}
179
     */
180 4
    public function getTemplate(): string
181
    {
182 4
        return $this->template;
183
    }
184
185
    /**
186
     * {@inheritDoc}
187
     */
188
    public function getVariableNames(): array
189
    {
190
        return $this->variablesNames;
191
    }
192
193
    /**
194
     * {@inheritDoc}
195
     */
196 2
    public function withTemplate($template): UriTemplateInterface
197
    {
198 2
        $template = $this->filterTemplate($template);
199 2
        if ($template === $this->template) {
200 2
            return $this;
201
        }
202
203 2
        return new self($template, $this->defaultVariables);
204
    }
205
206
    /**
207
     * {@inheritDoc}
208
     */
209 6
    public function getDefaultVariables(): array
210
    {
211 6
        return $this->defaultVariables;
212
    }
213
214
    /**
215
     * {@inheritDoc}
216
     */
217 2
    public function withDefaultVariables(array $defaultDefaultVariables): UriTemplateInterface
218
    {
219 2
        if ($defaultDefaultVariables === $this->defaultVariables) {
220 2
            return $this;
221
        }
222
223 2
        $clone = clone $this;
224 2
        $clone->defaultVariables = $defaultDefaultVariables;
225
226 2
        return $clone;
227
    }
228
229
    /**
230
     * @throws UriTemplateException if the variable contains nested array values
231
     */
232 164
    public function expand(array $variables = []): UriInterface
233
    {
234 164
        if (null !== $this->uri) {
235 2
            return $this->uri;
236
        }
237
238 162
        $this->variables = $variables + $this->defaultVariables;
239
240
        /** @var string $uri */
241 162
        $uri = preg_replace_callback(self::REGEXP_EXPRESSION, [$this, 'expandMatch'], $this->template);
242
243 154
        return Uri::createFromString($uri);
244
    }
245
246
    /**
247
     * Expands the found expressions.
248
     *
249
     * @throws UriTemplateException if the variables is an array and a ":" modifier needs to be applied
250
     * @throws UriTemplateException if the variables contains nested array values
251
     */
252 162
    private function expandMatch(array $matches): string
253
    {
254 162
        $parsed = $this->parseExpression($matches['variables']);
255 162
        $joiner = self::OPERATOR_HASH_LOOKUP[$matches['operator']]['joiner'];
256 162
        $useQuery = self::OPERATOR_HASH_LOOKUP[$matches['operator']]['query'];
257
258 162
        $parts = [];
259 162
        foreach ($parsed as $part) {
260 162
            $parts[] = $this->expandExpression($part, $matches['operator'], $joiner, $useQuery);
261
        }
262
263 154
        $matchExpanded = implode($joiner, array_filter($parts));
264 154
        $prefix = self::OPERATOR_HASH_LOOKUP[$matches['operator']]['prefix'];
265 154
        if ('' !== $matchExpanded && '' !== $prefix) {
266 102
            return $prefix.$matchExpanded;
267
        }
268
269 62
        return $matchExpanded;
270
    }
271
272
    /**
273
     * Parse a template expression.
274
     */
275 162
    private function parseExpression(string $expression): array
276
    {
277 162
        $result = [];
278 162
        foreach (explode(',', $expression) as $value) {
279 162
            preg_match(self::REGEXP_VARSPEC, $value, $varSpec);
280 162
            $varSpec += ['modifier' => '', 'position' => ''];
281
282 162
            if ('' === $varSpec['position']) {
283 142
                $result[] = $varSpec;
284
285 142
                continue;
286
            }
287
288 26
            $varSpec['position'] = (int) $varSpec['position'];
289 26
            $varSpec['modifier'] = ':';
290
291 26
            $result[] = $varSpec;
292
        }
293
294 162
        return $result;
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