<?php namespace Intellex\Curly;

use Intellex\Curly\Exception\ProtocolNotSupportedException;

/**
 * The list of all available protocols.
 */
class Protocol {

	/** @const string The insecure protocol. */
	const HTTP = 'http';

	/** @const string The secure protocol. */
	const HTTPS = 'https';

	/** @var string The protocol itself. */
	private $protocol;

	/**
	 * Initialize the protocol.
	 *
	 * @param string $protocol The requested protocol.
	 *
	 * @throws ProtocolNotSupportedException On protocol not recognized or not supported.
	 */
	public function __construct($protocol = 'http') {
		$this->protocol = static::validate($protocol);
	}

	/**
	 * Check if the URL is a secure.
	 *
	 * @return boolean True if the used protocol is HTTPS, false otherwise.
	 */
	public function isSecure() {
		return $this->protocol === static::HTTPS;
	}

	/**
	 * Validate the string representation of a protocol.
	 *
	 * @param string|Protocol $protocol The requested protocol.
	 *
	 * @return string The filtered protocol.
	 * @throws ProtocolNotSupportedException
	 */
	public static function validate($protocol) {
		if ($protocol instanceof Protocol) {
			return $protocol->toString();
		}

		$upper = strtolower(preg_replace('~[^a-zA-Z]~', '', $protocol));
		$supported = [ static::HTTP, static::HTTPS ];
		foreach ($supported as $const) {
			if ($const === $upper) {
				return $const;
			}
		}

		throw new ProtocolNotSupportedException($protocol);
	}

	/**
	 * Convert the protocol to a string representation.
	 *
	 * @return string The string representation of the current protocol.
	 */
	public function toString() {
		return strtolower($this->protocol);
	}

}
