Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

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