<?php
namespace gnomephp\mvc\router;
class ToField{
private $source;
const REGEXP_CM = '/([\$A-Za-z0-9_\\\\]+)\.([\$A-Za-z0-9_]+)\((.*?)\)$/';
public function __construct($source){
$this->source = $source;
}
/**
* Returns array if success reverseValidated.
* Array of additional parameters to deliver to from field.
*
* returns false if we didn't find reverse path.
*
* @param string $_controller
* @param string $_method
* @param array $args
*/
public function reverseValidate($_controller, $_method, $args){
$additionalArgs = array();
// Extra regexp that will get appended depended on flags .
$r = '';
$hasAnonymousArgs = false;
// Argument check is quite machine costly.
if (is_array($args)){
$namedKeys = array_keys($args);
// remove int keys, they can match anyway! ( Anonymous Arguments )
foreach($namedKeys as $k => $v){
if (is_int($v)){
unset($namedKeys[$k]);
$hasAnonymousArgs = true;
}
}
if (count($namedKeys) > 0){
foreach($namedKeys as $v){
// Arguments does not match, meaning, lets not compare this one!
if (!strstr($this->source, '$'.$v)){
return false;
}
}
}
}
// Allow support for variables in controller / method.
$c = $_controller;
$m = $_method;
preg_match(ToField::REGEXP_CM, $this->source, $matches);
list($mock, $controller, $method, $args) = $matches;
$controllerDynamic = substr($controller, 0, 1) == '$' ? true : false;
$methodDynamic = substr($method, 0, 1) == '$' ? true : false;
// Allow \ns\Controller .
$c = str_replace('\\','\\\\', $c);
if ($controllerDynamic){
$c = '([\$A-Za-z0-9_]*)';
$additionalArgs[substr($controller, 1)] = $_controller;
}
if ($methodDynamic){
$m = '([\$A-Za-z0-9_]*)';
$additionalArgs[substr($method, 1)] = $_method;
}
if (preg_match("/$c\.$m$r/", $this->source))return $additionalArgs;
return false;
}
public function getComponent($vars){
preg_match(ToField::REGEXP_CM, $this->source, $matches);
// List them out.
list($mock, $controller, $method, $args) = $matches;
// Prepare the arguments
$ar = array();
// Did we get arguments to parse ?
if ($args)$ar = str_getcsv($args);
// Var support for method and controller.
$controllerDynamic = substr($controller, 0, 1) == '$' ? true : false;
$methodDynamic = substr($method, 0, 1) == '$' ? true : false;
foreach($vars['vars'] as $key => $value){
if ($controllerDynamic){
if ($key == substr($controller, 1)){
$controller = $value;
$controllerDynamic = false; // No longer dynamic
}
}
if ($methodDynamic){
if ($key == substr($method, 1)){
$method = $value;
$methodDynamic = false; // No longer dynamic
}
}
}
// Parse arguments to get values.
foreach($ar as $k => $v){
if (substr($v, 0, 1) == '$' && isset($vars['vars'][substr($v, 1)])){
$ar[$k] = $vars['vars'][substr($v, 1)];
}
}
// Add anonymous vars in the end if we got it!
if ($vars['anonymousVars'] !== null){
$ar = array_merge($ar, $vars['anonymousVars']);
}
// Return array of controller, method , arguments.
return new BackendObject($controller, $method, $ar);
}
}