Completed
Push — master ( 1fae80...ecffef )
by Derek
02:12
created

Uri::fragmentToString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
namespace Subreality\Dilmun\Anshar\Http;
3
4
use Psr\Http\Message\UriInterface;
5
use Subreality\Dilmun\Anshar\Http\UriParts\Fragment;
6
use Subreality\Dilmun\Anshar\Http\UriParts\Query;
7
use Subreality\Dilmun\Anshar\Http\UriParts\Scheme;
8
use Subreality\Dilmun\Anshar\Utils\ArrayHelper;
9
use Subreality\Dilmun\Anshar\Utils\StringHelper;
10
11
/**
12
 * Class Uri
13
 * @package Subreality\Dilmun\Anshar\Http
14
 */
15
class Uri implements UriInterface
16
{
17
    use SchemePortsTrait;
18
19
    protected $uri_parts = array(
20
        "scheme"    => "",
21
        "hier_part" => "",
22
        "authority" => "",
23
        "user_info" => "",
24
        "host"      => "",
25
        "port"      => null,
26
        "path"      => "",
27
        "query"     => "",
28
        "fragment"  => "",
29
    );
30
31
    /** @var  Scheme */
32
    protected $scheme;
33
    /** @var  Query */
34
    protected $query;
35
    /** @var  Fragment */
36
    protected $fragment;
37
38
    protected $sub_delims = array(
39
        "!",
40
        "$",
41
        "&",
42
        "'",
43
        "(",
44
        ")",
45
        "*",
46
        "+",
47
        ",",
48
        ";",
49
        "=",
50
    );
51
52
    protected $pchar_unencoded = array(
53
        ":",
54
        "@",
55
    );
56
57
    /**
58
     * Uri constructor.  Accepts a string representing a URI and parses the string into the URI's component parts.
59
     *
60
     * @throws \InvalidArgumentException    Throws an \InvalidArgumentException when its parameter is not a string
61
     * @param string $uri
62
     */
63 81
    public function __construct($uri)
64
    {
65 81
        if (!is_string($uri)) {
66 6
            throw new \InvalidArgumentException("New Uri objects must be constructed with a string URI");
67
        }
68
69 75
        $this->explodeUri($uri);
70 75
    }
71
72
    /**
73
     * @todo Add a distinct test for this outside of constructor test
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
74
     * Retrieve the parsed components of the URI string.
75
     *
76
     * If the class was provided an invalid URI string, URI components will be empty strings, except port, which will
77
     * be null
78
     *
79
     * @return mixed[]
80
     */
81 34
    public function getParsedUri()
82
    {
83 34
        return $this->uri_parts;
84
    }
85
86
    /**
87
     * Retrieve the scheme component of the URI.
88
     *
89
     * If no scheme is present, this method MUST return an empty string.
90
     *
91
     * The value returned MUST be normalized to lowercase, per RFC 3986
92
     * Section 3.1.
93
     *
94
     * The trailing ":" character is not part of the scheme and MUST NOT be
95
     * added.
96
     *
97
     * @see https://tools.ietf.org/html/rfc3986#section-3.1
98
     * @return string The URI scheme.
99
     */
100 3
    public function getScheme()
101
    {
102 3
        return (string) $this->scheme;
103
    }
104
105
    /**
106
     * Retrieve the authority component of the URI.
107
     *
108
     * If no authority information is present, this method MUST return an empty
109
     * string.
110
     *
111
     * The authority syntax of the URI is:
112
     *
113
     * <pre>
114
     * [user-info@]host[:port]
115
     * </pre>
116
     *
117
     * If the port component is not set or is the standard port for the current
118
     * scheme, it SHOULD NOT be included.
119
     *
120
     * @see https://tools.ietf.org/html/rfc3986#section-3.2
121
     * @return string The URI authority, in "[user-info@]host[:port]" format.
122
     */
123 4
    public function getAuthority()
124
    {
125 4
        $normalized_authority = $this->uri_parts["host"];
126
127 4
        if (!empty($this->uri_parts["user_info"])) {
128 4
            $normalized_authority = $this->uri_parts["user_info"] . "@" . $normalized_authority;
129 4
        }
130
131 4
        $normalized_port = $this->normalizePort();
132
133 4
        if (!is_null($normalized_port)) {
134 2
            $normalized_authority = $normalized_authority . ":" . $normalized_port;
135 2
        }
136
137 4
        return $normalized_authority;
138
    }
139
140
    /**
141
     * Retrieve the user information component of the URI.
142
     *
143
     * If no user information is present, this method MUST return an empty
144
     * string.
145
     *
146
     * If a user is present in the URI, this will return that value;
147
     * additionally, if the password is also present, it will be appended to the
148
     * user value, with a colon (":") separating the values.
149
     *
150
     * The trailing "@" character is not part of the user information and MUST
151
     * NOT be added.
152
     *
153
     * @return string The URI user information, in "username[:password]" format.
154
     */
155 2
    public function getUserInfo()
156
    {
157 2
        return $this->uri_parts["user_info"];
158
    }
159
160
    /**
161
     * Retrieve the host component of the URI.
162
     *
163
     * If no host is present, this method MUST return an empty string.
164
     *
165
     * The value returned MUST be normalized to lowercase, per RFC 3986
166
     * Section 3.2.2.
167
     *
168
     * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
169
     * @return string The URI host.
170
     */
171 3
    public function getHost()
172
    {
173 3
        return strtolower($this->uri_parts["host"]);
174
    }
175
176
    /**
177
     * Retrieve the port component of the URI.
178
     *
179
     * If a port is present, and it is non-standard for the current scheme,
180
     * this method MUST return it as an integer. If the port is the standard port
181
     * used with the current scheme, this method SHOULD return null.
182
     *
183
     * If no port is present, and no scheme is present, this method MUST return
184
     * a null value.
185
     *
186
     * If no port is present, but a scheme is present, this method MAY return
187
     * the standard port for that scheme, but SHOULD return null.
188
     *
189
     * @return null|int The URI port.
190
     */
191 4
    public function getPort()
192
    {
193 4
        $normalized_port = $this->normalizePort();
194
195 4
        return $normalized_port;
196
    }
197
198
    /**
199
     * Retrieve the path component of the URI.
200
     *
201
     * The path can either be empty or absolute (starting with a slash) or
202
     * rootless (not starting with a slash). Implementations MUST support all
203
     * three syntaxes.
204
     *
205
     * Normally, the empty path "" and absolute path "/" are considered equal as
206
     * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
207
     * do this normalization because in contexts with a trimmed base path, e.g.
208
     * the front controller, this difference becomes significant. It's the task
209
     * of the user to handle both "" and "/".
210
     *
211
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
212
     * any characters. To determine what characters to encode, please refer to
213
     * RFC 3986, Sections 2 and 3.3.
214
     *
215
     * As an example, if the value should include a slash ("/") not intended as
216
     * delimiter between path segments, that value MUST be passed in encoded
217
     * form (e.g., "%2F") to the instance.
218
     *
219
     * @see https://tools.ietf.org/html/rfc3986#section-2
220
     * @see https://tools.ietf.org/html/rfc3986#section-3.3
221
     * @return string The URI path.
222
     */
223 8
    public function getPath()
224
    {
225 8
        $path_unencoded = array("/");
226 8
        $allowed        = implode($this->pchar_unencoded) . implode($this->sub_delims) . implode($path_unencoded);
227
228 8
        if ($this->containsUnallowedUriCharacters($this->uri_parts["path"], $allowed)) {
229 4
            $encoded_string = $this->encodeComponent($this->uri_parts["path"], $path_unencoded);
230
231 4
            return $encoded_string;
232
        } else {
233 4
            return $this->uri_parts["path"];
234
        }
235
    }
236
237
    /**
238
     * Retrieve the query string of the URI.
239
     *
240
     * If no query string is present, this method MUST return an empty string.
241
     *
242
     * The leading "?" character is not part of the query and MUST NOT be
243
     * added.
244
     *
245
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
246
     * any characters. To determine what characters to encode, please refer to
247
     * RFC 3986, Sections 2 and 3.4.
248
     *
249
     * As an example, if a value in a key/value pair of the query string should
250
     * include an ampersand ("&") not intended as a delimiter between values,
251
     * that value MUST be passed in encoded form (e.g., "%26") to the instance.
252
     *
253
     * @see https://tools.ietf.org/html/rfc3986#section-2
254
     * @see https://tools.ietf.org/html/rfc3986#section-3.4
255
     * @return string The URI query string.
256
     */
257 4
    public function getQuery()
258
    {
259 4
        return (string) $this->query;
260
    }
261
262
    /**
263
     * Retrieve the fragment component of the URI.
264
     *
265
     * If no fragment is present, this method MUST return an empty string.
266
     *
267
     * The leading "#" character is not part of the fragment and MUST NOT be
268
     * added.
269
     *
270
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
271
     * any characters. To determine what characters to encode, please refer to
272
     * RFC 3986, Sections 2 and 3.5.
273
     *
274
     * @see https://tools.ietf.org/html/rfc3986#section-2
275
     * @see https://tools.ietf.org/html/rfc3986#section-3.5
276
     * @return string The URI fragment.
277
     */
278 4
    public function getFragment()
279
    {
280 4
        return (string) $this->fragment;
281
    }
282
283
    /**
284
     * Return an instance with the specified scheme.
285
     *
286
     * This method MUST retain the state of the current instance, and return
287
     * an instance that contains the specified scheme.
288
     *
289
     * Implementations MUST support the schemes "http" and "https" case
290
     * insensitively, and MAY accommodate other schemes if required.
291
     *
292
     * An empty scheme is equivalent to removing the scheme.
293
     *
294
     * @param string $scheme The scheme to use with the new instance.
295
     * @return static A new instance with the specified scheme.
0 ignored issues
show
Documentation introduced by
Should the return type not be Uri|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
296
     * @throws \InvalidArgumentException for invalid or unsupported schemes.
297
     */
298
    public function withScheme($scheme)
299
    {
300
        // TODO: Implement withScheme() method.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
301
    }
302
303
    /**
304
     * Return an instance with the specified authority.
305
     *
306
     * This method MUST retain the state of the current instance, and return
307
     * an instance that contains the specified authority.
308
     *
309
     * Replacing the authority is equivalent to replacing or removing all authority components depending upon the
310
     * composition of the authority.
311
     *
312
     * An empty authority is equivalent to removing the authority and all authority components.
313
     *
314
     * @param string $authority The scheme to use with the new instance.
315
     * @return static A new instance with the specified authority.
316
     * @throws \InvalidArgumentException for invalid authorities.
317
     */
318 22
    public function withAuthority($authority)
319
    {
320 22
        if (!is_string($authority)) {
321 6
            throw new \InvalidArgumentException("Authority must be a string");
322 16
        } elseif (stristr($authority, "/")) {
323 1
            throw new \InvalidArgumentException("Authority must not contain a slash");
324
        }
325
326 15
        $uri_parts              = $this->uri_parts;
327 15
        $uri_parts["authority"] = $authority;
328
329 15
        $new_authority_string = $this->toString($uri_parts);
330
331 15
        $new_authority_uri = new Uri($new_authority_string);
332
333 15
        return $new_authority_uri;
334
    }
335
336
    /**
337
     * Return an instance with the specified user information.
338
     *
339
     * This method MUST retain the state of the current instance, and return
340
     * an instance that contains the specified user information.
341
     *
342
     * Password is optional, but the user information MUST include the
343
     * user; an empty string for the user is equivalent to removing user
344
     * information.
345
     *
346
     * @param string $user The user name to use for authority.
347
     * @param null|string $password The password associated with $user.
348
     * @return static A new instance with the specified user information.
0 ignored issues
show
Documentation introduced by
Should the return type not be Uri|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
349
     */
350
    public function withUserInfo($user, $password = null)
351
    {
352
        // TODO: Implement withUserInfo() method.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
353
    }
354
355
    /**
356
     * Return an instance with the specified host.
357
     *
358
     * This method MUST retain the state of the current instance, and return
359
     * an instance that contains the specified host.
360
     *
361
     * An empty host value is equivalent to removing the host.
362
     *
363
     * @param string $host The hostname to use with the new instance.
364
     * @return static A new instance with the specified host.
0 ignored issues
show
Documentation introduced by
Should the return type not be Uri|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
365
     * @throws \InvalidArgumentException for invalid hostnames.
366
     */
367
    public function withHost($host)
368
    {
369
        // TODO: Implement withHost() method.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
370
    }
371
372
    /**
373
     * Return an instance with the specified port.
374
     *
375
     * This method MUST retain the state of the current instance, and return
376
     * an instance that contains the specified port.
377
     *
378
     * Implementations MUST raise an exception for ports outside the
379
     * established TCP and UDP port ranges.
380
     *
381
     * A null value provided for the port is equivalent to removing the port
382
     * information.
383
     *
384
     * @param null|int $port The port to use with the new instance; a null value
385
     *     removes the port information.
386
     * @return static A new instance with the specified port.
0 ignored issues
show
Documentation introduced by
Should the return type not be Uri|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
387
     * @throws \InvalidArgumentException for invalid ports.
388
     */
389
    public function withPort($port)
390
    {
391
        // TODO: Implement withPort() method.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
392
    }
393
394
    /**
395
     * Return an instance with the specified path.
396
     *
397
     * This method MUST retain the state of the current instance, and return
398
     * an instance that contains the specified path.
399
     *
400
     * The path can either be empty or absolute (starting with a slash) or
401
     * rootless (not starting with a slash). Implementations MUST support all
402
     * three syntaxes.
403
     *
404
     * If the path is intended to be domain-relative rather than path relative then
405
     * it must begin with a slash ("/"). Paths not starting with a slash ("/")
406
     * are assumed to be relative to some base path known to the application or
407
     * consumer.
408
     *
409
     * Users can provide both encoded and decoded path characters.
410
     * Implementations ensure the correct encoding as outlined in getPath().
411
     *
412
     * @param string $path The path to use with the new instance.
413
     * @return static A new instance with the specified path.
414
     * @throws \InvalidArgumentException for invalid paths.
415
     */
416 18
    public function withPath($path)
417
    {
418 18
        if (!is_string($path)) {
419 6
            throw new \InvalidArgumentException("Supplied path must be a string");
420
        }
421
422 12
        $uri_parts          = $this->uri_parts;
423 12
        $uri_parts["path"]  = $path;
424 12
        $path_string_helper = new StringHelper($path);
425
426 12
        if (!empty($uri_parts["authority"]) && !empty($path) && !$path_string_helper->startsWith("/")) {
427 1
            throw new \InvalidArgumentException("Cannot create a URI with an authority given a rootless path");
428
        }
429
430 11
        $new_path_string = $this->toString($uri_parts);
431
432 11
        $new_path_uri = new Uri($new_path_string);
433
434 11
        return $new_path_uri;
435
    }
436
437
    /**
438
     * Return an instance with the specified query string.
439
     *
440
     * This method MUST retain the state of the current instance, and return
441
     * an instance that contains the specified query string.
442
     *
443
     * Users can provide both encoded and decoded query characters.
444
     * Implementations ensure the correct encoding as outlined in getQuery().
445
     *
446
     * An empty query string value is equivalent to removing the query string.
447
     *
448
     * @param string $query The query string to use with the new instance.
449
     * @return static A new instance with the specified query string.
0 ignored issues
show
Documentation introduced by
Should the return type not be Uri|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
450
     * @throws \InvalidArgumentException for invalid query strings.
451
     */
452
    public function withQuery($query)
453
    {
454
        // TODO: Implement withQuery() method.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
455
    }
456
457
    /**
458
     * Return an instance with the specified URI fragment.
459
     *
460
     * This method MUST retain the state of the current instance, and return
461
     * an instance that contains the specified URI fragment.
462
     *
463
     * Users can provide both encoded and decoded fragment characters.
464
     * Implementations ensure the correct encoding as outlined in getFragment().
465
     *
466
     * An empty fragment value is equivalent to removing the fragment.
467
     *
468
     * @param string $fragment The fragment to use with the new instance.
469
     * @return static A new instance with the specified fragment.
0 ignored issues
show
Documentation introduced by
Should the return type not be Uri|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
470
     */
471
    public function withFragment($fragment)
472
    {
473
        // TODO: Implement withFragment() method.
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
474
    }
475
476
    /**
477
     * Return the string representation as a URI reference.
478
     *
479
     * Depending on which components of the URI are present, the resulting
480
     * string is either a full URI or relative reference according to RFC 3986,
481
     * Section 4.1. The method concatenates the various components of the URI,
482
     * using the appropriate delimiters:
483
     *
484
     * - If a scheme is present, it MUST be suffixed by ":".
485
     * - If an authority is present, it MUST be prefixed by "//".
486
     * - The path can be concatenated without delimiters. But there are two
487
     *   cases where the path has to be adjusted to make the URI reference
488
     *   valid as PHP does not allow to throw an exception in __toString():
489
     *     - If the path is rootless and an authority is present, the path MUST
490
     *       be prefixed by "/".
491
     *     - If the path is starting with more than one "/" and no authority is
492
     *       present, the starting slashes MUST be reduced to one.
493
     * - If a query is present, it MUST be prefixed by "?".
494
     * - If a fragment is present, it MUST be prefixed by "#".
495
     *
496
     * @see http://tools.ietf.org/html/rfc3986#section-4.1
497
     * @return string
498
     */
499 8
    public function __toString()
500
    {
501 8
        return $this->toString($this->uri_parts);
502
    }
503
504
    /**
505
     * @todo Maybe make static?
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
506
     * Converts a given array of URI parts to a string according to the specification of the __toString magic method
507
     *
508
     * @see Uri::__toString
509
     *
510
     * @param array $uri_parts  The URI parts to be combined into a string
511
     * @return string           The string combined from the array of URI parts
512
     */
513 31
    private function toString(array $uri_parts)
514
    {
515 31
        $uri_string = "";
516
517 31
        $uri_string .= $this->scheme->toUriString();
518
519 31
        $uri_string .= $this->authorityToString($uri_parts["authority"]);
520
521 31
        $uri_string .= $this->pathToString($uri_parts["path"], $uri_parts["authority"]);
522
523 31
        $uri_string .= $this->query->toUriString();
524
525 31
        $uri_string .= $this->fragment->toUriString();
526
527 31
        return $uri_string;
528
    }
529
530
    /**
531
     * Splits a string URI into its component parts, returning true if the URI string matches a valid URI's syntax
532
     * and false if the URI string does not
533
     *
534
     * @param string $uri   The URI string to be decomposed
535
     * @return bool         Returns true if the URI string matches a valid URI's syntax
536
     *                      Returns false otherwise
537
     */
538 75
    private function explodeUri($uri)
539
    {
540 75
        $reg_start     = '/^';
541 75
        $scheme_part   = '(?:(?P<scheme>[A-Za-z0-9][^\/\?#:]+):)?';
542 75
        $hier_part     = '(?P<hier_part>[^\?#]+)?';
543 75
        $query_part    = '(?:\?(?P<query>[^#]*))?';
544 75
        $fragment_part = '(?:#(?P<fragment>.*))?';
545 75
        $reg_end       = '/';
546
547 75
        $uri_syntax = $reg_start . $scheme_part . $hier_part . $query_part . $fragment_part . $reg_end;
548
549 75
        $uri_valid = preg_match($uri_syntax, $uri, $parts);
550
551 75
        $this->uri_parts = array_merge($this->uri_parts, $parts); //overwriting default values with matches
552
553 75
        $this->scheme   = new Scheme($this->uri_parts["scheme"]);
554 75
        $this->query    = new Query($this->uri_parts["query"]);
555 75
        $this->fragment = new Fragment($this->uri_parts["fragment"]);
556
557 75
        $this->explodeHierParts($this->uri_parts["hier_part"]);
558
559 75
        $this->sanitizeUriPartsArray();
560
561 75
        return (bool) $uri_valid;
562
    }
563
564
    /**
565
     * Splits URI hierarchy data into authority and path data.
566
     *
567
     * @param string $hier_part     The hierarchy part of a URI to be decomposed
568
     * @return void
569
     */
570 75
    private function explodeHierParts($hier_part)
571
    {
572 75
        $authority_parts = array();
573
574 75
        $reg_start      = '/^';
575 75
        $authority_part = '(?:(?:\/\/)(?P<authority>.[^\/]+))?';
576 75
        $path_part      = '(?P<path>.+)?';
577 75
        $reg_end        = '/';
578
579 75
        $hier_part_syntax = $reg_start . $authority_part . $path_part . $reg_end;
580
581 75
        preg_match($hier_part_syntax, $hier_part, $hier_parts);
582
583 75
        if (isset($hier_parts["authority"])) {
584 74
            $authority_parts = $this->explodeAuthority($hier_parts["authority"]);
585 74
        }
586
587 75
        $hier_parts = array_merge($hier_parts, $authority_parts);
588
589 75
        $this->uri_parts = array_merge($this->uri_parts, $hier_parts);
590 75
    }
591
592
    /**
593
     * Splits URI authority data into user info, host, and port data, returning an array with named keys.
594
     *
595
     * For the host component, it will capture everything within brackets to support ipv6 or match all characters until
596
     * it finds a colon indicating the start of the port component.
597
     *
598
     * @param string $authority     The authority part of a URI to be decomposed
599
     * @return mixed[]              An array with named keys containing the component parts of the supplied
0 ignored issues
show
Documentation introduced by
Should the return type not be array<*,string|integer|null>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
600
     *                              authority
601
     */
602 74
    private function explodeAuthority($authority)
603
    {
604 74
        $reg_start      = '/^';
605 74
        $user_info_part = '(?:(?P<user_info>.+)@)?';
606 74
        $host_part      = '(?P<host>\[.+\]|.[^:]+)';
607 74
        $port_part      = '(?::(?P<port>[0-9]+))?';
608 74
        $reg_end        = '/';
609
610 74
        $authority_syntax = $reg_start . $user_info_part . $host_part . $port_part . $reg_end;
611
612 74
        preg_match($authority_syntax, $authority, $authority_parts);
613
614 74
        if (isset($authority_parts["port"])) {
615 33
            $authority_parts["port"] = (int) $authority_parts["port"];
616 33
        }
617
618 74
        return $authority_parts;
619
    }
620
621
    /**
622
     * Normalizes a port string based on whether the URI's port is standard for its scheme
623
     *
624
     * @return int|null     Returns null if the port is standard for the scheme
625
     *                      Returns the port prepended with a colon if the port is not standard for the scheme
626
     */
627 8
    private function normalizePort()
628
    {
629 8
        $scheme_port_array = new ArrayHelper($this->scheme_ports);
630
631 8
        $standard_port = $scheme_port_array->valueLookup($this->uri_parts["scheme"]);
632
633 8
        if ($this->uri_parts["port"] == $standard_port) {
634 5
            $normalized_port = null;
635 5
        } else {
636 3
            $normalized_port = $this->uri_parts["port"];
637
        }
638
639 8
        return $normalized_port;
640
    }
641
642
    /**
643
     * Sanitizes the URI component array by removing redundant key/value pairs
644
     *
645
     * @return void
646
     */
647 75
    private function sanitizeUriPartsArray()
648
    {
649 75
        $uri_part_array = new ArrayHelper($this->uri_parts);
650
651 75
        $this->uri_parts = $uri_part_array->removeNumericKeys();
652 75
    }
653
654
    /**
655
     * Percent encodes a component string except for sub-delims and unencoded pchar characters as defined by RFC 3986
656
     * in addition to any component-specific unencoded characters
657
     *
658
     * @param string $component_string          The string representing a URI component
659
     * @param string[] $component_unencoded     [OPTIONAL] Any additional unencoded characters specific to the component
660
     *
661
     * @return string                           The string with appropriate characters percent-encoded
662
     */
663 4
    private function encodeComponent($component_string, array $component_unencoded = array())
664
    {
665 4
        $uri_unencoded = array_merge($component_unencoded, $this->sub_delims, $this->pchar_unencoded);
666
667 4
        $string_helper = new StringHelper($component_string);
668
669 4
        $encoded_string = $string_helper->affectChunks("rawurlencode", ...$uri_unencoded);
670
671 4
        return $encoded_string;
672
    }
673
674
    /**
675
     * Determines whether a string contains unallowed URI characters, provided a string of allowed characters for a
676
     * given component.
677
     *
678
     * Note that a percent-encoded character (e.g. %20 for space) automatically counts as an allowed character, whereas
679
     * a percent sign not followed by two hex digits (e.g. %2X) does not count as an allowed character.
680
     *
681
     * @param string $string    The string to be checked for unallowed characters
682
     * @param string $allowed   A string containing all allowed characters for a given component
683
     *
684
     * @return bool             Returns true if the string contains unallowed characters
685
     *                          Returns false if the string contains only allowed characters (including percent-encoded
686
     *                          characters)
687
     */
688 8
    private function containsUnallowedUriCharacters($string, $allowed)
689
    {
690 8
        $allowed = preg_quote($allowed, "/");
691
692 8
        $pattern = "/^([0-9a-zA-Z\\.\\-_~{$allowed}]|%[0-9a-fA-F]{2})*\$/";
693
694 8
        $matches_allowed = preg_match($pattern, $string);
695
696 8
        return (bool) !$matches_allowed;
697
    }
698
699
    /**
700
     * Returns the appropriate authority string based upon __toString specification rules.
701
     *
702
     * @see Uri::__toString()
703
     *
704
     * @param string $authority     The authority to compile into a URI-friendly string
705
     *
706
     * @return string               The URI-friendly authority string
707
     */
708 31
    private function authorityToString($authority)
709
    {
710 31
        $authority_string = "";
711
712 31
        if (!empty($authority)) {
713 23
            $authority_string .= "//" . $authority;
714 23
        }
715
716 31
        return $authority_string;
717
    }
718
719
    /**
720
     * Returns the appropriate path string based upon __toString specification rules.
721
     *
722
     * @see Uri::__toString()
723
     *
724
     * @param string $path          The path to compile into a URI-friendly string
725
     * @param string $authority     [optional] The authority of the URI
726
     *
727
     * @return string               The URI-friendly path string
728
     */
729 31
    private function pathToString($path, $authority = "")
730
    {
731 31
        $path_string        = "";
732 31
        $path_string_helper = new StringHelper($path);
733
734 31
        if (empty($authority)) {
735 9
            $collapsed_slashes = $path_string_helper->collapseStartingRepetition("/");
736
737 9
            $path_string .= $collapsed_slashes;
738 31
        } elseif (!empty($path)) {
739 21
            if (!$path_string_helper->startsWith("/")) {
740 1
                $path_string .= "/" . $path;
741 1
            } else {
742 21
                $path_string .= $path;
743
            }
744 21
        }
745
746 31
        return $path_string;
747
    }
748
}
749