Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
VisitorsUrl
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
4 / 4
16
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getPrefix
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
6
 getHost
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 getUrl
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Drupal\visitors\Helper;
6
7/**
8 * A class for preparing URLs for storage.
9 */
10class 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    $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    $prefix = NULL;
37    if (isset($this->url['scheme'])) {
38      switch ($this->url['scheme']) {
39        case 'http':
40          $prefix = 0;
41          break;
42
43        case 'https':
44          $prefix = 2;
45          break;
46      }
47    }
48
49    if (isset($this->url['host'])) {
50      if (strpos($this->url['host'], 'www.') === 0) {
51        $prefix += 1;
52      }
53    }
54
55    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    $host = NULL;
69    if (isset($this->url['host'])) {
70      $host = $this->url['host'];
71    }
72    if (
73      $host
74      && $ignore_www
75      && strpos($host, 'www.') === 0) {
76      $host = substr($host, 4);
77    }
78
79    return $host;
80  }
81
82  /**
83   * Get the url.
84   *
85   * @return string
86   *   The url.
87   */
88  public function getUrl(): string {
89    $host     = $this->getHost() ?? '';
90    $port     = isset($this->url['port']) ? ':' . $this->url['port'] : '';
91    $path     = $this->url['path'] ?? '';
92    $query    = isset($this->url['query']) ? '?' . $this->url['query'] : '';
93    $fragment = isset($this->url['fragment']) ? '#' . $this->url['fragment'] : '';
94
95    return "$host$port$path$query$fragment";
96  }
97
98}