Completed
Push — master ( 15cc44...023ce1 )
by Derek
02:07
created

Uri::queryToString()   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\Query;
6
use Subreality\Dilmun\Anshar\Http\UriParts\Scheme;
7
use Subreality\Dilmun\Anshar\Utils\ArrayHelper;
8
use Subreality\Dilmun\Anshar\Utils\StringHelper;
9
10
/**
11
 * Class Uri
12
 * @package Subreality\Dilmun\Anshar\Http
13
 */
14
class Uri implements UriInterface
15
{
16
    use SchemePortsTrait;
17
18
    protected $uri_parts = array(
19
        "scheme"    => "",
20
        "hier_part" => "",
21
        "authority" => "",
22
        "user_info" => "",
23
        "host"      => "",
24
        "port"      => null,
25
        "path"      => "",
26
        "query"     => "",
27
        "fragment"  => "",
28
    );
29
30
    /** @var  Scheme */
31
    protected $scheme;
32
    /** @var  Query */
33
    protected $query;
34
35
    protected $sub_delims = array(
36
        "!",
37
        "$",
38
        "&",
39
        "'",
40
        "(",
41
        ")",
42
        "*",
43
        "+",
44
        ",",
45
        ";",
46
        "=",
47
    );
48
49
    protected $pchar_unencoded = array(
50
        ":",
51
        "@",
52
    );
53
54
    /**
55
     * Uri constructor.  Accepts a string representing a URI and parses the string into the URI's component parts.
56
     *
57
     * @throws \InvalidArgumentException    Throws an \InvalidArgumentException when its parameter is not a string
58
     * @param string $uri
59
     */
60 81
    public function __construct($uri)
61
    {
62 81
        if (!is_string($uri)) {
63 6
            throw new \InvalidArgumentException("New Uri objects must be constructed with a string URI");
64
        }
65
66 75
        $this->explodeUri($uri);
67 75
    }
68
69
    /**
70
     * @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...
71
     * Retrieve the parsed components of the URI string.
72
     *
73
     * If the class was provided an invalid URI string, URI components will be empty strings, except port, which will
74
     * be null
75
     *
76
     * @return mixed[]
77
     */
78 34
    public function getParsedUri()
79
    {
80 34
        return $this->uri_parts;
81
    }
82
83
    /**
84
     * Retrieve the scheme component of the URI.
85
     *
86
     * If no scheme is present, this method MUST return an empty string.
87
     *
88
     * The value returned MUST be normalized to lowercase, per RFC 3986
89
     * Section 3.1.
90
     *
91
     * The trailing ":" character is not part of the scheme and MUST NOT be
92
     * added.
93
     *
94
     * @see https://tools.ietf.org/html/rfc3986#section-3.1
95
     * @return string The URI scheme.
96
     */
97 3
    public function getScheme()
98
    {
99 3
        return strtolower($this->scheme);
100
    }
101
102
    /**
103
     * Retrieve the authority component of the URI.
104
     *
105
     * If no authority information is present, this method MUST return an empty
106
     * string.
107
     *
108
     * The authority syntax of the URI is:
109
     *
110
     * <pre>
111
     * [user-info@]host[:port]
112
     * </pre>
113
     *
114
     * If the port component is not set or is the standard port for the current
115
     * scheme, it SHOULD NOT be included.
116
     *
117
     * @see https://tools.ietf.org/html/rfc3986#section-3.2
118
     * @return string The URI authority, in "[user-info@]host[:port]" format.
119
     */
120 4
    public function getAuthority()
121
    {
122 4
        $normalized_authority = $this->uri_parts["host"];
123
124 4
        if (!empty($this->uri_parts["user_info"])) {
125 4
            $normalized_authority = $this->uri_parts["user_info"] . "@" . $normalized_authority;
126 4
        }
127
128 4
        $normalized_port = $this->normalizePort();
129
130 4
        if (!is_null($normalized_port)) {
131 2
            $normalized_authority = $normalized_authority . ":" . $normalized_port;
132 2
        }
133
134 4
        return $normalized_authority;
135
    }
136
137
    /**
138
     * Retrieve the user information component of the URI.
139
     *
140
     * If no user information is present, this method MUST return an empty
141
     * string.
142
     *
143
     * If a user is present in the URI, this will return that value;
144
     * additionally, if the password is also present, it will be appended to the
145
     * user value, with a colon (":") separating the values.
146
     *
147
     * The trailing "@" character is not part of the user information and MUST
148
     * NOT be added.
149
     *
150
     * @return string The URI user information, in "username[:password]" format.
151
     */
152 2
    public function getUserInfo()
153
    {
154 2
        return $this->uri_parts["user_info"];
155
    }
156
157
    /**
158
     * Retrieve the host component of the URI.
159
     *
160
     * If no host is present, this method MUST return an empty string.
161
     *
162
     * The value returned MUST be normalized to lowercase, per RFC 3986
163
     * Section 3.2.2.
164
     *
165
     * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
166
     * @return string The URI host.
167
     */
168 3
    public function getHost()
169
    {
170 3
        return strtolower($this->uri_parts["host"]);
171
    }
172
173
    /**
174
     * Retrieve the port component of the URI.
175
     *
176
     * If a port is present, and it is non-standard for the current scheme,
177
     * this method MUST return it as an integer. If the port is the standard port
178
     * used with the current scheme, this method SHOULD return null.
179
     *
180
     * If no port is present, and no scheme is present, this method MUST return
181
     * a null value.
182
     *
183
     * If no port is present, but a scheme is present, this method MAY return
184
     * the standard port for that scheme, but SHOULD return null.
185
     *
186
     * @return null|int The URI port.
187
     */
188 4
    public function getPort()
189
    {
190 4
        $normalized_port = $this->normalizePort();
191
192 4
        return $normalized_port;
193
    }
194
195
    /**
196
     * Retrieve the path component of the URI.
197
     *
198
     * The path can either be empty or absolute (starting with a slash) or
199
     * rootless (not starting with a slash). Implementations MUST support all
200
     * three syntaxes.
201
     *
202
     * Normally, the empty path "" and absolute path "/" are considered equal as
203
     * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
204
     * do this normalization because in contexts with a trimmed base path, e.g.
205
     * the front controller, this difference becomes significant. It's the task
206
     * of the user to handle both "" and "/".
207
     *
208
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
209
     * any characters. To determine what characters to encode, please refer to
210
     * RFC 3986, Sections 2 and 3.3.
211
     *
212
     * As an example, if the value should include a slash ("/") not intended as
213
     * delimiter between path segments, that value MUST be passed in encoded
214
     * form (e.g., "%2F") to the instance.
215
     *
216
     * @see https://tools.ietf.org/html/rfc3986#section-2
217
     * @see https://tools.ietf.org/html/rfc3986#section-3.3
218
     * @return string The URI path.
219
     */
220 8
    public function getPath()
221
    {
222 8
        $path_unencoded = array("/");
223 8
        $allowed        = implode($this->pchar_unencoded) . implode($this->sub_delims) . implode($path_unencoded);
224
225 8
        if ($this->containsUnallowedUriCharacters($this->uri_parts["path"], $allowed)) {
226 4
            $encoded_string = $this->encodeComponent($this->uri_parts["path"], $path_unencoded);
227
228 4
            return $encoded_string;
229
        } else {
230 4
            return $this->uri_parts["path"];
231
        }
232
    }
233
234
    /**
235
     * Retrieve the query string of the URI.
236
     *
237
     * If no query string is present, this method MUST return an empty string.
238
     *
239
     * The leading "?" character is not part of the query and MUST NOT be
240
     * added.
241
     *
242
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
243
     * any characters. To determine what characters to encode, please refer to
244
     * RFC 3986, Sections 2 and 3.4.
245
     *
246
     * As an example, if a value in a key/value pair of the query string should
247
     * include an ampersand ("&") not intended as a delimiter between values,
248
     * that value MUST be passed in encoded form (e.g., "%26") to the instance.
249
     *
250
     * @see https://tools.ietf.org/html/rfc3986#section-2
251
     * @see https://tools.ietf.org/html/rfc3986#section-3.4
252
     * @return string The URI query string.
253
     */
254 4
    public function getQuery()
255
    {
256 4
        return (string) $this->query;
257
    }
258
259
    /**
260
     * Retrieve the fragment component of the URI.
261
     *
262
     * If no fragment is present, this method MUST return an empty string.
263
     *
264
     * The leading "#" character is not part of the fragment and MUST NOT be
265
     * added.
266
     *
267
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
268
     * any characters. To determine what characters to encode, please refer to
269
     * RFC 3986, Sections 2 and 3.5.
270
     *
271
     * @see https://tools.ietf.org/html/rfc3986#section-2
272
     * @see https://tools.ietf.org/html/rfc3986#section-3.5
273
     * @return string The URI fragment.
274
     */
275 4
    public function getFragment()
276
    {
277 4
        $fragment_unencoded = array("/", "?");
278
279 4
        $encoded_string = $this->encodeComponent($this->uri_parts["fragment"], $fragment_unencoded);
280
281 4
        return $encoded_string;
282
    }
283
284
    /**
285
     * Return an instance with the specified scheme.
286
     *
287
     * This method MUST retain the state of the current instance, and return
288
     * an instance that contains the specified scheme.
289
     *
290
     * Implementations MUST support the schemes "http" and "https" case
291
     * insensitively, and MAY accommodate other schemes if required.
292
     *
293
     * An empty scheme is equivalent to removing the scheme.
294
     *
295
     * @param string $scheme The scheme to use with the new instance.
296
     * @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...
297
     * @throws \InvalidArgumentException for invalid or unsupported schemes.
298
     */
299
    public function withScheme($scheme)
300
    {
301
        // 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...
302
    }
303
304
    /**
305
     * Return an instance with the specified authority.
306
     *
307
     * This method MUST retain the state of the current instance, and return
308
     * an instance that contains the specified authority.
309
     *
310
     * Replacing the authority is equivalent to replacing or removing all authority components depending upon the
311
     * composition of the authority.
312
     *
313
     * An empty authority is equivalent to removing the authority and all authority components.
314
     *
315
     * @param string $authority The scheme to use with the new instance.
316
     * @return static A new instance with the specified authority.
317
     * @throws \InvalidArgumentException for invalid authorities.
318
     */
319 22
    public function withAuthority($authority)
320
    {
321 22
        if (!is_string($authority)) {
322 6
            throw new \InvalidArgumentException("Authority must be a string");
323 16
        } elseif (stristr($authority, "/")) {
324 1
            throw new \InvalidArgumentException("Authority must not contain a slash");
325
        }
326
327 15
        $uri_parts              = $this->uri_parts;
328 15
        $uri_parts["authority"] = $authority;
329
330 15
        $new_authority_string = $this->toString($uri_parts);
331
332 15
        $new_authority_uri = new Uri($new_authority_string);
333
334 15
        return $new_authority_uri;
335
    }
336
337
    /**
338
     * Return an instance with the specified user information.
339
     *
340
     * This method MUST retain the state of the current instance, and return
341
     * an instance that contains the specified user information.
342
     *
343
     * Password is optional, but the user information MUST include the
344
     * user; an empty string for the user is equivalent to removing user
345
     * information.
346
     *
347
     * @param string $user The user name to use for authority.
348
     * @param null|string $password The password associated with $user.
349
     * @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...
350
     */
351
    public function withUserInfo($user, $password = null)
352
    {
353
        // 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...
354
    }
355
356
    /**
357
     * Return an instance with the specified host.
358
     *
359
     * This method MUST retain the state of the current instance, and return
360
     * an instance that contains the specified host.
361
     *
362
     * An empty host value is equivalent to removing the host.
363
     *
364
     * @param string $host The hostname to use with the new instance.
365
     * @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...
366
     * @throws \InvalidArgumentException for invalid hostnames.
367
     */
368
    public function withHost($host)
369
    {
370
        // 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...
371
    }
372
373
    /**
374
     * Return an instance with the specified port.
375
     *
376
     * This method MUST retain the state of the current instance, and return
377
     * an instance that contains the specified port.
378
     *
379
     * Implementations MUST raise an exception for ports outside the
380
     * established TCP and UDP port ranges.
381
     *
382
     * A null value provided for the port is equivalent to removing the port
383
     * information.
384
     *
385
     * @param null|int $port The port to use with the new instance; a null value
386
     *     removes the port information.
387
     * @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...
388
     * @throws \InvalidArgumentException for invalid ports.
389
     */
390
    public function withPort($port)
391
    {
392
        // 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...
393
    }
394
395
    /**
396
     * Return an instance with the specified path.
397
     *
398
     * This method MUST retain the state of the current instance, and return
399
     * an instance that contains the specified path.
400
     *
401
     * The path can either be empty or absolute (starting with a slash) or
402
     * rootless (not starting with a slash). Implementations MUST support all
403
     * three syntaxes.
404
     *
405
     * If the path is intended to be domain-relative rather than path relative then
406
     * it must begin with a slash ("/"). Paths not starting with a slash ("/")
407
     * are assumed to be relative to some base path known to the application or
408
     * consumer.
409
     *
410
     * Users can provide both encoded and decoded path characters.
411
     * Implementations ensure the correct encoding as outlined in getPath().
412
     *
413
     * @param string $path The path to use with the new instance.
414
     * @return static A new instance with the specified path.
415
     * @throws \InvalidArgumentException for invalid paths.
416
     */
417 18
    public function withPath($path)
418
    {
419 18
        if (!is_string($path)) {
420 6
            throw new \InvalidArgumentException("Supplied path must be a string");
421
        }
422
423 12
        $uri_parts          = $this->uri_parts;
424 12
        $uri_parts["path"]  = $path;
425 12
        $path_string_helper = new StringHelper($path);
426
427 12
        if (!empty($uri_parts["authority"]) && !empty($path) && !$path_string_helper->startsWith("/")) {
428 1
            throw new \InvalidArgumentException("Cannot create a URI with an authority given a rootless path");
429
        }
430
431 11
        $new_path_string = $this->toString($uri_parts);
432
433 11
        $new_path_uri = new Uri($new_path_string);
434
435 11
        return $new_path_uri;
436
    }
437
438
    /**
439
     * Return an instance with the specified query string.
440
     *
441
     * This method MUST retain the state of the current instance, and return
442
     * an instance that contains the specified query string.
443
     *
444
     * Users can provide both encoded and decoded query characters.
445
     * Implementations ensure the correct encoding as outlined in getQuery().
446
     *
447
     * An empty query string value is equivalent to removing the query string.
448
     *
449
     * @param string $query The query string to use with the new instance.
450
     * @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...
451
     * @throws \InvalidArgumentException for invalid query strings.
452
     */
453
    public function withQuery($query)
454
    {
455
        // 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...
456
    }
457
458
    /**
459
     * Return an instance with the specified URI fragment.
460
     *
461
     * This method MUST retain the state of the current instance, and return
462
     * an instance that contains the specified URI fragment.
463
     *
464
     * Users can provide both encoded and decoded fragment characters.
465
     * Implementations ensure the correct encoding as outlined in getFragment().
466
     *
467
     * An empty fragment value is equivalent to removing the fragment.
468
     *
469
     * @param string $fragment The fragment to use with the new instance.
470
     * @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...
471
     */
472
    public function withFragment($fragment)
473
    {
474
        // 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...
475
    }
476
477
    /**
478
     * Return the string representation as a URI reference.
479
     *
480
     * Depending on which components of the URI are present, the resulting
481
     * string is either a full URI or relative reference according to RFC 3986,
482
     * Section 4.1. The method concatenates the various components of the URI,
483
     * using the appropriate delimiters:
484
     *
485
     * - If a scheme is present, it MUST be suffixed by ":".
486
     * - If an authority is present, it MUST be prefixed by "//".
487
     * - The path can be concatenated without delimiters. But there are two
488
     *   cases where the path has to be adjusted to make the URI reference
489
     *   valid as PHP does not allow to throw an exception in __toString():
490
     *     - If the path is rootless and an authority is present, the path MUST
491
     *       be prefixed by "/".
492
     *     - If the path is starting with more than one "/" and no authority is
493
     *       present, the starting slashes MUST be reduced to one.
494
     * - If a query is present, it MUST be prefixed by "?".
495
     * - If a fragment is present, it MUST be prefixed by "#".
496
     *
497
     * @see http://tools.ietf.org/html/rfc3986#section-4.1
498
     * @return string
499
     */
500 8
    public function __toString()
501
    {
502 8
        return $this->toString($this->uri_parts);
503
    }
504
505
    /**
506
     * @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...
507
     * Converts a given array of URI parts to a string according to the specification of the __toString magic method
508
     *
509
     * @see Uri::__toString
510
     *
511
     * @param array $uri_parts  The URI parts to be combined into a string
512
     * @return string           The string combined from the array of URI parts
513
     */
514 31
    private function toString(array $uri_parts)
515
    {
516 31
        $uri_string = "";
517
518 31
        $uri_string .= $this->scheme->toUriString();
519
520 31
        $uri_string .= $this->authorityToString($uri_parts["authority"]);
521
522 31
        $uri_string .= $this->pathToString($uri_parts["path"], $uri_parts["authority"]);
523
524 31
        $uri_string .= $this->query->toUriString();
525
526 31
        $uri_string .= $this->fragmentToString($uri_parts["fragment"]);
527
528 31
        return $uri_string;
529
    }
530
531
    /**
532
     * Splits a string URI into its component parts, returning true if the URI string matches a valid URI's syntax
533
     * and false if the URI string does not
534
     *
535
     * @param string $uri   The URI string to be decomposed
536
     * @return bool         Returns true if the URI string matches a valid URI's syntax
537
     *                      Returns false otherwise
538
     */
539 75
    private function explodeUri($uri)
540
    {
541 75
        $reg_start     = '/^';
542 75
        $scheme_part   = '(?:(?P<scheme>[A-Za-z0-9][^\/\?#:]+):)?';
543 75
        $hier_part     = '(?P<hier_part>[^\?#]+)?';
544 75
        $query_part    = '(?:\?(?P<query>[^#]*))?';
545 75
        $fragment_part = '(?:#(?P<fragment>.*))?';
546 75
        $reg_end       = '/';
547
548 75
        $uri_syntax = $reg_start . $scheme_part . $hier_part . $query_part . $fragment_part . $reg_end;
549
550 75
        $uri_valid = preg_match($uri_syntax, $uri, $parts);
551
552 75
        $this->uri_parts = array_merge($this->uri_parts, $parts); //overwriting default values with matches
553
554 75
        $this->scheme = new Scheme($this->uri_parts["scheme"]);
555 75
        $this->query  = new Query($this->uri_parts["query"]);
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 8
    private function encodeComponent($component_string, array $component_unencoded = array())
664
    {
665 8
        $uri_unencoded = array_merge($component_unencoded, $this->sub_delims, $this->pchar_unencoded);
666
667 8
        $string_helper = new StringHelper($component_string);
668
669 8
        $encoded_string = $string_helper->affectChunks("rawurlencode", ...$uri_unencoded);
670
671 8
        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
    /**
750
     * Returns the appropriate fragment string based upon __toString specification rules.
751
     *
752
     * @see Uri::__toString()
753
     *
754
     * @param string $fragment  The fragment to compile into a URI-friendly string
755
     *
756
     * @return string           The URI-friendly fragment string
757
     */
758 31
    private function fragmentToString($fragment)
759
    {
760 31
        $fragment_string = "";
761
762 31
        if (!empty($fragment)) {
763 27
            $fragment_string .= "#" . $fragment;
764 27
        }
765
766 31
        return $fragment_string;
767
    }
768
}
769