Completed
Pull Request — master (#153)
by ignace nyamagana
02:19
created

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