Optional.php 2.6KB

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