ArrayAccess.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace RocketTheme\Toolbox\ArrayTraits;
  3. /**
  4. * Implements ArrayAccess interface.
  5. *
  6. * @package RocketTheme\Toolbox\ArrayTraits
  7. * @author RocketTheme
  8. * @license MIT
  9. *
  10. * @property array $items
  11. */
  12. trait ArrayAccess
  13. {
  14. /**
  15. * Whether or not an offset exists.
  16. *
  17. * @param mixed $offset An offset to check for.
  18. * @return bool Returns TRUE on success or FALSE on failure.
  19. */
  20. public function offsetExists($offset)
  21. {
  22. return isset($this->items[$offset]);
  23. }
  24. /**
  25. * Returns the value at specified offset.
  26. *
  27. * @param mixed $offset The offset to retrieve.
  28. * @return mixed Can return all value types.
  29. */
  30. public function offsetGet($offset)
  31. {
  32. return isset($this->items[$offset]) ? $this->items[$offset] : null;
  33. }
  34. /**
  35. * Assigns a value to the specified offset.
  36. *
  37. * @param mixed $offset The offset to assign the value to.
  38. * @param mixed $value The value to set.
  39. */
  40. public function offsetSet($offset, $value)
  41. {
  42. if (is_null($offset)) {
  43. $this->items[] = $value;
  44. } else {
  45. $this->items[$offset] = $value;
  46. }
  47. }
  48. /**
  49. * Unsets an offset.
  50. *
  51. * @param mixed $offset The offset to unset.
  52. */
  53. public function offsetUnset($offset)
  54. {
  55. // Hack to make Iterator trait work together with unset.
  56. if (isset($this->iteratorUnset) && $offset == key($this->items)) {
  57. $this->iteratorUnset = true;
  58. }
  59. unset($this->items[$offset]);
  60. }
  61. }