Completed
Pull Request — master (#153)
by ignace nyamagana
03:24
created

UriTemplate::parseExpression()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

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

253
            /** @scrutinizer ignore-call */ 
254
            $expanded = self::expandString($variable, $value, $operator);
Loading history...
254 86
        } elseif (is_array($variable)) {
255 86
            $expanded = self::expandList($variable, $value, $operator, $joiner, $actualQuery);
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

255
            /** @scrutinizer ignore-call */ 
256
            $expanded = self::expandList($variable, $value, $operator, $joiner, $actualQuery);
Loading history...
256
        }
257
258 150
        if (!$actualQuery) {
259 112
            return $expanded;
260
        }
261
262 46
        if ('&' !== $joiner && '' === $expanded) {
263 2
            return $value['name'];
264
        }
265
266 46
        return $value['name'].'='.$expanded;
267
    }
268
269
    /**
270
     * Expands an expression using a string value.
271
     */
272 82
    private function expandString(string $variable, array $value, string $operator): string
273
    {
274 82
        if (':' === $value['modifier']) {
275 22
            $variable = substr($variable, 0, $value['position']);
276
        }
277
278 82
        $expanded = rawurlencode($variable);
279 82
        if ('+' === $operator || '#' === $operator) {
280 32
            return $this->decodeReserved($expanded);
281
        }
282
283 58
        return $expanded;
284
    }
285
286
    /**
287
     * Expands an expression using a list of values.
288
     *
289
     * @throws SyntaxError if the variables is an array and a ":" modifier needs to be applied
290
     * @throws SyntaxError if the variables contains nested array values
291
     */
292 86
    private function expandList(array $variable, array $value, string $operator, string $joiner, bool &$useQuery): string
293
    {
294 86
        if ([] === $variable) {
295 4
            $useQuery = false;
296
297 4
            return '';
298
        }
299
300 82
        $isAssoc = $this->isAssoc($variable);
301 82
        $pairs = [];
302 82
        if (':' === $value['modifier']) {
303 4
            throw new SyntaxError(sprintf('The ":" modifier can not be applied on the "%s" variable which is a list.', $value['name']));
304
        }
305
306 78
        foreach ($variable as $key => $var) {
307 78
            if ($isAssoc) {
308 38
                if (is_array($var)) {
309 2
                    throw new SyntaxError(sprintf('The submitted value for `%s` can not be a nested array.', $key));
310
                }
311
312 36
                $key = rawurlencode((string) $key);
313
            }
314
315 76
            $var = rawurlencode((string) $var);
316 76
            if ('+' === $operator || '#' === $operator) {
317 16
                $var = $this->decodeReserved($var);
318
            }
319
320 76
            if ('*' === $value['modifier']) {
321 44
                if ($isAssoc) {
322 20
                    $var = $key.'='.$var;
323 24
                } elseif ($key > 0 && $useQuery) {
324 12
                    $var = $value['name'].'='.$var;
325
                }
326
            }
327
328 76
            $pairs[$key] = $var;
329
        }
330
331 76
        if ('*' === $value['modifier']) {
332 44
            if ($isAssoc) {
333
                // Don't prepend the value name when using the explode
334
                // modifier with an associative array.
335 20
                $useQuery = false;
336
            }
337
338 44
            return implode($joiner, $pairs);
339
        }
340
341 38
        if ($isAssoc) {
342
            // When an associative array is encountered and the
343
            // explode modifier is not set, then the result must be
344
            // a comma separated list of keys followed by their
345
            // respective values.
346 16
            foreach ($pairs as $offset => &$data) {
347 16
                $data = $offset.','.$data;
348
            }
349
350 16
            unset($data);
351
        }
352
353 38
        return implode(',', $pairs);
354
    }
355
356
    /**
357
     * Determines if an array is associative.
358
     *
359
     * This makes the assumption that input arrays are sequences or hashes.
360
     * This assumption is a tradeoff for accuracy in favor of speed, but it
361
     * should work in almost every case where input is supplied for a URI
362
     * template.
363
     */
364 82
    private function isAssoc(array $array): bool
365
    {
366 82
        return [] !== $array && 0 !== array_keys($array)[0];
367
    }
368
369
    /**
370
     * Removes percent encoding on reserved characters (used with + and # modifiers).
371
     */
372 48
    private function decodeReserved(string $str): string
373
    {
374 48
        static $delimiters = [
375
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
376
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
377
        ];
378
379 48
        static $delimiters_encoded = [
380
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
381
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
382
        ];
383
384 48
        return str_replace($delimiters_encoded, $delimiters, $str);
385
    }
386
}
387