Completed
Pull Request — master (#153)
by ignace nyamagana
01:58
created

UriTemplate::getTemplate()   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 238
    public function __construct($template, array $defaultVariables = [])
111
    {
112 238
        $this->template = $this->filterTemplate($template);
113 236
        $this->defaultVariables = $defaultVariables;
114
115 236
        $this->parseExpressions();
116 186
    }
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 238
    private function filterTemplate($template): string
124
    {
125 238
        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 236
        return (string) $template;
130
    }
131
132
    /**
133
     * Parse the template expressions.
134
     *
135
     * @throws TemplateCanNotBeExpanded if the template syntax is invalid
136
     */
137 236
    private function parseExpressions(): void
138
    {
139 236
        $this->expressions = [];
140 236
        $this->variablesNames = [];
141 236
        $this->uri = null;
142 236
        $bracesOffset = strpos($this->template, '{');
143 236
        if (false === $bracesOffset || false === strpos($this->template, '}', $bracesOffset)) {
144 10
            return;
145
        }
146
147 226
        preg_match_all(self::REGEXP_EXPRESSION, $this->template, $matches, PREG_SET_ORDER);
148 226
        $variables = [];
149 226
        foreach ($matches as $found) {
150 226
            $found = $found + ['operator' => ''];
151 226
            [$variables, $parsedExpression] = $this->parseVariables($found, $variables);
152 180
            $this->expressions[$found['expression']] = [
153 180
                'operator' => $found['operator'],
154 180
                'variables' => $parsedExpression,
155 180
                'joiner' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['joiner'],
156 180
                'prefix' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['prefix'],
157 180
                'query' => self::OPERATOR_HASH_LOOKUP[$found['operator']]['query'],
158
            ];
159
        }
160
161 176
        $this->variablesNames = array_keys($variables);
162 176
    }
163
164
    /**
165
     * Checks the expression conformance to RFC6570.
166
     *
167
     * @throws TemplateCanNotBeExpanded if the expression does not conform to RFC6570
168
     */
169 226
    private function parseVariables(array $parts, array $variables): array
170
    {
171 226
        if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
172 6
            throw TemplateCanNotBeExpanded::dueToUsingReservedOperator($parts['expression']);
173
        }
174
175 220
        $parsed = [];
176 220
        foreach (explode(',', $parts['variables']) as $varSpec) {
177 220
            if (1 !== preg_match(self::REGEXP_VARSPEC, $varSpec, $matches)) {
178 44
                throw TemplateCanNotBeExpanded::dueToInvalidVariableSpecification($varSpec, $parts['expression']);
179
            }
180
181 184
            $matches += ['modifier' => '', 'position' => ''];
182 184
            if ('' !== $matches['position']) {
183 28
                $matches['position'] = (int) $matches['position'];
184 28
                $matches['modifier'] = ':';
185
            }
186
187 184
            $variables[$matches['name']] = 1;
188 184
            $parsed[] = $matches;
189
        }
190
191 180
        return [$variables, $parsed];
192
    }
193
194
    /**
195
     * {@inheritDoc}
196
     */
197 4
    public function getTemplate(): string
198
    {
199 4
        return $this->template;
200
    }
201
202
    /**
203
     * {@inheritDoc}
204
     */
205 14
    public function getVariableNames(): array
206
    {
207 14
        return $this->variablesNames;
208
    }
209
210
    /**
211
     * {@inheritDoc}
212
     */
213 2
    public function withTemplate($template): UriTemplateInterface
214
    {
215 2
        $template = $this->filterTemplate($template);
216 2
        if ($template === $this->template) {
217 2
            return $this;
218
        }
219
220 2
        $clone = clone $this;
221 2
        $clone->template = $template;
222 2
        $clone->parseExpressions();
223
224 2
        return $clone;
225
    }
226
227
    /**
228
     * {@inheritDoc}
229
     */
230 6
    public function getDefaultVariables(): array
231
    {
232 6
        return $this->defaultVariables;
233
    }
234
235
    /**
236
     * {@inheritDoc}
237
     */
238 2
    public function withDefaultVariables(array $defaultDefaultVariables): UriTemplateInterface
239
    {
240 2
        if ($defaultDefaultVariables === $this->defaultVariables) {
241 2
            return $this;
242
        }
243
244 2
        $clone = clone $this;
245 2
        $clone->defaultVariables = $defaultDefaultVariables;
246
247 2
        return $clone;
248
    }
249
250
    /**
251
     * @throws TemplateCanNotBeExpanded if the variable contains nested array values
252
     * @throws UriException             if the resulting expansion can not be converted to a UriInterface instance
253
     */
254 164
    public function expand(array $variables = []): UriInterface
255
    {
256 164
        if ([] === $this->expressions) {
257 2
            $this->uri = $this->uri ?? Uri::createFromString($this->template);
258
259 2
            return $this->uri;
260
        }
261
262 162
        $this->variables = $variables + $this->defaultVariables;
263
264
        /** @var string $uri */
265 162
        $uri = preg_replace_callback(self::REGEXP_EXPRESSION, [$this, 'expandExpression'], $this->template);
266
267 154
        return Uri::createFromString($uri);
268
    }
269
270
    /**
271
     * Expands the found expressions.
272
     *
273
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
274
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
275
     */
276 162
    private function expandExpression(array $matches): string
277
    {
278 162
        $expression = $this->expressions[$matches['expression']];
279
280 162
        $joiner = $expression['joiner'];
281 162
        $useQuery = $expression['query'];
282
283 162
        $parts = [];
284 162
        foreach ($expression['variables'] as $variable) {
285 162
            $parts[] = $this->expandVariable($variable, $expression['operator'], $joiner, $useQuery);
286
        }
287
288 154
        $expanded = implode($joiner, array_filter($parts));
289 154
        $prefix = $expression['prefix'];
290 154
        if ('' !== $expanded && '' !== $prefix) {
291 102
            return $prefix.$expanded;
292
        }
293
294 62
        return $expanded;
295
    }
296
297
    /**
298
     * Expands an expression.
299
     *
300
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
301
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
302
     */
303 162
    private function expandVariable(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
        if (is_string($variable)) {
312 84
            $expanded = $this->expandString($variable, $value, $operator);
313 84
            $actualQuery = $useQuery;
314
        } else {
315 86
            [$expanded, $actualQuery] = $this->expandList($variable, $value, $operator, $joiner, $useQuery);
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 TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
372
     * @throws TemplateCanNotBeExpanded 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 TemplateCanNotBeExpanded::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 TemplateCanNotBeExpanded::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