ArrayHash.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * This file is part of the Nette Framework (https://nette.org)
  4. * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  5. */
  6. declare(strict_types=1);
  7. namespace Nette\Utils;
  8. use Nette;
  9. /**
  10. * Provides objects to work as array.
  11. */
  12. class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate
  13. {
  14. /**
  15. * Transforms array to ArrayHash.
  16. * @return static
  17. */
  18. public static function from(array $array, bool $recursive = true)
  19. {
  20. $obj = new static;
  21. foreach ($array as $key => $value) {
  22. $obj->$key = $recursive && is_array($value)
  23. ? static::from($value, true)
  24. : $value;
  25. }
  26. return $obj;
  27. }
  28. /**
  29. * Returns an iterator over all items.
  30. */
  31. public function getIterator(): \RecursiveArrayIterator
  32. {
  33. return new \RecursiveArrayIterator((array) $this);
  34. }
  35. /**
  36. * Returns items count.
  37. */
  38. public function count(): int
  39. {
  40. return count((array) $this);
  41. }
  42. /**
  43. * Replaces or appends a item.
  44. * @param string|int $key
  45. * @param mixed $value
  46. */
  47. public function offsetSet($key, $value): void
  48. {
  49. if (!is_scalar($key)) { // prevents null
  50. throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', gettype($key)));
  51. }
  52. $this->$key = $value;
  53. }
  54. /**
  55. * Returns a item.
  56. * @param string|int $key
  57. * @return mixed
  58. */
  59. public function offsetGet($key)
  60. {
  61. return $this->$key;
  62. }
  63. /**
  64. * Determines whether a item exists.
  65. * @param string|int $key
  66. */
  67. public function offsetExists($key): bool
  68. {
  69. return isset($this->$key);
  70. }
  71. /**
  72. * Removes the element from this list.
  73. * @param string|int $key
  74. */
  75. public function offsetUnset($key): void
  76. {
  77. unset($this->$key);
  78. }
  79. }