1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90:
<?php
namespace Coast\Validator;
use JsonSerializable;
abstract class Rule implements JsonSerializable
{
protected $_name;
protected $_errors = [];
public function __construct()
{}
public function name($name = null)
{
if (func_num_args() > 0) {
$this->_name = $name;
return $this;
}
if (isset($this->_name)) {
return $this->_name;
}
$parts = explode('\\', get_class($this));
return lcfirst(array_pop($parts));
}
public function params()
{
$params = [];
foreach (get_object_vars($this) as $key => $value) {
if (in_array($key, ['_name', '_errors'])) {
continue;
}
$params[ltrim($key, '_')] = $value;
}
return $params;
}
abstract protected function _validate($value);
public function validate($value, $context = null)
{
$this->_errors = [];
$this->_validate($value, $context);
return !count($this->_errors);
}
public function isValid()
{
return !count($this->_errors);
}
public function __invoke($value, $context = null)
{
return $this->validate($value, $context);
}
public function error($error = null)
{
if (!is_array($error)) {
$error = [$this->name(), $error, $this->params()];
}
$this->_errors[] = $error;
return $this;
}
public function errors(array $errors = null)
{
if (func_num_args() > 0) {
foreach ($errors as $error) {
$this->error($error);
return $this;
}
}
return $this->_errors;
}
public function jsonSerialize()
{
return [
'name' => $this->name(),
'params' => $this->params(),
];
}
}