CastsValue.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Database\Model;
  12. use Hyperf\Contract\Arrayable;
  13. use Hyperf\Contract\Synchronized;
  14. abstract class CastsValue implements Synchronized, Arrayable
  15. {
  16. protected array $items = [];
  17. protected bool $isSynchronized = false;
  18. public function __construct(protected Model $model, array $items = [])
  19. {
  20. $this->items = array_merge($this->items, $items);
  21. }
  22. public function __get($name)
  23. {
  24. return $this->items[$name] ?? null;
  25. }
  26. public function __set($name, $value)
  27. {
  28. $this->items[$name] = $value;
  29. $this->syncAttributes();
  30. }
  31. public function __isset($name)
  32. {
  33. return isset($this->items[$name]);
  34. }
  35. public function __unset($name)
  36. {
  37. unset($this->items[$name]);
  38. $this->syncAttributes();
  39. }
  40. public function isSynchronized(): bool
  41. {
  42. return $this->isSynchronized;
  43. }
  44. public function toArray(): array
  45. {
  46. return $this->items;
  47. }
  48. public function syncAttributes(): void
  49. {
  50. $this->isSynchronized = false;
  51. $this->model->syncAttributes();
  52. $this->isSynchronized = true;
  53. }
  54. }