ArrayHash.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. * @template T
  12. */
  13. class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate
  14. {
  15. /**
  16. * Transforms array to ArrayHash.
  17. * @param array<T> $array
  18. * @return static
  19. */
  20. public static function from(array $array, bool $recursive = true)
  21. {
  22. $obj = new static;
  23. foreach ($array as $key => $value) {
  24. $obj->$key = $recursive && is_array($value)
  25. ? static::from($value, true)
  26. : $value;
  27. }
  28. return $obj;
  29. }
  30. /**
  31. * Returns an iterator over all items.
  32. * @return \RecursiveArrayIterator<array-key, T>
  33. */
  34. public function getIterator(): \RecursiveArrayIterator
  35. {
  36. return new \RecursiveArrayIterator((array) $this);
  37. }
  38. /**
  39. * Returns items count.
  40. */
  41. public function count(): int
  42. {
  43. return count((array) $this);
  44. }
  45. /**
  46. * Replaces or appends a item.
  47. * @param string|int $key
  48. * @param T $value
  49. */
  50. public function offsetSet($key, $value): void
  51. {
  52. if (!is_scalar($key)) { // prevents null
  53. throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', gettype($key)));
  54. }
  55. $this->$key = $value;
  56. }
  57. /**
  58. * Returns a item.
  59. * @param string|int $key
  60. * @return T
  61. */
  62. #[\ReturnTypeWillChange]
  63. public function offsetGet($key)
  64. {
  65. return $this->$key;
  66. }
  67. /**
  68. * Determines whether a item exists.
  69. * @param string|int $key
  70. */
  71. public function offsetExists($key): bool
  72. {
  73. return isset($this->$key);
  74. }
  75. /**
  76. * Removes the element from this list.
  77. * @param string|int $key
  78. */
  79. public function offsetUnset($key): void
  80. {
  81. unset($this->$key);
  82. }
  83. }