RouteUri   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 129
ccs 36
cts 36
cp 1
rs 10
c 0
b 0
f 0
wmc 19

7 Methods

Rating   Name   Duplication   Size   Complexity  
A withHost() 0 5 1
A withScheme() 0 5 1
A __construct() 0 4 1
A withFragment() 0 7 2
A withPort() 0 11 4
A withQuery() 0 12 3
B __toString() 0 20 7
1
<?php declare(strict_types=1);
2
3
/*
4
 * This file is part of Flight Routing.
5
 *
6
 * PHP version 8.0 and above required
7
 *
8
 * @author    Divine Niiquaye Ibok <[email protected]>
9
 * @copyright 2019 Divine Niiquaye Ibok (https://divinenii.com/)
10
 * @license   https://opensource.org/licenses/BSD-3-Clause License
11
 *
12
 * For the full copyright and license information, please view the LICENSE
13
 * file that was distributed with this source code.
14
 */
15
16
namespace Flight\Routing;
17
18
use Flight\Routing\Exceptions\UrlGenerationException;
19
20
/**
21
 * A generated URI from route made up of only the
22
 * URIs path component (pathinfo, scheme, host, and maybe port.) starting with a slash.
23
 *
24
 * @author Divine Niiquaye Ibok <[email protected]>
25
 */
26
class RouteUri implements \Stringable
27
{
28
    /** Generates an absolute URL, e.g. "http://example.com/dir/file". */
29
    public const ABSOLUTE_URL = 0;
30
31
    /** Generates an absolute path, e.g. "/dir/file". */
32
    public const ABSOLUTE_PATH = 1;
33
34
    /** Generates a path with beginning with a single dot, e.g. "./file". */
35
    public const RELATIVE_PATH = 2;
36
37
    /** Generates a network path, e.g. "//example.com/dir/file". */
38
    public const NETWORK_PATH = 3;
39
40
    /** Adopted from symfony's routing component: Symfony\Component\Routing\Generator::QUERY_FRAGMENT_DECODED */
41
    private const QUERY_DECODED = [
42
        // RFC 3986 explicitly allows those in the query to reference other URIs unencoded
43
        '%2F' => '/',
44
        '%3F' => '?',
45
        // reserved chars that have no special meaning for HTTP URIs in a query
46
        // this excludes esp. "&", "=" and also "+" because PHP would treat it as a space (form-encoded)
47
        '%40' => '@',
48
        '%3A' => ':',
49
        '%21' => '!',
50
        '%3B' => ';',
51
        '%2C' => ',',
52
        '%2A' => '*',
53
    ];
54
55
    private string $pathInfo;
56
    private int $referenceType;
57
    private ?string $scheme = null, $host = null, $port = null;
58
59 12
    public function __construct(string $pathInfo, int $referenceType)
60
    {
61 12
        $this->pathInfo = $pathInfo;
62 12
        $this->referenceType = $referenceType;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 11
    public function __toString()
69
    {
70 11
        $pathInfo = '/'.\ltrim($this->pathInfo, '/');
71
72 11
        if (self::ABSOLUTE_PATH === $type = $this->referenceType) {
73 11
            return $pathInfo;
74
        }
75
76 7
        if (self::RELATIVE_PATH === $type) {
77 1
            return '.'.$pathInfo;
78
        }
79
80 7
        if (isset($this->host)) {
81 1
            $hostPort = $this->host.$this->port;
82
        } else {
83 7
            $h = \explode(':', $_SERVER['HTTP_HOST'] ?? 'localhost:80', 2);
84 7
            $hostPort = $h[0].($this->port ?? (!\in_array($h[1] ?? '', ['', '80', '443'], true) ? ':'.$h[0] : ''));
85
        }
86
87 7
        return (self::NETWORK_PATH === $type ? '//' : (isset($this->scheme) ? $this->scheme.'://' : '//')).$hostPort.$pathInfo;
88
    }
89
90
    /**
91
     * Set the host component of the URI, may include port too.
92
     */
93 7
    public function withHost(string $host): self
94
    {
95 7
        $this->host = $host;
96
97 7
        return $this;
98
    }
99
100
    /**
101
     * Set the scheme component of the URI.
102
     */
103 7
    public function withScheme(string $scheme): self
104
    {
105 7
        $this->scheme = $scheme;
106
107 7
        return $this;
108
    }
109
110
    /**
111
     * Sets the port component of the URI.
112
     */
113 7
    public function withPort(int $port): self
114
    {
115 7
        if (0 > $port || 0xFFFF < $port) {
116 1
            throw new UrlGenerationException(\sprintf('Invalid port: %d. Must be between 0 and 65535', $port));
117
        }
118
119 6
        if (!\in_array($port, [80, 443], true)) {
120 6
            $this->port = ':'.$port;
121
        }
122
123 6
        return $this;
124
    }
125
126
    /**
127
     * Set the query component of the URI.
128
     *
129
     * @param array<int|string,int|string> $queryParams
130
     */
131 6
    public function withQuery(array $queryParams = []): self
132
    {
133
        // Incase query is added to uri.
134 6
        if ([] !== $queryParams) {
135 6
            $queryString = \http_build_query($queryParams, '', '&', \PHP_QUERY_RFC3986);
136
137 6
            if (!empty($queryString)) {
138 6
                $this->pathInfo .= '?'.\strtr($queryString, self::QUERY_DECODED);
139
            }
140
        }
141
142 6
        return $this;
143
    }
144
145
    /**
146
     * Set the fragment component of the URI.
147
     */
148 6
    public function withFragment(string $fragment): self
149
    {
150 6
        if (!empty($fragment)) {
151 6
            $this->pathInfo .= '#'.$fragment;
152
        }
153
154 6
        return $this;
155
    }
156
}
157