Created
September 5, 2023 17:00
-
-
Save datashaman/2b0e33a158c83fc4437ea71c09640ca9 to your computer and use it in GitHub Desktop.
Self-validating Options class for Laravel
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\Support; | |
use ArrayAccess; | |
use ArrayIterator; | |
use Illuminate\Support\Facades\Validator; | |
use Iterator; | |
use IteratorAggregate; | |
abstract class Options implements | |
ArrayAccess, | |
IteratorAggregate | |
{ | |
protected array $attributes; | |
public function __construct( | |
array $attributes | |
) { | |
$this->attributes = $this->validated($attributes); | |
} | |
public function rules(): array | |
{ | |
return []; | |
} | |
public function get(string $name, $default = null): mixed | |
{ | |
return $this->attributes[$name] ?? $default; | |
} | |
public function has(string $name): bool | |
{ | |
return isset($this->attributes[$name]); | |
} | |
public function __get(string $name): mixed | |
{ | |
return $this->attributes[$name]; | |
} | |
public function __isset(string $name): bool | |
{ | |
return isset($this->attributes[$name]); | |
} | |
public function offsetGet(mixed $offset): mixed | |
{ | |
return $this->attributes[$offset]; | |
} | |
public function offsetExists(mixed $offset): bool | |
{ | |
return isset($this->attributes, $offset); | |
} | |
public function offsetSet(mixed $offset, mixed $value): void | |
{ | |
throw new Exception('Options objects are readonly'); | |
} | |
public function offsetUnset(mixed $offset): void | |
{ | |
throw new Exception('Options objects are readonly'); | |
} | |
public function getIterator(): Iterator | |
{ | |
return new ArrayIterator($this->attributes); | |
} | |
public function toArray(): array | |
{ | |
return $this->attributes; | |
} | |
protected function validated(array $attributes): array | |
{ | |
return Validator::make($attributes, $this->rules()) | |
->validate() | |
->validated(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment