| Total Complexity | 17 |
| Total Lines | 83 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | <?php |
||
| 9 | final class UriBuilder |
||
| 10 | { |
||
| 11 | private string $uri = ''; |
||
| 12 | |||
| 13 | public function withScheme(string $scheme): self |
||
| 14 | { |
||
| 15 | $builder = clone $this; |
||
| 16 | |||
| 17 | if ('' !== $scheme) { |
||
| 18 | $builder->uri .= $scheme . ':'; |
||
| 19 | } |
||
| 20 | |||
| 21 | return $builder; |
||
| 22 | } |
||
| 23 | |||
| 24 | public function withAuthority(string $authority): self |
||
| 25 | { |
||
| 26 | $builder = clone $this; |
||
| 27 | |||
| 28 | if ('' !== $authority) { |
||
| 29 | $builder->uri .= '//' . $authority; |
||
| 30 | } |
||
| 31 | |||
| 32 | return $builder; |
||
| 33 | } |
||
| 34 | |||
| 35 | public function withPath(string $authority, string $path): self |
||
| 36 | { |
||
| 37 | $builder = clone $this; |
||
| 38 | |||
| 39 | if ('' !== $path) { |
||
| 40 | $path = $this->buildPathByAuthority($path, $authority); |
||
| 41 | $builder->uri .= $path; |
||
| 42 | } |
||
| 43 | |||
| 44 | return $builder; |
||
| 45 | } |
||
| 46 | |||
| 47 | public function withQuery(string $query): self |
||
| 48 | { |
||
| 49 | $builder = clone $this; |
||
| 50 | |||
| 51 | if ('' !== $query) { |
||
| 52 | $builder->uri .= '?' . $query; |
||
| 53 | } |
||
| 54 | |||
| 55 | return $builder; |
||
| 56 | } |
||
| 57 | |||
| 58 | public function withFragment(string $fragment): self |
||
| 59 | { |
||
| 60 | $builder = clone $this; |
||
| 61 | |||
| 62 | if ('' !== $fragment) { |
||
| 63 | $builder->uri .= '#' . $fragment; |
||
| 64 | } |
||
| 65 | |||
| 66 | return $builder; |
||
| 67 | } |
||
| 68 | |||
| 69 | /** |
||
| 70 | * @return string |
||
| 71 | */ |
||
| 72 | public function getUri(): string |
||
| 73 | { |
||
| 74 | return $this->uri; |
||
| 75 | } |
||
| 76 | |||
| 77 | private function buildPathByAuthority(string $path, string $authority): string |
||
| 78 | { |
||
| 79 | $newPath = $path; |
||
| 80 | |||
| 81 | if ('/' !== $path[0]) { |
||
| 82 | if ('' !== $authority) { |
||
| 83 | $newPath = '/' . $path; |
||
| 84 | } |
||
| 85 | } elseif (isset($path[1]) and '/' === $path[1]) { |
||
| 86 | if ('' === $authority) { |
||
| 87 | $newPath = '/' . ltrim($path, '/'); |
||
| 88 | } |
||
| 89 | } |
||
| 90 | |||
| 91 | return $newPath; |
||
| 92 | } |
||
| 93 | } |