Completed
Pull Request — master (#153)
by ignace nyamagana
01:48
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\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_callback;
33
use function rawurlencode;
34
use function sprintf;
35
use function strpos;
36
use function substr;
37
use const PREG_SET_ORDER;
38
39
/**
40
 * Expands URI templates.
41
 *
42
 * @link http://tools.ietf.org/html/rfc6570
43
 *
44
 * Based on GuzzleHttp\UriTemplate class which is removed from Guzzle7.
45
 * @see https://github.com/guzzle/guzzle/blob/6.5/src/UriTemplate.php
46
 */
47
final class UriTemplate implements UriTemplateInterface
48
{
49
    private const REGEXP_EXPRESSION = '/\{
50
        (?<expression>
51
            (?<operator>[\.\/;\?&\=,\!@\|\+#])?
52
            (?<variables>[^\}]+)
53
        )
54
    \}/x';
55
56
    private const REGEXP_VARSPEC = '/^
57
        (?<name>(?:[A-z0-9_\.]|%[0-9a-fA-F]{2})+)
58
        (?<modifier>\:(?<position>\d+)|\*)?
59
    $/x';
60
61
    private const RESERVED_OPERATOR = '=,!@|';
62
63
    private const OPERATOR_HASH_LOOKUP = [
64
        ''  => ['prefix' => '',  'joiner' => ',', 'query' => false],
65
        '+' => ['prefix' => '',  'joiner' => ',', 'query' => false],
66
        '#' => ['prefix' => '#', 'joiner' => ',', 'query' => false],
67
        '.' => ['prefix' => '.', 'joiner' => '.', 'query' => false],
68
        '/' => ['prefix' => '/', 'joiner' => '/', 'query' => false],
69
        ';' => ['prefix' => ';', 'joiner' => ';', 'query' => true],
70
        '?' => ['prefix' => '?', 'joiner' => '&', 'query' => true],
71
        '&' => ['prefix' => '&', 'joiner' => '&', 'query' => true],
72
    ];
73
74
    /**
75
     * @var string
76
     */
77
    private $template;
78
79
    /**
80
     * @var array
81
     */
82
    private $defaultVariables;
83
84
    /**
85
     * @var array
86
     */
87
    private $variablesNames;
88
89
    /**
90
     * @var array
91
     */
92
    private $expressions;
93
94
    /**
95
     * @var UriInterface|null
96
     */
97
    private $uri;
98
99
    /**
100
     * @var array
101
     */
102
    private $variables;
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
     * @throws TemplateCanNotBeExpanded if the template syntax is invalid
109
     */
110 236
    public function __construct($template, array $defaultVariables = [])
111
    {
112 236
        $this->template = $this->filterTemplate($template);
113 234
        $this->defaultVariables = $defaultVariables;
114
115 234
        $this->parseExpressions();
116 180
    }
117
118
    /**
119
     * @param object|string $template a string or an object with the __toString method
120
     *
121
     * @throws \TypeError if the template is not a string or an object with the __toString method
122
     */
123 236
    private function filterTemplate($template): string
124
    {
125 236
        if (!is_string($template) && !method_exists($template, '__toString')) {
126 2
            throw new \TypeError(sprintf('The template must be a string or a stringable object %s given.', gettype($template)));
127
        }
128
129 234
        return (string) $template;
130
    }
131
132
    /**
133
     * Parse the template expressions.
134
     *
135
     * @throws TemplateCanNotBeExpanded if the template syntax is invalid
136
     */
137 234
    private function parseExpressions(): void
138
    {
139 234
        $this->expressions = [];
140 234
        $this->variablesNames = [];
141 234
        $this->uri = null;
142 234
        if (false === strpos($this->template, '{') && false === strpos($this->template, '}')) {
143 4
            return;
144
        }
145
146 230
        $res = preg_match_all(self::REGEXP_EXPRESSION, $this->template, $matches, PREG_SET_ORDER);
147 230
        if (0 === $res) {
148 4
            throw TemplateCanNotBeExpanded::dueToInvalidTemplate($this->template);
149
        }
150
151 226
        $variables = [];
152 226
        foreach ($matches as $found) {
153 226
            $found = $found + ['operator' => ''];
154 226
            [$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 176
        $this->variablesNames = array_keys($variables);
165 176
    }
166
167
    /**
168
     * Checks the expression conformance to RFC6570.
169
     *
170
     * @throws TemplateCanNotBeExpanded if the expression does not conform to RFC6570
171
     */
172 226
    private function parseVariables(array $parts, array $variables): array
173
    {
174 226
        if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
175 6
            throw TemplateCanNotBeExpanded::dueToUsingReservedOperator($parts['expression']);
176
        }
177
178 220
        $parsed = [];
179 220
        foreach (explode(',', $parts['variables']) as $varSpec) {
180 220
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $matches)) {
181 44
                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->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 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
        if (is_string($variable)) {
315 84
            $expanded = $this->expandString($variable, $value, $operator);
316 84
            $actualQuery = $useQuery;
317
        } else {
318 86
            [$expanded, $actualQuery] = $this->expandList($variable, $value, $operator, $joiner, $useQuery);
319
        }
320
321 152
        if (!$actualQuery) {
322 114
            return $expanded;
323
        }
324
325 46
        if ('&' !== $joiner && '' === $expanded) {
326 2
            return $value['name'];
327
        }
328
329 46
        return $value['name'].'='.$expanded;
330
    }
331
332
    /**
333
     * @param mixed $var the value to be expanded
334
     *
335
     * @throws \TypeError if the type is not supported
336
     */
337 158
    private function normalizeVariable($var)
338
    {
339 158
        if (is_array($var)) {
340 86
            return $var;
341
        }
342
343 86
        if (is_bool($var)) {
344 2
            return true === $var ? '1' : '0';
345
        }
346
347 84
        if (is_scalar($var) || method_exists($var, '__toString')) {
348 82
            return (string) $var;
349
        }
350
351 2
        throw new \TypeError(sprintf('The variables must be a scalar or a stringable object `%s` given', gettype($var)));
352
    }
353
354
    /**
355
     * Expands an expression using a string value.
356
     */
357 84
    private function expandString(string $variable, array $value, string $operator): string
358
    {
359 84
        if (':' === $value['modifier']) {
360 22
            $variable = substr($variable, 0, $value['position']);
361
        }
362
363 84
        $expanded = rawurlencode($variable);
364 84
        if ('+' === $operator || '#' === $operator) {
365 32
            return $this->decodeReserved($expanded);
366
        }
367
368 60
        return $expanded;
369
    }
370
371
    /**
372
     * Expands an expression using a list of values.
373
     *
374
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
375
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
376
     *
377
     * @return array{0:string, 1:bool}
378
     */
379 86
    private function expandList(array $variable, array $value, string $operator, string $joiner, bool $useQuery): array
380
    {
381 86
        if ([] === $variable) {
382 4
            return ['', false];
383
        }
384
385 82
        $isAssoc = $this->isAssoc($variable);
386 82
        $pairs = [];
387 82
        if (':' === $value['modifier']) {
388 4
            throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($value['name']);
389
        }
390
391
        /** @var string $key */
392 78
        foreach ($variable as $key => $var) {
393 78
            if ($isAssoc) {
394 38
                if (is_array($var)) {
395 2
                    throw TemplateCanNotBeExpanded::dueToNestedListOfValue($key);
396
                }
397
398 36
                $key = rawurlencode((string) $key);
399
            }
400
401 76
            $var = rawurlencode((string) $var);
402 76
            if ('+' === $operator || '#' === $operator) {
403 16
                $var = $this->decodeReserved($var);
404
            }
405
406 76
            if ('*' === $value['modifier']) {
407 44
                if ($isAssoc) {
408 20
                    $var = $key.'='.$var;
409 24
                } elseif ($key > 0 && $useQuery) {
410 12
                    $var = $value['name'].'='.$var;
411
                }
412
            }
413
414 76
            $pairs[$key] = $var;
415
        }
416
417 76
        if ('*' === $value['modifier']) {
418 44
            if ($isAssoc) {
419
                // Don't prepend the value name when using the explode
420
                // modifier with an associative array.
421 20
                $useQuery = false;
422
            }
423
424 44
            return [implode($joiner, $pairs), $useQuery];
425
        }
426
427 38
        if ($isAssoc) {
428
            // When an associative array is encountered and the
429
            // explode modifier is not set, then the result must be
430
            // a comma separated list of keys followed by their
431
            // respective values.
432 16
            foreach ($pairs as $offset => &$data) {
433 16
                $data = $offset.','.$data;
434
            }
435
436 16
            unset($data);
437
        }
438
439 38
        return [implode(',', $pairs), $useQuery];
440
    }
441
442
    /**
443
     * Determines if an array is associative.
444
     *
445
     * This makes the assumption that input arrays are sequences or hashes.
446
     * This assumption is a tradeoff for accuracy in favor of speed, but it
447
     * should work in almost every case where input is supplied for a URI
448
     * template.
449
     */
450 82
    private function isAssoc(array $array): bool
451
    {
452 82
        return [] !== $array && 0 !== array_keys($array)[0];
453
    }
454
455
    /**
456
     * Removes percent encoding on reserved characters (used with + and # modifiers).
457
     */
458 48
    private function decodeReserved(string $str): string
459
    {
460 48
        static $delimiters = [
461
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
462
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
463
        ];
464
465 48
        static $delimiters_encoded = [
466
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
467
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
468
        ];
469
470 48
        return str_replace($delimiters_encoded, $delimiters, $str);
471
    }
472
}
473