Last active
June 3, 2019 10:07
-
-
Save nvahalik/677eef988d86ec6db0fc4617a4612ca1 to your computer and use it in GitHub Desktop.
A QnD class for keeping arrays straight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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