Completed
Push — master ( 7a84ca...fefbb0 )
by Derek
04:41
created

Uri::getAuthority()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 22
ccs 8
cts 8
cp 1
rs 9.2
cc 2
eloc 7
nc 2
nop 0
crap 2
1
<?php
2
namespace Subreality\Dilmun\Anshar\Http;
3
4
use Psr\Http\Message\UriInterface;
5
use Subreality\Dilmun\Anshar\Utils\ArrayHelper;
6
7
class Uri implements UriInterface
8
{
9
    use SchemePortsTrait;
10
11
    protected $uri_parts = array(
12
        "scheme"    => "",
13
        "hier_part" => "",
14
        "authority" => "",
15
        "user_info" => "",
16
        "host"      => "",
17
        "port"      => null,
18
        "path"      => "",
19
        "query"     => "",
20
        "fragment"  => "",
21
    );
22
23
    /**
24
     * Uri constructor.  Accepts a string representing a URI and parses the string into the URI's component parts.
25
     *
26
     * @throws \InvalidArgumentException    Throws an \InvalidArgumentException when its parameter is not a string
27
     * @param string $uri
28
     */
29 35
    public function __construct($uri)
30
    {
31 35
        if (!is_string($uri)) {
32 6
            throw new \InvalidArgumentException("New Uri objects must be constructed with a string URI");
33
        }
34
35 29
        $this->explodeUri($uri);
36 29
    }
37
38
    /**
39
     * Retrieve the scheme component of the URI.
40
     *
41
     * If no scheme is present, this method MUST return an empty string.
42
     *
43
     * The value returned MUST be normalized to lowercase, per RFC 3986
44
     * Section 3.1.
45
     *
46
     * The trailing ":" character is not part of the scheme and MUST NOT be
47
     * added.
48
     *
49
     * @see https://tools.ietf.org/html/rfc3986#section-3.1
50
     * @return string The URI scheme.
51
     */
52 5
    public function getScheme()
53
    {
54 5
        return strtolower($this->uri_parts["scheme"]);
55
    }
56
57
    /**
58
     * Retrieve the authority component of the URI.
59
     *
60
     * If no authority information is present, this method MUST return an empty
61
     * string.
62
     *
63
     * The authority syntax of the URI is:
64
     *
65
     * <pre>
66
     * [user-info@]host[:port]
67
     * </pre>
68
     *
69
     * If the port component is not set or is the standard port for the current
70
     * scheme, it SHOULD NOT be included.
71
     *
72
     * @see https://tools.ietf.org/html/rfc3986#section-3.2
73
     * @return string The URI authority, in "[user-info@]host[:port]" format.
74
     */
75 6
    public function getAuthority()
76
    {
77 6
        $normalized_authority = $this->uri_parts["host"];
78
//        $standard_port        = null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
79
80
//        if (array_key_exists($this->getScheme(), $this->scheme_ports)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
81
//            $standard_port = $this->scheme_ports[$this->getScheme()];
82
//        }
83
84 6
        if (!empty($this->uri_parts["user_info"])) {
85 4
            $normalized_authority = $this->uri_parts["user_info"] . "@" . $normalized_authority;
86 4
        }
87
88 6
        $normalized_port      = $this->normalizePort();
89 6
        $normalized_authority = $normalized_authority . $normalized_port;
90
91
//        if (!is_null($this->uri_parts["port"]) && $this->uri_parts["port"] != $standard_port) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
92
//            $normalized_authority = $normalized_authority . ":" . $this->uri_parts["port"];
93
//        }
94
95 6
        return $normalized_authority;
96
    }
97
98
    /**
99
     * Retrieve the user information component of the URI.
100
     *
101
     * If no user information is present, this method MUST return an empty
102
     * string.
103
     *
104
     * If a user is present in the URI, this will return that value;
105
     * additionally, if the password is also present, it will be appended to the
106
     * user value, with a colon (":") separating the values.
107
     *
108
     * The trailing "@" character is not part of the user information and MUST
109
     * NOT be added.
110
     *
111
     * @return string The URI user information, in "username[:password]" format.
112
     */
113 3
    public function getUserInfo()
114
    {
115 3
        return $this->uri_parts["user_info"];
116
    }
117
118
    /**
119
     * Retrieve the host component of the URI.
120
     *
121
     * If no host is present, this method MUST return an empty string.
122
     *
123
     * The value returned MUST be normalized to lowercase, per RFC 3986
124
     * Section 3.2.2.
125
     *
126
     * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
127
     * @return string The URI host.
128
     */
129 3
    public function getHost()
130
    {
131 3
        return $this->uri_parts["host"];
132
    }
133
134
    /**
135
     * Retrieve the port component of the URI.
136
     *
137
     * If a port is present, and it is non-standard for the current scheme,
138
     * this method MUST return it as an integer. If the port is the standard port
139
     * used with the current scheme, this method SHOULD return null.
140
     *
141
     * If no port is present, and no scheme is present, this method MUST return
142
     * a null value.
143
     *
144
     * If no port is present, but a scheme is present, this method MAY return
145
     * the standard port for that scheme, but SHOULD return null.
146
     *
147
     * @return null|int The URI port.
148
     */
149 3
    public function getPort()
150
    {
151 3
        return $this->uri_parts["port"];
152
    }
153
154
    /**
155
     * Retrieve the path component of the URI.
156
     *
157
     * The path can either be empty or absolute (starting with a slash) or
158
     * rootless (not starting with a slash). Implementations MUST support all
159
     * three syntaxes.
160
     *
161
     * Normally, the empty path "" and absolute path "/" are considered equal as
162
     * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
163
     * do this normalization because in contexts with a trimmed base path, e.g.
164
     * the front controller, this difference becomes significant. It's the task
165
     * of the user to handle both "" and "/".
166
     *
167
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
168
     * any characters. To determine what characters to encode, please refer to
169
     * RFC 3986, Sections 2 and 3.3.
170
     *
171
     * As an example, if the value should include a slash ("/") not intended as
172
     * delimiter between path segments, that value MUST be passed in encoded
173
     * form (e.g., "%2F") to the instance.
174
     *
175
     * @see https://tools.ietf.org/html/rfc3986#section-2
176
     * @see https://tools.ietf.org/html/rfc3986#section-3.3
177
     * @return string The URI path.
178
     */
179 3
    public function getPath()
180
    {
181 3
        return $this->uri_parts["path"];
182
    }
183
184
    /**
185
     * Retrieve the query string of the URI.
186
     *
187
     * If no query string is present, this method MUST return an empty string.
188
     *
189
     * The leading "?" character is not part of the query and MUST NOT be
190
     * added.
191
     *
192
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
193
     * any characters. To determine what characters to encode, please refer to
194
     * RFC 3986, Sections 2 and 3.4.
195
     *
196
     * As an example, if a value in a key/value pair of the query string should
197
     * include an ampersand ("&") not intended as a delimiter between values,
198
     * that value MUST be passed in encoded form (e.g., "%26") to the instance.
199
     *
200
     * @see https://tools.ietf.org/html/rfc3986#section-2
201
     * @see https://tools.ietf.org/html/rfc3986#section-3.4
202
     * @return string The URI query string.
203
     */
204 3
    public function getQuery()
205
    {
206 3
        return $this->uri_parts["query"];
207
    }
208
209
    /**
210
     * Retrieve the fragment component of the URI.
211
     *
212
     * If no fragment is present, this method MUST return an empty string.
213
     *
214
     * The leading "#" character is not part of the fragment and MUST NOT be
215
     * added.
216
     *
217
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
218
     * any characters. To determine what characters to encode, please refer to
219
     * RFC 3986, Sections 2 and 3.5.
220
     *
221
     * @see https://tools.ietf.org/html/rfc3986#section-2
222
     * @see https://tools.ietf.org/html/rfc3986#section-3.5
223
     * @return string The URI fragment.
224
     */
225 3
    public function getFragment()
226
    {
227 3
        return $this->uri_parts["fragment"];
228
    }
229
230
    /**
231
     * Return an instance with the specified scheme.
232
     *
233
     * This method MUST retain the state of the current instance, and return
234
     * an instance that contains the specified scheme.
235
     *
236
     * Implementations MUST support the schemes "http" and "https" case
237
     * insensitively, and MAY accommodate other schemes if required.
238
     *
239
     * An empty scheme is equivalent to removing the scheme.
240
     *
241
     * @param string $scheme The scheme to use with the new instance.
242
     * @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...
243
     * @throws \InvalidArgumentException for invalid or unsupported schemes.
244
     */
245
    public function withScheme($scheme)
246
    {
247
        // 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...
248
    }
249
250
    /**
251
     * Return an instance with the specified user information.
252
     *
253
     * This method MUST retain the state of the current instance, and return
254
     * an instance that contains the specified user information.
255
     *
256
     * Password is optional, but the user information MUST include the
257
     * user; an empty string for the user is equivalent to removing user
258
     * information.
259
     *
260
     * @param string $user The user name to use for authority.
261
     * @param null|string $password The password associated with $user.
262
     * @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...
263
     */
264
    public function withUserInfo($user, $password = null)
265
    {
266
        // 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...
267
    }
268
269
    /**
270
     * Return an instance with the specified host.
271
     *
272
     * This method MUST retain the state of the current instance, and return
273
     * an instance that contains the specified host.
274
     *
275
     * An empty host value is equivalent to removing the host.
276
     *
277
     * @param string $host The hostname to use with the new instance.
278
     * @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...
279
     * @throws \InvalidArgumentException for invalid hostnames.
280
     */
281
    public function withHost($host)
282
    {
283
        // 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...
284
    }
285
286
    /**
287
     * Return an instance with the specified port.
288
     *
289
     * This method MUST retain the state of the current instance, and return
290
     * an instance that contains the specified port.
291
     *
292
     * Implementations MUST raise an exception for ports outside the
293
     * established TCP and UDP port ranges.
294
     *
295
     * A null value provided for the port is equivalent to removing the port
296
     * information.
297
     *
298
     * @param null|int $port The port to use with the new instance; a null value
299
     *     removes the port information.
300
     * @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...
301
     * @throws \InvalidArgumentException for invalid ports.
302
     */
303
    public function withPort($port)
304
    {
305
        // 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...
306
    }
307
308
    /**
309
     * Return an instance with the specified path.
310
     *
311
     * This method MUST retain the state of the current instance, and return
312
     * an instance that contains the specified path.
313
     *
314
     * The path can either be empty or absolute (starting with a slash) or
315
     * rootless (not starting with a slash). Implementations MUST support all
316
     * three syntaxes.
317
     *
318
     * If the path is intended to be domain-relative rather than path relative then
319
     * it must begin with a slash ("/"). Paths not starting with a slash ("/")
320
     * are assumed to be relative to some base path known to the application or
321
     * consumer.
322
     *
323
     * Users can provide both encoded and decoded path characters.
324
     * Implementations ensure the correct encoding as outlined in getPath().
325
     *
326
     * @param string $path The path to use with the new instance.
327
     * @return static A new instance with the specified path.
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...
328
     * @throws \InvalidArgumentException for invalid paths.
329
     */
330
    public function withPath($path)
331
    {
332
        // TODO: Implement withPath() 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...
333
    }
334
335
    /**
336
     * Return an instance with the specified query string.
337
     *
338
     * This method MUST retain the state of the current instance, and return
339
     * an instance that contains the specified query string.
340
     *
341
     * Users can provide both encoded and decoded query characters.
342
     * Implementations ensure the correct encoding as outlined in getQuery().
343
     *
344
     * An empty query string value is equivalent to removing the query string.
345
     *
346
     * @param string $query The query string to use with the new instance.
347
     * @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...
348
     * @throws \InvalidArgumentException for invalid query strings.
349
     */
350
    public function withQuery($query)
351
    {
352
        // 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...
353
    }
354
355
    /**
356
     * Return an instance with the specified URI fragment.
357
     *
358
     * This method MUST retain the state of the current instance, and return
359
     * an instance that contains the specified URI fragment.
360
     *
361
     * Users can provide both encoded and decoded fragment characters.
362
     * Implementations ensure the correct encoding as outlined in getFragment().
363
     *
364
     * An empty fragment value is equivalent to removing the fragment.
365
     *
366
     * @param string $fragment The fragment to use with the new instance.
367
     * @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...
368
     */
369
    public function withFragment($fragment)
370
    {
371
        // 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...
372
    }
373
374
    /**
375
     * Return the string representation as a URI reference.
376
     *
377
     * Depending on which components of the URI are present, the resulting
378
     * string is either a full URI or relative reference according to RFC 3986,
379
     * Section 4.1. The method concatenates the various components of the URI,
380
     * using the appropriate delimiters:
381
     *
382
     * - If a scheme is present, it MUST be suffixed by ":".
383
     * - If an authority is present, it MUST be prefixed by "//".
384
     * - The path can be concatenated without delimiters. But there are two
385
     *   cases where the path has to be adjusted to make the URI reference
386
     *   valid as PHP does not allow to throw an exception in __toString():
387
     *     - If the path is rootless and an authority is present, the path MUST
388
     *       be prefixed by "/".
389
     *     - If the path is starting with more than one "/" and no authority is
390
     *       present, the starting slashes MUST be reduced to one.
391
     * - If a query is present, it MUST be prefixed by "?".
392
     * - If a fragment is present, it MUST be prefixed by "#".
393
     *
394
     * @see http://tools.ietf.org/html/rfc3986#section-4.1
395
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|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...
396
     */
397
    public function __toString()
398
    {
399
        // TODO: Implement __toString() 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...
400
    }
401
402
    /**
403
     * Splits a string URI into its component parts, returning true if the URI string matches a valid URI's syntax
404
     * and false if the URI string does not
405
     *
406
     * @param string $uri   The URI string to be decomposed
407
     * @return bool         Returns true if the URI string matches a valid URI's syntax
408
     *                      Returns false otherwise
409
     */
410 29
    private function explodeUri($uri)
411
    {
412 29
        $reg_start        = '/^';
413 29
        $scheme_part      = '(?P<scheme>.[^:]+)';
414 29
        $scheme_separator = ':';
415 29
        $hier_part        = '(?<hier_part>.[^\?#]+)';
416 29
        $query_part       = '(?:\?(?P<query>.[^#]+))?';
417 29
        $fragment_part    = '(?:#(?P<fragment>.+))?';
418 29
        $reg_end          = '/';
419
420 29
        $uri_syntax = $reg_start . $scheme_part . $scheme_separator . $hier_part . $query_part . $fragment_part .
421 29
            $reg_end;
422
423 29
        $uri_valid = preg_match($uri_syntax, $uri, $parts);
424
425 29
        $this->uri_parts = array_merge($this->uri_parts, $parts); //overwriting default values with matches
426
427 29
        $hier_parts = $this->explodeHierParts($this->uri_parts["hier_part"]);
428
429 29
        $this->uri_parts = array_merge($this->uri_parts, $hier_parts);
430
431 29
        return (bool) $uri_valid;
432
    }
433
434
    /**
435
     * Splits URI hierarchy data into authority and path data, returning an array with named keys
436
     *
437
     * @param string $hier_part     The hierarchy part of a URI to be decomposed
438
     * @return string[]             An array with named keys containing the component parts of the supplied
439
     *                              hierarchy
440
     */
441 29
    private function explodeHierParts($hier_part)
442
    {
443 29
        $authority_parts = array();
444
445 29
        $reg_start      = '/^';
446 29
        $authority_part = '(?:(?:\/\/)(?P<authority>.[^\/]+))?';
447 29
        $path_part      = '(?P<path>.+)';
448 29
        $reg_end        = '/';
449
450 29
        $hier_part_syntax = $reg_start . $authority_part . $path_part . $reg_end;
451
452 29
        preg_match($hier_part_syntax, $hier_part, $hier_parts);
453
454 29
        if (isset($hier_parts["authority"])) {
455 19
            $authority_parts = $this->explodeAuthority($hier_parts["authority"]);
456 19
        }
457
458 29
        $hier_parts = array_merge($hier_parts, $authority_parts);
459
460 29
        return $hier_parts;
461
    }
462
463
    /**
464
     * Splits URI authority data into user info, host, and port data, returning an array with named keys
465
     *
466
     * @param string $authority     The authority part of a URI to be decomposed
467
     * @return (string|int|null)[]  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...
468
     *                              authority
469
     */
470 19
    private function explodeAuthority($authority)
471
    {
472 19
        $reg_start      = '/^';
473 19
        $user_info_part = '(?:(?P<user_info>.+)@)?';
474 19
        $host_part      = '(?P<host>.[^:]+)';
475 19
        $port_part      = '(?::(?P<port>[0-9]+))?';
476 19
        $reg_end        = '/';
477
478 19
        $authority_syntax = $reg_start . $user_info_part . $host_part . $port_part . $reg_end;
479
480 19
        preg_match($authority_syntax, $authority, $authority_parts);
481
482 19
        if (isset($authority_parts["port"])) {
483 10
            $authority_parts["port"] = (int) $authority_parts["port"];
484 10
        }
485
486 19
        return $authority_parts;
487
    }
488
489
    /**
490
     * Normalizes a port string based on whether the URI's port is standard for its scheme
491
     *
492
     * @return string   Returns an empty string if the port is standard for the scheme
493
     *                  Returns the port prepended with a colon if the port is not standard for the scheme
494
     */
495 6
    private function normalizePort()
496
    {
497 6
        $scheme_port_array = new ArrayHelper($this->scheme_ports);
498
499 6
        $standard_port = $scheme_port_array->valueLookup($this->uri_parts["scheme"]);
500
501 6
        if ($this->uri_parts["port"] == $standard_port) {
502 4
            $normalized_port = "";
503 4
        } else {
504 2
            $normalized_port = ":{$this->uri_parts["port"]}";
505
        }
506
507 6
        return $normalized_port;
508
    }
509
}
510