Accessable.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Supports\Traits;
  4. use Yansongda\Supports\Str;
  5. trait Accessable
  6. {
  7. public function __get(string $key): mixed
  8. {
  9. return $this->get($key);
  10. }
  11. public function __isset(string $key): bool
  12. {
  13. return !is_null($this->get($key));
  14. }
  15. public function __unset(string $key): void
  16. {
  17. $this->offsetUnset($key);
  18. }
  19. public function __set(string $key, mixed $value): void
  20. {
  21. $this->set($key, $value);
  22. }
  23. public function get(?string $key = null, mixed $default = null): mixed
  24. {
  25. if (is_null($key)) {
  26. return method_exists($this, 'toArray') ? $this->toArray() : $default;
  27. }
  28. $method = 'get'.Str::studly($key);
  29. if (method_exists($this, $method)) {
  30. return $this->{$method}();
  31. }
  32. return $default;
  33. }
  34. public function set(string $key, mixed $value): self
  35. {
  36. $method = 'set'.Str::studly($key);
  37. if (method_exists($this, $method)) {
  38. $this->{$method}($value);
  39. }
  40. return $this;
  41. }
  42. public function offsetExists(mixed $offset): bool
  43. {
  44. return !is_null($this->get($offset));
  45. }
  46. public function offsetGet(mixed $offset): mixed
  47. {
  48. return $this->get($offset);
  49. }
  50. public function offsetSet(mixed $offset, mixed $value): void
  51. {
  52. $this->set($offset, $value);
  53. }
  54. public function offsetUnset(mixed $offset): void {}
  55. }