<?php
/*
 * Copyright (c) 2012, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

/**
 * @since  v4.0
 * @author Christoph
 */
class _WV24_Dispatcher {
	protected $resolver;

	public function __construct(_WV24_Resolver $resolver) {
		$this->resolver = $resolver;
	}

	/**
	 * @return array
	 */
	public function dispatch($alwaysReturn = false) {
		$url = '/';

		// prepare the full URL
		if     (isset($_SERVER['REDIRECT_REQUEST_URI']))          $url = sly_Util_HTTP::getBaseUrl(true).$_SERVER['REDIRECT_REQUEST_URI'];
		elseif (isset($_SERVER['REDIRECT_REDIRECT_REQUEST_URI'])) $url = sly_Util_HTTP::getBaseUrl(true).$_SERVER['REDIRECT_REDIRECT_REQUEST_URI'];
		elseif (isset($_SERVER['REQUEST_URI']))                   $url = sly_Util_HTTP::getBaseUrl().$_SERVER['REQUEST_URI'];

		$isPOST = isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) === 'post';
		$url    = WV24_Util::cleanUrl($url);

		// resolve it
		$urlObj = $this->resolver->resolveUrl($url);

		// If nothing was found, try at least to set the correct language based
		// on the domain (assuming the project uses different domains per
		// standard fragment).
		if ($urlObj === null) {
			$urlObj = $this->resolver->resolveUrl(sly_Util_HTTP::getBaseUrl(true).'/');
			if ($urlObj) sly_Core::setCurrentClang($urlObj->getClang());

			return null;
		}

		// If the found URL differs from the requested one (because we fixed it
		// for the client), we redirect the client to the correct one. Be careful
		// not to change the protocol! And again, don't do this when POSTing.
		if (!$alwaysReturn && !$isPOST && $urlObj->getRawURL() !== $url) {
			WV24_Util::redirect($urlObj);
		}

		// restore the params associated (in DB) with this URL
		$_GET = array_merge($_GET, $urlObj->getParams());

		return sly_Util_Article::findById($urlObj->getArticleID(), $urlObj->getClang());
	}
}
