Expression   B
last analyzed

Complexity

Total Complexity 43

Size/Duplication

Total Lines 322
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 105
c 1
b 0
f 0
dl 0
loc 322
ccs 100
cts 100
cp 1
rs 8.96
wmc 43

14 Methods

Rating   Name   Duplication   Size   Complexity  
A replace() 0 18 5
A __set_state() 0 3 1
A replaceString() 0 12 4
A toString() 0 3 1
A inject() 0 7 2
A setVariableNames() 0 7 1
A decodeReserved() 0 13 1
A expand() 0 22 4
A setExpressionString() 0 9 1
A variableNames() 0 3 1
A __construct() 0 7 1
C replaceList() 0 56 15
A isAssoc() 0 3 2
A createFromString() 0 17 4

How to fix   Complexity   

Complex Class

Complex classes like Expression often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Expression, and based on these observations, apply Extract Interface, too.

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\UriTemplate;
15
16
use League\Uri\Exceptions\SyntaxError;
17
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
18
use function array_filter;
19
use function array_keys;
20
use function array_map;
21
use function array_unique;
22
use function explode;
23
use function implode;
24
use function preg_match;
25
use function rawurlencode;
26
use function str_replace;
27
use function strpos;
28
use function substr;
29
30
final class Expression
31
{
32
    /**
33
     * Expression regular expression pattern.
34
     *
35
     * @link https://tools.ietf.org/html/rfc6570#section-2.2
36
     */
37
    private const REGEXP_EXPRESSION = '/^\{
38
        (?:
39
            (?<operator>[\.\/;\?&\=,\!@\|\+#])?
40
            (?<variables>[^\}]*)
41
        )
42
    \}$/x';
43
44
    /**
45
     * Reserved Operator characters.
46
     *
47
     * @link https://tools.ietf.org/html/rfc6570#section-2.2
48
     */
49
    private const RESERVED_OPERATOR = '=,!@|';
50
51
    /**
52
     * Processing behavior according to the expression type operator.
53
     *
54
     * @link https://tools.ietf.org/html/rfc6570#appendix-A
55
     */
56
    private const OPERATOR_HASH_LOOKUP = [
57
        ''  => ['prefix' => '',  'joiner' => ',', 'query' => false],
58
        '+' => ['prefix' => '',  'joiner' => ',', 'query' => false],
59
        '#' => ['prefix' => '#', 'joiner' => ',', 'query' => false],
60
        '.' => ['prefix' => '.', 'joiner' => '.', 'query' => false],
61
        '/' => ['prefix' => '/', 'joiner' => '/', 'query' => false],
62
        ';' => ['prefix' => ';', 'joiner' => ';', 'query' => true],
63
        '?' => ['prefix' => '?', 'joiner' => '&', 'query' => true],
64
        '&' => ['prefix' => '&', 'joiner' => '&', 'query' => true],
65
    ];
66
67
    /**
68
     * @var string
69
     */
70
    private $operator;
71
72
    /**
73
     * @var string
74
     */
75
    private $joiner;
76
77
    /**
78
     * @var array<VarSpecifier>
79
     */
80
    private $varSpecifiers;
81
82
    /**
83
     * @var array<string>
84
     */
85
    private $variableNames;
86
87
    /**
88
     * @var string
89
     */
90
    private $expressionString;
91
92 40
    private function __construct(string $operator, VarSpecifier ...$varSpecifiers)
93
    {
94 40
        $this->operator = $operator;
95 40
        $this->varSpecifiers = $varSpecifiers;
96 40
        $this->joiner = self::OPERATOR_HASH_LOOKUP[$operator]['joiner'];
97 40
        $this->variableNames = $this->setVariableNames();
98 40
        $this->expressionString = $this->setExpressionString();
99 40
    }
100
101
    /**
102
     * @return array<string>
103
     */
104 40
    private function setVariableNames(): array
105
    {
106
        $mapper = static function (VarSpecifier $varSpecifier): string {
107 40
            return $varSpecifier->name();
108 40
        };
109
110 40
        return array_unique(array_map($mapper, $this->varSpecifiers));
111
    }
112
113 40
    private function setExpressionString(): string
114
    {
115
        $mapper = static function (VarSpecifier $variable): string {
116 40
            return $variable->toString();
117 40
        };
118
119 40
        $varSpecifierString = implode(',', array_map($mapper, $this->varSpecifiers));
120
121 40
        return '{'.$this->operator.$varSpecifierString.'}';
122
    }
123
124
    /**
125
     * {@inheritDoc}
126
     */
127 2
    public static function __set_state(array $properties): self
128
    {
129 2
        return new self($properties['operator'], ...$properties['varSpecifiers']);
130
    }
131
132
    /**
133
     * @throws SyntaxError if the expression is invalid
134
     * @throws SyntaxError if the operator used in the expression is invalid
135
     * @throws SyntaxError if the variable specifiers is invalid
136
     */
137 100
    public static function createFromString(string $expression): self
138
    {
139 100
        if (1 !== preg_match(self::REGEXP_EXPRESSION, $expression, $parts)) {
140 6
            throw new SyntaxError('The expression "'.$expression.'" is invalid.');
141
        }
142
143
        /** @var array{operator:string, variables:string} $parts */
144 94
        $parts = $parts + ['operator' => ''];
145 94
        if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
146 8
            throw new SyntaxError('The operator used in the expression "'.$expression.'" is reserved.');
147
        }
148
149
        $mapper = static function (string $varSpec): VarSpecifier {
150 86
            return VarSpecifier::createFromString($varSpec);
151 86
        };
152
153 86
        return new Expression($parts['operator'], ...array_map($mapper, explode(',', $parts['variables'])));
154
    }
155
156
    /**
157
     * Returns the expression string representation.
158
     *
159
     */
160 40
    public function toString(): string
161
    {
162 40
        return $this->expressionString;
163
    }
164
165
    /**
166
     * @return array<string>
167
     */
168 40
    public function variableNames(): array
169
    {
170 40
        return $this->variableNames;
171
    }
172
173 148
    public function expand(VariableBag $variables): string
174
    {
175 148
        $parts = [];
176 148
        foreach ($this->varSpecifiers as $varSpecifier) {
177 148
            $parts[] = $this->replace($varSpecifier, $variables);
178
        }
179
180
        $nullFilter = static function ($value): bool {
181 148
            return '' !== $value;
182 148
        };
183
184 148
        $expanded = implode($this->joiner, array_filter($parts, $nullFilter));
185 148
        if ('' === $expanded) {
186 8
            return $expanded;
187
        }
188
189 140
        $prefix = self::OPERATOR_HASH_LOOKUP[$this->operator]['prefix'];
190 140
        if ('' === $prefix) {
191 46
            return $expanded;
192
        }
193
194 96
        return $prefix.$expanded;
195
    }
196
197
    /**
198
     * Replaces an expression with the given variables.
199
     *
200
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
201
     * @throws TemplateCanNotBeExpanded if the variables contains nested array values
202
     */
203 148
    private function replace(VarSpecifier $varSpec, VariableBag $variables): string
204
    {
205 148
        $value = $variables->fetch($varSpec->name());
206 148
        if (null === $value) {
207 4
            return '';
208
        }
209
210 146
        $useQuery = self::OPERATOR_HASH_LOOKUP[$this->operator]['query'];
211 146
        [$expanded, $actualQuery] = $this->inject($value, $varSpec, $useQuery);
212 146
        if (!$actualQuery) {
213 108
            return $expanded;
214
        }
215
216 40
        if ('&' !== $this->joiner && '' === $expanded) {
217 2
            return $varSpec->name();
218
        }
219
220 40
        return $varSpec->name().'='.$expanded;
221
    }
222
223
    /**
224
     * @param string|array<string> $value
225
     *
226
     * @return array{0:string, 1:bool}
227
     */
228 146
    private function inject($value, VarSpecifier $varSpec, bool $useQuery): array
229
    {
230 146
        if (is_string($value)) {
231 78
            return $this->replaceString($value, $varSpec, $useQuery);
232
        }
233
234 72
        return $this->replaceList($value, $varSpec, $useQuery);
235
    }
236
237
    /**
238
     * Expands an expression using a string value.
239
     *
240
     * @return array{0:string, 1:bool}
241
     */
242 78
    private function replaceString(string $value, VarSpecifier $varSpec, bool $useQuery): array
243
    {
244 78
        if (':' === $varSpec->modifier()) {
245 20
            $value = substr($value, 0, $varSpec->position());
246
        }
247
248 78
        $expanded = rawurlencode($value);
249 78
        if ('+' === $this->operator || '#' === $this->operator) {
250 24
            return [$this->decodeReserved($expanded), $useQuery];
251
        }
252
253 56
        return [$expanded, $useQuery];
254
    }
255
256
    /**
257
     * Expands an expression using a list of values.
258
     *
259
     * @param array<string> $value
260
     *
261
     * @throws TemplateCanNotBeExpanded if the variables is an array and a ":" modifier needs to be applied
262
     *
263
     * @return array{0:string, 1:bool}
264
     */
265 76
    private function replaceList(array $value, VarSpecifier $varSpec, bool $useQuery): array
266
    {
267 76
        if ([] === $value) {
268 4
            return ['', false];
269
        }
270
271 72
        if (':' === $varSpec->modifier()) {
272 4
            throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($varSpec->name());
273
        }
274
275 68
        $pairs = [];
276 68
        $isAssoc = $this->isAssoc($value);
277 68
        foreach ($value as $key => $var) {
278 68
            if ($isAssoc) {
279 32
                $key = rawurlencode((string) $key);
280
            }
281
282 68
            $var = rawurlencode($var);
283 68
            if ('+' === $this->operator || '#' === $this->operator) {
284 16
                $var = $this->decodeReserved($var);
285
            }
286
287 68
            if ('*' === $varSpec->modifier()) {
288 36
                if ($isAssoc) {
289 16
                    $var = $key.'='.$var;
290 20
                } elseif ($key > 0 && $useQuery) {
291 8
                    $var = $varSpec->name().'='.$var;
292
                }
293
            }
294
295 68
            $pairs[$key] = $var;
296
        }
297
298 68
        if ('*' === $varSpec->modifier()) {
299 36
            if ($isAssoc) {
300
                // Don't prepend the value name when using the explode
301
                // modifier with an associative array.
302 16
                $useQuery = false;
303
            }
304
305 36
            return [implode($this->joiner, $pairs), $useQuery];
306
        }
307
308 34
        if ($isAssoc) {
309
            // When an associative array is encountered and the
310
            // explode modifier is not set, then the result must be
311
            // a comma separated list of keys followed by their
312
            // respective values.
313 16
            foreach ($pairs as $offset => &$data) {
314 16
                $data = $offset.','.$data;
315
            }
316
317 16
            unset($data);
318
        }
319
320 34
        return [implode(',', $pairs), $useQuery];
321
    }
322
323
    /**
324
     * Determines if an array is associative.
325
     *
326
     * This makes the assumption that input arrays are sequences or hashes.
327
     * This assumption is a trade-off for accuracy in favor of speed, but it
328
     * should work in almost every case where input is supplied for a URI
329
     * template.
330
     */
331 68
    private function isAssoc(array $array): bool
332
    {
333 68
        return [] !== $array && 0 !== array_keys($array)[0];
334
    }
335
336
    /**
337
     * Removes percent encoding on reserved characters (used with + and # modifiers).
338
     */
339 40
    private function decodeReserved(string $str): string
340
    {
341 40
        static $delimiters = [
342
            ':', '/', '?', '#', '[', ']', '@', '!', '$',
343
            '&', '\'', '(', ')', '*', '+', ',', ';', '=',
344
        ];
345
346 40
        static $delimitersEncoded = [
347
            '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24',
348
            '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D',
349
        ];
350
351 40
        return str_replace($delimitersEncoded, $delimiters, $str);
352
    }
353
}
354