<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\api\Libraries\Content\Udf;

use Drupal\languagewire_translation_provider\api\Helpers\Ensure;
use Laminas\Diactoros\Uri as LaminasUri;

/**
 * Uri.
 *
 * Represents a URI in the format applicable to LanguageWire platform.
 * The URI string is validated upon object construction,
 * namely the protocol and length will be checked.
 * Constraints on the URI:
 * * Scheme must be specified and must be either HTTP or HTTPS
 * * URI cannot be longer than 256 characters.
 *
 * Note.
 * The link should be publicly accessible without any restrictions.
* */
final class Uri extends LaminasUri {
  private const MAX_LENGTH = 256;

  /**
   * Constructs a new Uri object.
   *
   * @param string $uri
   *   URI string.
   */
  public function __construct(string $uri) {
    parent::__construct($uri);
    $this->validate($uri);
  }

  /**
   * To String .
   *
   * @return string
   *   URI string.
   */
  public function toString(): string {
    return $this->__toString();
  }

  /**
   * Validate .
   *
   * @param string $uri
   *   URI string.
   */
  private function validate(string $uri): void {
    $this->mustUseProperScheme($uri);
    Ensure::notLongerThan($uri, self::MAX_LENGTH, 'URI');
  }

  /**
   * Must Use Proper Scheme .
   *
   * @param string $uri
   *   URI string.
   */
  private function mustUseProperScheme(string $uri): void {
    if (!preg_match('#^(http|https)://#', $uri)) {
      throw new \InvalidArgumentException("Unsupported or missing scheme. Must be HTTP or HTTPS");
    }
  }

}
