Coverage index

src/Helper/VisitorsUrl.php

Lines: 96.30%

LineHitsSource
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) {
2611
    $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 {
3611
    $prefix = NULL;
3711
    if (isset($this->url['scheme'])) {
3811
      switch ($this->url['scheme']) {
3911
        case 'http':
402
          $prefix = 0;
412
          break;
42
4311
        case 'https':
4411
          $prefix = 2;
450
          break;
46
      }
47
    }
48
4911
    if (isset($this->url['host'])) {
5011
      if (strpos($this->url['host'], 'www.') === 0) {
512
        $prefix += 1;
52
      }
53
    }
54
5511
    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 {
6811
    $host = NULL;
6911
    if (isset($this->url['host'])) {
7011
      $host = $this->url['host'];
71
    }
72
    if (
7311
      $host
74
      && $ignore_www
7511
      && strpos($host, 'www.') === 0) {
763
      $host = substr($host, 4);
77
    }
78
7911
    return $host;
80
  }
81
82
  /**
83
   * Get the url.
84
   *
85
   * @return string
86
   *   The url.
87
   */
88
  public function getUrl(): string {
8911
    $host     = $this->getHost() ?? '';
9011
    $port     = isset($this->url['port']) ? ':' . $this->url['port'] : '';
9111
    $path     = $this->url['path'] ?? '';
9211
    $query    = isset($this->url['query']) ? '?' . $this->url['query'] : '';
9311
    $fragment = isset($this->url['fragment']) ? '#' . $this->url['fragment'] : '';
94
9511
    return "$host$port$path$query$fragment";
96
  }
97
98
}