Lines: 96.30%
| Line | Hits | Source |
|---|---|---|
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Drupal\visitors\Helper; | |
| 6 | ||
| 7 | /** | |
| 8 | * A class for preparing URLs for storage. | |
| 9 | */ | |
| 10 | class VisitorsUrl { | |
| 11 | ||
| 12 | /** | |
| 13 | * The url. | |
| 14 | * | |
| 15 | * @var array | |
| 16 | */ | |
| 17 | protected $url; | |
| 18 | ||
| 19 | /** | |
| 20 | * The constructor. | |
| 21 | * | |
| 22 | * @param string $url | |
| 23 | * The url. | |
| 24 | */ | |
| 25 | public function __construct(string $url) { | |
| 26 | 11 | $this->url = parse_url($url); |
| 27 | } | |
| 28 | ||
| 29 | /** | |
| 30 | * Get the prefix. | |
| 31 | * | |
| 32 | * @return int|null | |
| 33 | * The prefix. | |
| 34 | */ | |
| 35 | public function getPrefix(): ?int { | |
| 36 | 11 | $prefix = NULL; |
| 37 | 11 | if (isset($this->url['scheme'])) { |
| 38 | 11 | switch ($this->url['scheme']) { |
| 39 | 11 | case 'http': |
| 40 | 2 | $prefix = 0; |
| 41 | 2 | break; |
| 42 | ||
| 43 | 11 | case 'https': |
| 44 | 11 | $prefix = 2; |
| 45 | 0 | break; |
| 46 | } | |
| 47 | } | |
| 48 | ||
| 49 | 11 | if (isset($this->url['host'])) { |
| 50 | 11 | if (strpos($this->url['host'], 'www.') === 0) { |
| 51 | 2 | $prefix += 1; |
| 52 | } | |
| 53 | } | |
| 54 | ||
| 55 | 11 | return $prefix; |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * Get the host. | |
| 60 | * | |
| 61 | * @param bool $ignore_www | |
| 62 | * Ignore www. | |
| 63 | * | |
| 64 | * @return string|null | |
| 65 | * The host. | |
| 66 | */ | |
| 67 | public function getHost($ignore_www = TRUE): ?string { | |
| 68 | 11 | $host = NULL; |
| 69 | 11 | if (isset($this->url['host'])) { |
| 70 | 11 | $host = $this->url['host']; |
| 71 | } | |
| 72 | if ( | |
| 73 | 11 | $host |
| 74 | && $ignore_www | |
| 75 | 11 | && strpos($host, 'www.') === 0) { |
| 76 | 3 | $host = substr($host, 4); |
| 77 | } | |
| 78 | ||
| 79 | 11 | return $host; |
| 80 | } | |
| 81 | ||
| 82 | /** | |
| 83 | * Get the url. | |
| 84 | * | |
| 85 | * @return string | |
| 86 | * The url. | |
| 87 | */ | |
| 88 | public function getUrl(): string { | |
| 89 | 11 | $host = $this->getHost() ?? ''; |
| 90 | 11 | $port = isset($this->url['port']) ? ':' . $this->url['port'] : ''; |
| 91 | 11 | $path = $this->url['path'] ?? ''; |
| 92 | 11 | $query = isset($this->url['query']) ? '?' . $this->url['query'] : ''; |
| 93 | 11 | $fragment = isset($this->url['fragment']) ? '#' . $this->url['fragment'] : ''; |
| 94 | ||
| 95 | 11 | return "$host$port$path$query$fragment"; |
| 96 | } | |
| 97 | ||
| 98 | } |