File: /www/exchange0old/exchange/admin/validator/Validator.php
<?php
/**
* validator - Validator.php
*
* Initial version by: MisterX
* Initial version created on: 09.12.2015
*/
class Validator
{
protected $_rules = array();
protected $_empty_rules = array('not_empty', 'matches');
public function rule($field,$rule,array $params=null){
if ($params === NULL)
{
// Default to array(':value')
$params = array(':value');
}
$this->_rules[$field][] = array($rule, $params);
}
public function check(ValidationData $object)
{
$errors = $bound = array();
$bound[':object'] = $object;
// Import the rules locally
$rules = $this->_rules;
// Execute the rules
foreach ($rules as $field => $set)
{
// Get the field value
$value = $object->getFieldValue($field);
// Bind the field name and value to :field and :value respectively
$bound[':value'] = $value;
foreach ($set as $array)
{
// Rules are defined as array($rule, $params)
list($rule, $params) = $array;
foreach ($params as $key => $param)
{
if (is_string($param) AND array_key_exists($param, $bound))
{
// Replace with bound value
$params[$key] = $bound[$param];
}
}
// Default the error name to be the rule (except array and lambda rules)
$error_name = $rule;
if (is_array($rule))
{
// This is an array callback, the method name is the error name
$passed = call_user_func_array($rule, $params);
}
elseif (method_exists('Valid', $rule))
{
// Use a method in this object
$method = new ReflectionMethod('Valid', $rule);
// Call static::$rule($this[$field], $param, ...) with Reflection
$passed = $method->invokeArgs(NULL, $params);
}
elseif (strpos($rule, '::') === FALSE)
{
// Use a function call
$function = new ReflectionFunction($rule);
// Call $function($this[$field], $param, ...) with Reflection
$passed = $function->invokeArgs($params);
}
else
{
// Split the class and method of the rule
list($class, $method) = explode('::', $rule, 2);
// Use a static method call
$method = new ReflectionMethod($class, $method);
// Call $Class::$method($this[$field], $param, ...) with Reflection
$passed = $method->invokeArgs(NULL, $params);
}
// Ignore return values from rules when the field is empty
if ( ! in_array($rule, $this->_empty_rules) AND ! Valid::not_empty($value))
continue;
if ($passed === FALSE AND $error_name !== FALSE)
{
// Add the rule to the errors
$errors[$field][] = array('error'=>$error_name/*, $params*/);
// This field has an error, stop executing rules
break;
}elseif(is_string($passed) AND $error_name !== FALSE){
// Add the rule to the errors
$errors[$field][] = array('error'=>$error_name/*, $params*/,'result'=>$passed);
// This field has an error, stop executing rules
break;
}
elseif (isset($errors[$field]))
{
// The callback added the error manually, stop checking rules
break;
}
}
}
$object->setErrors($errors);
return $errors?$errors:true;
}
}