Optional.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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\Support;
  12. use ArrayAccess;
  13. use Hyperf\Collection\Arr;
  14. use Hyperf\Macroable\Macroable;
  15. class Optional implements ArrayAccess
  16. {
  17. use Macroable {
  18. __call as macroCall;
  19. }
  20. /**
  21. * Create a new optional instance.
  22. *
  23. * @param mixed $value the underlying object
  24. */
  25. public function __construct(protected $value)
  26. {
  27. }
  28. /**
  29. * Dynamically access a property on the underlying object.
  30. *
  31. * @param string $key
  32. * @return mixed
  33. */
  34. public function __get($key)
  35. {
  36. if (is_object($this->value)) {
  37. return $this->value->{$key} ?? null;
  38. }
  39. return null;
  40. }
  41. /**
  42. * Dynamically check a property exists on the underlying object.
  43. *
  44. * @param mixed $name
  45. * @return bool
  46. */
  47. public function __isset($name)
  48. {
  49. if (is_object($this->value)) {
  50. return isset($this->value->{$name});
  51. }
  52. return false;
  53. }
  54. /**
  55. * Dynamically pass a method to the underlying object.
  56. *
  57. * @param string $method
  58. * @param array $parameters
  59. * @return mixed
  60. */
  61. public function __call($method, $parameters)
  62. {
  63. if (static::hasMacro($method)) {
  64. return $this->macroCall($method, $parameters);
  65. }
  66. if (is_object($this->value)) {
  67. return $this->value->{$method}(...$parameters);
  68. }
  69. return null;
  70. }
  71. /**
  72. * Determine if an item exists at an offset.
  73. */
  74. public function offsetExists(mixed $offset): bool
  75. {
  76. return Arr::accessible($this->value) && Arr::exists($this->value, $offset);
  77. }
  78. /**
  79. * Get an item at a given offset.
  80. */
  81. public function offsetGet(mixed $offset): mixed
  82. {
  83. return Arr::get($this->value, $offset);
  84. }
  85. /**
  86. * Set the item at a given offset.
  87. */
  88. public function offsetSet(mixed $offset, mixed $value): void
  89. {
  90. if (Arr::accessible($this->value)) {
  91. $this->value[$offset] = $value;
  92. }
  93. }
  94. /**
  95. * Unset the item at a given offset.
  96. */
  97. public function offsetUnset(mixed $offset): void
  98. {
  99. if (Arr::accessible($this->value)) {
  100. unset($this->value[$offset]);
  101. }
  102. }
  103. }