Source

Ray / Ray / Router / Route.php

Full commit
<?php

namespace Ray\Router;

use Ray;

class Route{

    private $pattern;

    private $callable;

    private $view;

    private $params;

    private $conditions = array();

    public function __construct($pattern, $callable, $view=null){
        $this->pattern = $pattern;
        $this->callable = $callable;
        $this->view = $view;
    }

    public function check($call){

        preg_match_all('@:([\w]+)@', $this->pattern, $params, PREG_PATTERN_ORDER);
        $params = current($params);

        $regex = preg_replace_callback('@:[\w]+@', array($this, 'getRegex'), $this->pattern);

        if ( substr($this->pattern, -1) === '/' ) {
            $regex = $regex . '?';
        }

        if(preg_match('@^' . $regex . '$@', $call, $values)){
            array_shift($values);
            foreach($params as $k=>$v){
                $val = substr($v, 1);
                if(isset($values[$val])){
                    $this->params[$val] = urldecode($values[$val]);
                }
            }

            return true;
        }

        return false;
    }

    public function conditions(array $conditions){
        $this->conditions = $conditions;
    }

    public function proccess(){

        if(is_array($this->params)){
            $return = call_user_func_array($this->callable, $this->params);
        }else{
            $return = call_user_func($this->callable);
        }

        return array(
            'view' => $this->view,
            'callback' => $return
        );
    }

    protected function getRegex( $matches ) {
        $key = substr(current($matches),1);

        $condition = isset($this->conditions[$key]) ? $this->conditions[$key] :
                     '.*?';

        return '(?P<'.$key.'>' . $condition . ')';
    }

}