ArrayHash.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. namespace Nette\Utils;
  7. use Nette;
  8. /**
  9. * Provides objects to work as array.
  10. */
  11. class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate
  12. {
  13. /**
  14. * @param array to wrap
  15. * @param bool
  16. * @return static
  17. */
  18. public static function from($arr, $recursive = true)
  19. {
  20. $obj = new static;
  21. foreach ($arr as $key => $value) {
  22. if ($recursive && is_array($value)) {
  23. $obj->$key = static::from($value, true);
  24. } else {
  25. $obj->$key = $value;
  26. }
  27. }
  28. return $obj;
  29. }
  30. /**
  31. * Returns an iterator over all items.
  32. * @return \RecursiveArrayIterator
  33. */
  34. public function getIterator()
  35. {
  36. return new \RecursiveArrayIterator((array) $this);
  37. }
  38. /**
  39. * Returns items count.
  40. * @return int
  41. */
  42. public function count()
  43. {
  44. return count((array) $this);
  45. }
  46. /**
  47. * Replaces or appends a item.
  48. * @return void
  49. */
  50. public function offsetSet($key, $value)
  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. * @return mixed
  60. */
  61. public function offsetGet($key)
  62. {
  63. return $this->$key;
  64. }
  65. /**
  66. * Determines whether a item exists.
  67. * @return bool
  68. */
  69. public function offsetExists($key)
  70. {
  71. return isset($this->$key);
  72. }
  73. /**
  74. * Removes the element from this list.
  75. * @return void
  76. */
  77. public function offsetUnset($key)
  78. {
  79. unset($this->$key);
  80. }
  81. }