Source

Ray / Ray / Router / Route.php

Full commit
<?php

class Ray_Router_Route{
    
    private $pattern;
    
    private $callable;
    
    private $params;
    
    private $conditions = array();
    
    public function __construct($pattern, $callable){
        $this->pattern = $pattern;
        $this->callable = $callable;
    }
    
    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);
        }
        
        return call_user_func($this->callable);
    }
    
    protected function getRegex( $matches ) {
        $key = substr(current($matches),1);
        
        $condition = isset($this->conditions[$key]) ? $this->conditions[$key] : 
                     '.*?';
        
        return '(?P<'.$key.'>' . $condition . ')';
    }
    
}