| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* This file is part of the Nette Framework (https://nette.org) |
| 5 |
* Copyright (c) 2004 David Grudl (https://davidgrudl.com) |
| 6 |
*/ |
| 7 |
declare (strict_types=1); |
| 8 |
namespace Packetery\Nette\Utils; |
| 9 |
|
| 10 |
use Packetery\Nette; |
| 11 |
/** |
| 12 |
* Provides objects to work as array. |
| 13 |
*/ |
| 14 |
class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate |
| 15 |
{ |
| 16 |
/** |
| 17 |
* Transforms array to ArrayHash. |
| 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) ? static::from($value, \true) : $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)) { |
| 50 |
// prevents null |
| 51 |
throw new \Packetery\Nette\InvalidArgumentException(\sprintf('Key must be either a string or an integer, %s given.', \gettype($key))); |
| 52 |
} |
| 53 |
$this->{$key} = $value; |
| 54 |
} |
| 55 |
/** |
| 56 |
* Returns a item. |
| 57 |
* @param string|int $key |
| 58 |
* @return mixed |
| 59 |
*/ |
| 60 |
public function offsetGet($key) |
| 61 |
{ |
| 62 |
return $this->{$key}; |
| 63 |
} |
| 64 |
/** |
| 65 |
* Determines whether a item exists. |
| 66 |
* @param string|int $key |
| 67 |
*/ |
| 68 |
public function offsetExists($key) : bool |
| 69 |
{ |
| 70 |
return isset($this->{$key}); |
| 71 |
} |
| 72 |
/** |
| 73 |
* Removes the element from this list. |
| 74 |
* @param string|int $key |
| 75 |
*/ |
| 76 |
public function offsetUnset($key) : void |
| 77 |
{ |
| 78 |
unset($this->{$key}); |
| 79 |
} |
| 80 |
} |
| 81 |
|