HasAttributes.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Libs\TikTok\Kernel\Traits;
  4. use function array_key_exists;
  5. use function array_merge;
  6. use function json_encode;
  7. trait HasAttributes
  8. {
  9. /**
  10. * @var array<int|string,mixed>
  11. */
  12. protected array $attributes = [];
  13. /**
  14. * @param array<int|string,mixed> $attributes
  15. */
  16. public function __construct(array $attributes)
  17. {
  18. $this->attributes = $attributes;
  19. }
  20. /**
  21. * @return array<int|string,mixed>
  22. */
  23. public function toArray(): array
  24. {
  25. return $this->attributes;
  26. }
  27. public function toJson(): string|false
  28. {
  29. return json_encode($this->attributes);
  30. }
  31. public function has(string $key): bool
  32. {
  33. return array_key_exists($key, $this->attributes);
  34. }
  35. /**
  36. * @param array<int|string,mixed> $attributes
  37. */
  38. public function merge(array $attributes): self
  39. {
  40. $this->attributes = array_merge($this->attributes, $attributes);
  41. return $this;
  42. }
  43. /**
  44. * @return array<int|string,mixed> $attributes
  45. */
  46. public function jsonSerialize(): array
  47. {
  48. return $this->attributes;
  49. }
  50. public function __set(string $attribute, $value): void
  51. {
  52. $this->attributes[$attribute] = $value;
  53. }
  54. public function __get(string $attribute)
  55. {
  56. return $this->attributes[$attribute] ?? null;
  57. }
  58. public function offsetExists($offset): bool
  59. {
  60. /** @phpstan-ignore-next-line */
  61. return array_key_exists($offset, $this->attributes);
  62. }
  63. public function offsetGet($offset)
  64. {
  65. return $this->attributes[$offset];
  66. }
  67. public function offsetSet($offset, $value): void
  68. {
  69. if (null === $offset) {
  70. $this->attributes[] = $value;
  71. } else {
  72. $this->attributes[$offset] = $value;
  73. }
  74. }
  75. public function offsetUnset($offset): void
  76. {
  77. unset($this->attributes[$offset]);
  78. }
  79. }