<?php
/**
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage app
 * @since 2010-02-25
 * @version SVN: $Id$
 * @filesource $URL$
 */

class Route
{
    
    protected $route;
    protected $action;
    protected $params;
    protected $layout;
    
    public function __construct($route, $action, $params = null, $layout = null)
    {
        $this->route  = $route;
        $this->action = $action;
        $this->params = $params;
        $this->layout = $layout;
    }
    
    /**
     * @param array $request
     */
    public function match($request)
    {
        $parts = explode('/', $this->route);
        $cnt   = count($parts);
        
        if(count($request) != $cnt) {
            return false;
        }
        
        for ($i = 0; $i < $cnt; $i++) {
            if (substr($parts[$i], 0, 1) == ':') {
                $this->params[substr($parts[$i], 1)] = $request[$i];
            } elseif (substr($parts[$i], 0, 2) == '(?') {
                $match = array();
                if (!preg_match('#^' . $parts[$i] . '$#iu', $request[$i], $match)) {
                    return false;
                }
                $start = strpos($parts[$i], '<') + 1;
                $key = substr($parts[$i], $start, strpos($parts[$i], '>', $start) - $start);
                $this->params[$key] = $match[$key];
            } elseif ($parts[$i] != $request[$i]) {
                return false;
            }
        }
        return true;
    }
    
    public function getAction()
    {
        return $this->action . 'Action';
    }
    
    public function getLayout()
    {
        return $this->layout . 'Layout';
    }
    
    public function getParams()
    {
        return $this->params;
    }
}