friendship ended with social-app. php is my new best friend
at main 2.0 kB view raw
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 8declare(strict_types=1); 9 10namespace Nette\Utils; 11 12use Nette; 13use function count, is_array, is_scalar, sprintf; 14 15 16/** 17 * Provides objects to work as array. 18 * @template T 19 * @implements \IteratorAggregate<array-key, T> 20 * @implements \ArrayAccess<array-key, T> 21 */ 22class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate 23{ 24 /** 25 * Transforms array to ArrayHash. 26 * @param array<T> $array 27 */ 28 public static function from(array $array, bool $recursive = true): static 29 { 30 $obj = new static; 31 foreach ($array as $key => $value) { 32 $obj->$key = $recursive && is_array($value) 33 ? static::from($value) 34 : $value; 35 } 36 37 return $obj; 38 } 39 40 41 /** 42 * Returns an iterator over all items. 43 * @return \Iterator<array-key, T> 44 */ 45 public function &getIterator(): \Iterator 46 { 47 foreach ((array) $this as $key => $foo) { 48 yield $key => $this->$key; 49 } 50 } 51 52 53 /** 54 * Returns items count. 55 */ 56 public function count(): int 57 { 58 return count((array) $this); 59 } 60 61 62 /** 63 * Replaces or appends an item. 64 * @param array-key $key 65 * @param T $value 66 */ 67 public function offsetSet($key, $value): void 68 { 69 if (!is_scalar($key)) { // prevents null 70 throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', get_debug_type($key))); 71 } 72 73 $this->$key = $value; 74 } 75 76 77 /** 78 * Returns an item. 79 * @param array-key $key 80 * @return T 81 */ 82 #[\ReturnTypeWillChange] 83 public function offsetGet($key) 84 { 85 return $this->$key; 86 } 87 88 89 /** 90 * Determines whether an item exists. 91 * @param array-key $key 92 */ 93 public function offsetExists($key): bool 94 { 95 return isset($this->$key); 96 } 97 98 99 /** 100 * Removes the element from this list. 101 * @param array-key $key 102 */ 103 public function offsetUnset($key): void 104 { 105 unset($this->$key); 106 } 107}