Improve model serialization

Probably going to switch to spatie's package, though
This commit is contained in:
Dan Jones 2022-08-14 13:35:37 -05:00
commit 70e4404c22
2 changed files with 39 additions and 7 deletions

View file

@ -6,12 +6,12 @@ use App\Exceptions\Quit;
class Input extends Model class Input extends Model
{ {
public ?array $files; protected ?array $files = null;
public ?string $url; protected ?string $url = null;
public ?string $destination; protected ?string $destination = null;
public ?string $title; protected ?string $title = null;
public bool $low; protected bool $low = false;
public bool $sync; protected bool $sync = false;
public function assertValid(): self public function assertValid(): self
{ {

View file

@ -3,8 +3,11 @@
namespace App\Models; namespace App\Models;
use Illuminate\Support\Str; 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 = []) public function __construct(array $data = [])
{ {
@ -22,4 +25,33 @@ abstract class Model
$this->$key = $value; $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);
}
} }