Skip to content

Instantly share code, notes, and snippets.

@nvahalik
Last active June 3, 2019 10:07
Show Gist options
  • Save nvahalik/677eef988d86ec6db0fc4617a4612ca1 to your computer and use it in GitHub Desktop.
Save nvahalik/677eef988d86ec6db0fc4617a4612ca1 to your computer and use it in GitHub Desktop.
A QnD class for keeping arrays straight
<?php namespace App\Models;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Fluent;
class ArrayModel extends Fluent
{
public function __construct($data)
{
if (($validator = Validator::make($data, $this->rules()))->fails()) {
throw new \InvalidArgumentException($validator->getMessageBag()->first());
}
parent::__construct($data);
}
protected function rules(): array {
// Implement in your other subclass.
}
public static function make($data) {
return (new static)($data);
}
}
<?php
class A extends ArrayModel {
protected function rules():array {
return [
'name' => 'string',
'number' => 'numeric'
];
}
}
$b = new A(['name' => 'Gustaf', 'number' => 4]);
dump($b->name);
dump($b->number);
dump($b->toArray());
// $b = new A(['name' => 'Gustaf', 'number' => 'four']); // Throws an error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment