<?php namespace Intellex\Manicure\Source;

/**
 * A source from the remote URL.
 */
class UrlSource implements SourceInterface {

	/** @var string The URL to the image. */
	protected $url;

	/** @var ImageDataSource The cached data source. */
	protected $data;

	/**
	 * LocalSource constructor.
	 *
	 * @param string $url The URL to the image.
	 */
	public function __construct($url) {
		$this->url = $url;
	}

	/** @inheritdoc */
	public function getData() {
		$this->load();
		return $this->data->getData();
	}

	/** @inheritdoc */
	public function getWidth() {
		$this->load();
		return $this->data->getWidth();
	}

	/** @inheritdoc */
	public function getHeight() {
		$this->load();
		return $this->data->getHeight();
	}

	/**
	 * Fill the data from the supplied path.
	 */
	protected function load() {
		if ($this->data === null) {
			try {

				// Get the image
				$image = file_get_contents($this->url);
				if (!$image) {
					throw new \Exception("Cannot load the image from `{$this->url}`.");
				}

				// Load into data source
				$this->data = new ImageDataSource(imagecreatefromstring($image));

			} catch (\Exception $ex) {
				throw new \Exception("Cannot load the image from `{$this->url}`.");
			}
		}
	}

}