@ 2017-07-02T23:33:00Z <?php
class Validator {
const GREATER = [self::class, 'greater'];
const IS_TYPE = [self::class, 'isType'];
public static function all(...$rules) {
foreach ($rules as $def) {
$rule = array_shift($def);
if ($rule(...$def)) { continue; }
return false;
}
return true;
}
public static function greater($value, $compare) : bool {
return $value > $compare;
}
public static function isType($value, $type) : bool {
return gettype($value) === $type;
}
}
class Model {
const RULES = [
'foo' => [
'integer', // shorthand for [Validator::IS_TYPE, 'integer']
[Validator::GREATER, 10]
]
];
protected $foo;
public function set($name, $value) {
if ($this->isValid($name, $value)) {
$this->$name = $value;
return;
}
throw new Exception("{$name} cannot be {$value}");
}
function isValid($name, $value) : bool {
$rules = [];
foreach (self::RULES[$name] as $rule) {
// convenience: turn strings into typehints
if (is_string($rule)) {
$rules[] = [Validator::IS_TYPE, $value];
continue;
}
// ... other convenience parsing ...
// for fully defined rules, just add value arg at proper spot
array_splice($rule, 1, 0, $value);
$rules[] = $rule;
}
return Validator::ALL($rules);
}
}
$m = new Model;
$m->set('foo', 15);
var_dump($m);
$m->set('foo', 7);
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 7.0.0 - 7.0.33 , 7.1.0 - 7.1.33 , 7.2.0 - 7.2.33 , 7.3.0 - 7.3.33 , 7.4.0 - 7.4.33 , 8.0.0 - 8.0.30 , 8.1.0 - 8.1.28 , 8.2.0 - 8.2.18 , 8.3.0 - 8.3.7 Fatal error: Uncaught Error: First array member is not a valid class name or object in /in/iRMov:11
Stack trace:
#0 /in/iRMov(62): Validator::all(Array)
#1 /in/iRMov(38): Model->isValid('foo', 15)
#2 /in/iRMov(68): Model->set('foo', 15)
#3 {main}
thrown in /in/iRMov on line 11
Process exited with code 255 . Output for 5.6.0 - 5.6.40 Parse error: syntax error, unexpected ':', expecting ';' or '{' in /in/iRMov on line 17
Process exited with code 255 . preferences:dark mode live preview
238.97 ms | 401 KiB | 289 Q