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

UriString::parse()   C

Complexity

Conditions 15
Paths 8

Size

Total Lines 59
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 15

Importance

Changes 0
Metric Value
cc 15
eloc 33
nc 8
nop 1
dl 0
loc 59
ccs 34
cts 34
cp 1
crap 15
rs 5.9166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Exception\IdnSupportMissing;
17
use League\Uri\Exception\SyntaxError;
18
use TypeError;
19
use function array_merge;
20
use function defined;
21
use function explode;
22
use function filter_var;
23
use function function_exists;
24
use function gettype;
25
use function idn_to_ascii;
26
use function implode;
27
use function inet_pton;
28
use function is_scalar;
29
use function method_exists;
30
use function preg_match;
31
use function rawurldecode;
32
use function sprintf;
33
use function strpos;
34
use function substr;
35
use const FILTER_FLAG_IPV6;
36
use const FILTER_VALIDATE_IP;
37
use const IDNA_ERROR_BIDI;
38
use const IDNA_ERROR_CONTEXTJ;
39
use const IDNA_ERROR_DISALLOWED;
40
use const IDNA_ERROR_DOMAIN_NAME_TOO_LONG;
41
use const IDNA_ERROR_EMPTY_LABEL;
42
use const IDNA_ERROR_HYPHEN_3_4;
43
use const IDNA_ERROR_INVALID_ACE_LABEL;
44
use const IDNA_ERROR_LABEL_HAS_DOT;
45
use const IDNA_ERROR_LABEL_TOO_LONG;
46
use const IDNA_ERROR_LEADING_COMBINING_MARK;
47
use const IDNA_ERROR_LEADING_HYPHEN;
48
use const IDNA_ERROR_PUNYCODE;
49
use const IDNA_ERROR_TRAILING_HYPHEN;
50
use const INTL_IDNA_VARIANT_UTS46;
51
52
/**
53
 * A class to parse a URI string according to RFC3986.
54
 *
55
 * @see     https://tools.ietf.org/html/rfc3986
56
 * @package League\Uri
57
 * @author  Ignace Nyamagana Butera <[email protected]>
58
 * @since   0.1.0
59
 */
60
final class UriString
61
{
62
    /**
63
     * default URI component values.
64
     */
65
    private const URI_COMPONENTS = [
66
        'scheme' => null, 'user' => null, 'pass' => null, 'host' => null,
67
        'port' => null, 'path' => '', 'query' => null, 'fragment' => null,
68
    ];
69
70
    /**
71
     * simple URI which do not need any parsing.
72
     */
73
    private const URI_SCHORTCUTS = [
74
        '' => [],
75
        '#' => ['fragment' => ''],
76
        '?' => ['query' => ''],
77
        '?#' => ['query' => '', 'fragment' => ''],
78
        '/' => ['path' => '/'],
79
        '//' => ['host' => ''],
80
    ];
81
82
    /**
83
     * range of invalid characters in URI string.
84
     */
85
    private const REGEXP_INVALID_URI_CHARS = '/[\x00-\x1f\x7f]/';
86
87
    /**
88
     * @see https://tools.ietf.org/html/rfc3986#appendix-B
89
     *
90
     * RFC3986 regular expression URI splitter
91
     */
92
    private const REGEXP_URI_PARTS = ',^
93
        (?<scheme>(?<scontent>[^:/?\#]+):)?    # URI scheme component
94
        (?<authority>//(?<acontent>[^/?\#]*))? # URI authority part
95
        (?<path>[^?\#]*)                       # URI path component
96
        (?<query>\?(?<qcontent>[^\#]*))?       # URI query component
97
        (?<fragment>\#(?<fcontent>.*))?        # URI fragment component
98
    ,x';
99
100
    /**
101
     * @see https://tools.ietf.org/html/rfc3986#section-3.1
102
     *
103
     * URI scheme regular expresssion
104
     */
105
    private const REGEXP_URI_SCHEME = '/^([a-z][a-z\d\+\.\-]*)?$/i';
106
107
    /**
108
     * @see https://tools.ietf.org/html/rfc3986#section-3.2.2
109
     *
110
     * IPvFuture regular expression
111
     */
112
    private const REGEXP_IP_FUTURE = '/^
113
        v(?<version>[A-F0-9])+\.
114
        (?:
115
            (?<unreserved>[a-z0-9_~\-\.])|
116
            (?<sub_delims>[!$&\'()*+,;=:])  # also include the : character
117
        )+
118
    $/ix';
119
120
    /**
121
     * @see https://tools.ietf.org/html/rfc3986#section-3.2.2
122
     *
123
     * General registered name regular expression
124
     */
125
    private const REGEXP_REGISTERED_NAME = '/(?(DEFINE)
126
        (?<unreserved>[a-z0-9_~\-])   # . is missing as it is used to separate labels
127
        (?<sub_delims>[!$&\'()*+,;=])
128
        (?<encoded>%[A-F0-9]{2})
129
        (?<reg_name>(?:(?&unreserved)|(?&sub_delims)|(?&encoded))*)
130
    )
131
    ^(?:(?&reg_name)\.)*(?&reg_name)\.?$/ix';
132
133
    /**
134
     * @see https://tools.ietf.org/html/rfc3986#section-3.2.2
135
     *
136
     * invalid characters in host regular expression
137
     */
138
    private const REGEXP_INVALID_HOST_CHARS = '/
139
        [:\/?#\[\]@ ]  # gen-delims characters as well as the space character
140
    /ix';
141
142
    /**
143
     * @see https://tools.ietf.org/html/rfc3986#section-3.3
144
     *
145
     * invalid path for URI without scheme and authority regular expression
146
     */
147
    private const REGEXP_INVALID_PATH = ',^(([^/]*):)(.*)?/,';
148
149
    /**
150
     * Host and Port splitter regular expression.
151
     */
152
    private const REGEXP_HOST_PORT = ',^(?<host>\[.*\]|[^:]*)(:(?<port>.*))?$,';
153
154
    /**
155
     * IDN Host detector regular expression.
156
     */
157
    private const REGEXP_IDN_PATTERN = '/[^\x20-\x7f]/';
158
159
    /**
160
     * Only the address block fe80::/10 can have a Zone ID attach to
161
     * let's detect the link local significant 10 bits.
162
     */
163
    private const ZONE_ID_ADDRESS_BLOCK = "\xfe\x80";
164
165
    /**
166
     * Generate an URI string representation from its parsed representation
167
     * returned by League\Uri\parse() or PHP's parse_url.
168
     *
169
     * If you supply your own array, you are responsible for providing
170
     * valid components without their URI delimiters.
171
     *
172
     * @see https://tools.ietf.org/html/rfc3986#section-5.3
173
     * @see https://tools.ietf.org/html/rfc3986#section-7.5
174
     */
175 94
    public static function build(array $components): string
176
    {
177 94
        $result = $components['path'] ?? '';
178 94
        if (isset($components['query'])) {
179 50
            $result .= '?'.$components['query'];
180
        }
181
182 94
        if (isset($components['fragment'])) {
183 56
            $result .= '#'.$components['fragment'];
184
        }
185
186 94
        $scheme = null;
187 94
        if (isset($components['scheme'])) {
188 52
            $scheme = $components['scheme'].':';
189
        }
190
191 94
        if (!isset($components['host'])) {
192 42
            return $scheme.$result;
193
        }
194
195 52
        $scheme .= '//';
196 52
        $authority = $components['host'];
197 52
        if (isset($components['port'])) {
198 14
            $authority .= ':'.$components['port'];
199
        }
200
201 52
        if (!isset($components['user'])) {
202 34
            return $scheme.$authority.$result;
203
        }
204
205 18
        $authority = '@'.$authority;
206 18
        if (!isset($components['pass'])) {
207 4
            return $scheme.$components['user'].$authority.$result;
208
        }
209
210 14
        return $scheme.$components['user'].':'.$components['pass'].$authority.$result;
211
    }
212
213
    /**
214
     * Parse an URI string into its components.
215
     *
216
     * This method parses a URI and returns an associative array containing any
217
     * of the various components of the URI that are present.
218
     *
219
     * <code>
220
     * $components = (new Parser())->parse('http://[email protected]:42?query#');
221
     * var_export($components);
222
     * //will display
223
     * array(
224
     *   'scheme' => 'http',           // the URI scheme component
225
     *   'user' => 'foo',              // the URI user component
226
     *   'pass' => null,               // the URI pass component
227
     *   'host' => 'test.example.com', // the URI host component
228
     *   'port' => 42,                 // the URI port component
229
     *   'path' => '',                 // the URI path component
230
     *   'query' => 'query',           // the URI query component
231
     *   'fragment' => '',             // the URI fragment component
232
     * );
233
     * </code>
234
     *
235
     * The returned array is similar to PHP's parse_url return value with the following
236
     * differences:
237
     *
238
     * <ul>
239
     * <li>All components are always present in the returned array</li>
240
     * <li>Empty and undefined component are treated differently. And empty component is
241
     *   set to the empty string while an undefined component is set to the `null` value.</li>
242
     * <li>The path component is never undefined</li>
243
     * <li>The method parses the URI following the RFC3986 rules but you are still
244
     *   required to validate the returned components against its related scheme specific rules.</li>
245
     * </ul>
246
     *
247
     * @see https://tools.ietf.org/html/rfc3986
248
     *
249
     * @param mixed $uri any scalar or stringable object
250
     *
251
     * @throws SyntaxError if the URI contains invalid characters
252
     * @throws SyntaxError if the URI contains an invalid scheme
253
     * @throws SyntaxError if the URI contains an invalid path
254
     */
255 526
    public static function parse($uri): array
256
    {
257 526
        if (!is_scalar($uri) && !method_exists($uri, '__toString')) {
258 2
            throw new TypeError(sprintf('The uri must be a scalar or a stringable object `%s` given', gettype($uri)));
259
        }
260
261 524
        $uri = (string) $uri;
262
263 524
        if (isset(self::URI_SCHORTCUTS[$uri])) {
264 44
            return array_merge(self::URI_COMPONENTS, self::URI_SCHORTCUTS[$uri]);
265
        }
266
267 494
        if (1 === preg_match(self::REGEXP_INVALID_URI_CHARS, $uri)) {
268 2
            throw new SyntaxError(sprintf('The uri `%s` contains invalid characters', $uri));
269
        }
270
271
        //if the first character is a known URI delimiter parsing can be simplified
272 492
        $first_char = $uri[0];
273
274
        //The URI is made of the fragment only
275 492
        if ('#' === $first_char) {
276 6
            [, $fragment] = explode('#', $uri, 2);
277 6
            $components = self::URI_COMPONENTS;
278 6
            $components['fragment'] = $fragment;
279
280 6
            return $components;
281
        }
282
283
        //The URI is made of the query and fragment
284 488
        if ('?' === $first_char) {
285 6
            [, $partial] = explode('?', $uri, 2);
286 6
            [$query, $fragment] = explode('#', $partial, 2) + [1 => null];
287 6
            $components = self::URI_COMPONENTS;
288 6
            $components['query'] = $query;
289 6
            $components['fragment'] = $fragment;
290
291 6
            return $components;
292
        }
293
294
        //use RFC3986 URI regexp to split the URI
295 484
        preg_match(self::REGEXP_URI_PARTS, $uri, $parts);
296 484
        $parts += ['query' => '', 'fragment' => ''];
297
298 484
        if (':' === $parts['scheme'] || 1 !== preg_match(self::REGEXP_URI_SCHEME, $parts['scontent'])) {
299 6
            throw new SyntaxError(sprintf('The uri `%s` contains an invalid scheme', $uri));
300
        }
301
302 478
        if ('' === $parts['scheme'].$parts['authority'] && 1 === preg_match(self::REGEXP_INVALID_PATH, $parts['path'])) {
303 2
            throw new SyntaxError(sprintf('The uri `%s` contains an invalid path.', $uri));
304
        }
305
306 476
        return array_merge(
307 476
            self::URI_COMPONENTS,
308 476
            '' === $parts['authority'] ? [] : self::parseAuthority($parts['acontent']),
309
            [
310 442
                'path' => $parts['path'],
311 442
                'scheme' => '' === $parts['scheme'] ? null : $parts['scontent'],
312 442
                'query' => '' === $parts['query'] ? null : $parts['qcontent'],
313 442
                'fragment' => '' === $parts['fragment'] ? null : $parts['fcontent'],
314
            ]
315
        );
316
    }
317
318
    /**
319
     * Parses the URI authority part.
320
     *
321
     * @see https://tools.ietf.org/html/rfc3986#section-3.2
322
     *
323
     * @throws SyntaxError If the port component is invalid
324
     */
325 376
    private static function parseAuthority(string $authority): array
326
    {
327 376
        $components = ['user' => null, 'pass' => null, 'host' => '', 'port' => null];
328 376
        if ('' === $authority) {
329 14
            return $components;
330
        }
331
332 364
        $parts = explode('@', $authority, 2);
333 364
        if (isset($parts[1])) {
334 88
            [$components['user'], $components['pass']] = explode(':', $parts[0], 2) + [1 => null];
335
        }
336
337 364
        preg_match(self::REGEXP_HOST_PORT, $parts[1] ?? $parts[0], $matches);
338 364
        $matches += ['port' => ''];
339
340 364
        $components['port'] = self::filterPort($matches['port']);
341 352
        $components['host'] = self::filterHost($matches['host']);
342
343 330
        return $components;
344
    }
345
346
    /**
347
     * Filter and format the port component.
348
     *
349
     * @see https://tools.ietf.org/html/rfc3986#section-3.2.2
350
     *
351
     * @throws SyntaxError if the registered name is invalid
352
     *
353
     */
354 364
    private static function filterPort(string $port): ?int
355
    {
356 364
        if ('' === $port) {
357 260
            return null;
358
        }
359
360 108
        if (1 === preg_match('/^\d*$/', $port)) {
361 96
            return (int) $port;
362
        }
363
364 12
        throw new SyntaxError(sprintf('The port `%s` is invalid', $port));
365
    }
366
367
    /**
368
     * Returns whether a hostname is valid.
369
     *
370
     * @see https://tools.ietf.org/html/rfc3986#section-3.2.2
371
     *
372
     * @throws SyntaxError if the registered name is invalid
373
     */
374 352
    private static function filterHost(string $host): string
375
    {
376 352
        if ('' === $host) {
377 4
            return $host;
378
        }
379
380 350
        if ('[' !== $host[0] || ']' !== substr($host, -1)) {
381 314
            return self::filterRegisteredName($host);
382
        }
383
384 36
        if (!self::isIpHost(substr($host, 1, -1))) {
385 10
            throw new SyntaxError(sprintf('Host `%s` is invalid : the IP host is malformed', $host));
386
        }
387
388 26
        return $host;
389
    }
390
391
    /**
392
     * Returns whether the host is an IPv4 or a registered named.
393
     *
394
     * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
395
     *
396
     * @throws SyntaxError       if the registered name is invalid
397
     * @throws IdnSupportMissing if IDN support or ICU requirement are not available or met.
398
     */
399 314
    private static function filterRegisteredName(string $host): string
400
    {
401
        // @codeCoverageIgnoreStart
402
        // added because it is not possible in travis to disabled the ext/intl extension
403
        // see travis issue https://github.com/travis-ci/travis-ci/issues/4701
404
        static $idn_support = null;
405
        $idn_support = $idn_support ?? function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46');
406
        // @codeCoverageIgnoreEnd
407
408 314
        $formatted_host = rawurldecode(strtolower($host));
409 314
        if (1 === preg_match(self::REGEXP_REGISTERED_NAME, $formatted_host)) {
410 300
            if (false === strpos($formatted_host, 'xn--')) {
411 296
                return $host;
412
            }
413
414
            // @codeCoverageIgnoreStart
415
            if (!$idn_support) {
416
                throw new IdnSupportMissing(sprintf('the host `%s` could not be processed for IDN. Verify that ext/intl is installed for IDN support and that ICU is at least version 4.6.', $host));
417
            }
418
            // @codeCoverageIgnoreEnd
419
420 4
            $unicode = idn_to_utf8($host, 0, INTL_IDNA_VARIANT_UTS46, $arr);
421 4
            if (0 !== $arr['errors']) {
422 2
                throw new SyntaxError(sprintf('The host `%s` is invalid : %s', $host, self::getIDNAErrors($arr['errors'])));
423
            }
424
425
            // @codeCoverageIgnoreStart
426
            if (false === $unicode) {
427
                throw new IdnSupportMissing(sprintf('The Intl extension is misconfigured for %s, please correct this issue before proceeding.', PHP_OS));
428
            }
429
            // @codeCoverageIgnoreEnd
430
431 2
            return $host;
432
        }
433
434
        //to test IDN host non-ascii characters must be present in the host
435 14
        if (1 !== preg_match(self::REGEXP_IDN_PATTERN, $formatted_host)) {
436 2
            throw new SyntaxError(sprintf('Host `%s` is invalid : the host is not a valid registered name', $host));
437
        }
438
439
        // @codeCoverageIgnoreStart
440
        if (!$idn_support) {
441
            throw new IdnSupportMissing(sprintf('the host `%s` could not be processed for IDN. Verify that ext/intl is installed for IDN support and that ICU is at least version 4.6.', $host));
442
        }
443
        // @codeCoverageIgnoreEnd
444
445 12
        $retval = idn_to_ascii($formatted_host, 0, INTL_IDNA_VARIANT_UTS46, $arr);
446 12
        if (0 !== $arr['errors']) {
447 4
            throw new SyntaxError(sprintf('Host `%s` is not a valid IDN host : %s', $host, self::getIDNAErrors($arr['errors'])));
448
        }
449
450
        // @codeCoverageIgnoreStart
451
        if (false === $retval) {
452
            throw new IdnSupportMissing(sprintf('The Intl extension is misconfigured for %s, please correct this issue before proceeding.', PHP_OS));
453
        }
454
        // @codeCoverageIgnoreEnd
455
456 8
        if (false !== strpos($retval, '%')) {
457 4
            throw new SyntaxError(sprintf('Host `%s` is invalid : the host is not a valid registered name', $host));
458
        }
459
460 4
        return $host;
461
    }
462
463
    /**
464
     * Retrieves and format IDNA conversion error message.
465
     *
466
     * @see http://icu-project.org/apiref/icu4j/com/ibm/icu/text/IDNA.Error.html
467
     */
468 6
    private static function getIDNAErrors(int $error_byte): string
469
    {
470
        /**
471
         * IDNA errors.
472
         */
473 6
        static $idn_errors = [
474
            IDNA_ERROR_EMPTY_LABEL => 'a non-final domain name label (or the whole domain name) is empty',
475
            IDNA_ERROR_LABEL_TOO_LONG => 'a domain name label is longer than 63 bytes',
476
            IDNA_ERROR_DOMAIN_NAME_TOO_LONG => 'a domain name is longer than 255 bytes in its storage form',
477
            IDNA_ERROR_LEADING_HYPHEN => 'a label starts with a hyphen-minus ("-")',
478
            IDNA_ERROR_TRAILING_HYPHEN => 'a label ends with a hyphen-minus ("-")',
479
            IDNA_ERROR_HYPHEN_3_4 => 'a label contains hyphen-minus ("-") in the third and fourth positions',
480
            IDNA_ERROR_LEADING_COMBINING_MARK => 'a label starts with a combining mark',
481
            IDNA_ERROR_DISALLOWED => 'a label or domain name contains disallowed characters',
482
            IDNA_ERROR_PUNYCODE => 'a label starts with "xn--" but does not contain valid Punycode',
483
            IDNA_ERROR_LABEL_HAS_DOT => 'a label contains a dot=full stop',
484
            IDNA_ERROR_INVALID_ACE_LABEL => 'An ACE label does not contain a valid label string',
485
            IDNA_ERROR_BIDI => 'a label does not meet the IDNA BiDi requirements (for right-to-left characters)',
486
            IDNA_ERROR_CONTEXTJ => 'a label does not meet the IDNA CONTEXTJ requirements',
487
        ];
488
489 6
        $res = [];
490 6
        foreach ($idn_errors as $error => $reason) {
491 6
            if ($error === ($error_byte & $error)) {
492 6
                $res[] = $reason;
493
            }
494
        }
495
496 6
        return [] === $res ? 'Unknown IDNA conversion error.' : implode(', ', $res).'.';
497
    }
498
499
    /**
500
     * Validates a IPv6/IPvfuture host.
501
     *
502
     * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
503
     * @see http://tools.ietf.org/html/rfc6874#section-2
504
     * @see http://tools.ietf.org/html/rfc6874#section-4
505
     */
506 36
    private static function isIpHost(string $ip_host): bool
507
    {
508 36
        if (false !== filter_var($ip_host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
509 20
            return true;
510
        }
511
512 16
        if (1 === preg_match(self::REGEXP_IP_FUTURE, $ip_host, $matches)) {
513 4
            return !in_array($matches['version'], ['4', '6'], true);
514
        }
515
516 12
        $pos = strpos($ip_host, '%');
517 12
        if (false === $pos || 1 === preg_match(
518 8
            self::REGEXP_INVALID_HOST_CHARS,
519 12
            rawurldecode(substr($ip_host, $pos))
520
        )) {
521 6
            return false;
522
        }
523
524 6
        $ip_host = substr($ip_host, 0, $pos);
525
526 6
        return false !== filter_var($ip_host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)
527 6
            && 0 === strpos((string) inet_pton($ip_host), self::ZONE_ID_ADDRESS_BLOCK);
528
    }
529
}
530