From 70e4404c22741db5c1e2b096934c250042e5fb61 Mon Sep 17 00:00:00 2001 From: Dan Jones Date: Sun, 14 Aug 2022 13:35:37 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Improve=20model=20serialization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Probably going to switch to spatie's package, though --- app/Models/Input.php | 12 ++++++------ app/Models/Model.php | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/app/Models/Input.php b/app/Models/Input.php index 71ec18b..71e913f 100644 --- a/app/Models/Input.php +++ b/app/Models/Input.php @@ -6,12 +6,12 @@ use App\Exceptions\Quit; class Input extends Model { - public ?array $files; - public ?string $url; - public ?string $destination; - public ?string $title; - public bool $low; - public bool $sync; + protected ?array $files = null; + protected ?string $url = null; + protected ?string $destination = null; + protected ?string $title = null; + protected bool $low = false; + protected bool $sync = false; public function assertValid(): self { diff --git a/app/Models/Model.php b/app/Models/Model.php index 75f19c3..55dd40f 100644 --- a/app/Models/Model.php +++ b/app/Models/Model.php @@ -3,8 +3,11 @@ namespace App\Models; use Illuminate\Support\Str; +use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Contracts\Support\Jsonable; +use JsonSerializable; -abstract class Model +abstract class Model implements Arrayable, JsonSerializable, Jsonable { public function __construct(array $data = []) { @@ -22,4 +25,33 @@ abstract class Model $this->$key = $value; } } + + public function __get(string $key) + { + $getter = 'get' . Str::studly($key); + if (method_exists($this, $getter)) { + return $this->$getter($this->$key ?? null); + } elseif (property_exists($this, $key)) { + return $this->$key; + } + + throw new \OutOfBoundsException(sprintf( + 'Undefined property %s::%s', static::class, $key + )); + } + + public function toArray() + { + return get_object_vars($this); + } + + public function jsonSerialize() + { + return $this->toArray(); + } + + public function toJson($options = 0) + { + return json_encode($this->jsonSerialize(), $options); + } }