Collectionで与えられた値のバリデーションをチェックするマクロです。
Collection::macro('validate', function (array $validates) {
collect($validates)->map(function($typeName, $key) {
$data = $this->get($key, false);
// required check.
if (! $this->has($key) || ! $data) {
throw new \Exception(sprintf('"%s" is required.', $key));
}
$messase = '"%s" Must be of the type %s, %s given!';
// objectとそれ以外で出し分け
switch (gettype($data)) {
case 'object':
if ( ! $data instanceof $typeName) {
throw new \Exception(sprintf($messase, $key, $typeName, get_class($data)));
}
break;
default:
if (gettype($data) != $typeName) {
throw new \Exception(sprintf($messase, $key, $typeName, gettype($data)));
}
}
});
return $this;
});
結果
"name" Must be of the type string, integer given!