<?php

declare(strict_types=1);

namespace Drupal\visitors\Helper;

/**
 * A class for preparing URLs for storage.
 */
class VisitorsUrl {

  /**
   * The url.
   *
   * @var array
   */
  protected $url;

  /**
   * The constructor.
   *
   * @param string $url
   *   The url.
   */
  public function __construct(string $url) {
    $this->url = parse_url($url);
  }

  /**
   * Get the prefix.
   *
   * @return int|null
   *   The prefix.
   */
  public function getPrefix(): ?int {
    $prefix = NULL;
    if (isset($this->url['scheme'])) {
      switch ($this->url['scheme']) {
        case 'http':
          $prefix = 0;
          break;

        case 'https':
          $prefix = 2;
          break;
      }
    }

    if (isset($this->url['host'])) {
      if (strpos($this->url['host'], 'www.') === 0) {
        $prefix += 1;
      }
    }

    return $prefix;
  }

  /**
   * Get the host.
   *
   * @param bool $ignore_www
   *   Ignore www.
   *
   * @return string|null
   *   The host.
   */
  public function getHost($ignore_www = TRUE): ?string {
    $host = NULL;
    if (isset($this->url['host'])) {
      $host = $this->url['host'];
    }
    if (
      $host
      && $ignore_www
      && strpos($host, 'www.') === 0) {
      $host = substr($host, 4);
    }

    return $host;
  }

  /**
   * Get the url.
   *
   * @return string
   *   The url.
   */
  public function getUrl(): string {
    $host     = $this->getHost() ?? '';
    $port     = isset($this->url['port']) ? ':' . $this->url['port'] : '';
    $path     = $this->url['path'] ?? '';
    $query    = isset($this->url['query']) ? '?' . $this->url['query'] : '';
    $fragment = isset($this->url['fragment']) ? '#' . $this->url['fragment'] : '';

    return "$host$port$path$query$fragment";
  }

}
