Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | 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
	 * @return static
25
	 */
26
	public static function from(array $array, bool $recursive = true)
27
	{
28
		$obj = new static;
29
		foreach ($array as $key => $value) {
30
			$obj->$key = $recursive && is_array($value)
31
				? static::from($value, true)
32
				: $value;
33
		}
34
 
35
		return $obj;
36
	}
37
 
38
 
39
	/**
40
	 * Returns an iterator over all items.
41
	 * @return \RecursiveArrayIterator<array-key, T>
42
	 */
43
	public function getIterator(): \RecursiveArrayIterator
44
	{
45
		return new \RecursiveArrayIterator((array) $this);
46
	}
47
 
48
 
49
	/**
50
	 * Returns items count.
51
	 */
52
	public function count(): int
53
	{
54
		return count((array) $this);
55
	}
56
 
57
 
58
	/**
59
	 * Replaces or appends a item.
60
	 * @param  string|int  $key
61
	 * @param  T  $value
62
	 */
63
	public function offsetSet($key, $value): void
64
	{
65
		if (!is_scalar($key)) { // prevents null
66
			throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', gettype($key)));
67
		}
68
 
69
		$this->$key = $value;
70
	}
71
 
72
 
73
	/**
74
	 * Returns a item.
75
	 * @param  string|int  $key
76
	 * @return T
77
	 */
78
	#[\ReturnTypeWillChange]
79
	public function offsetGet($key)
80
	{
81
		return $this->$key;
82
	}
83
 
84
 
85
	/**
86
	 * Determines whether a item exists.
87
	 * @param  string|int  $key
88
	 */
89
	public function offsetExists($key): bool
90
	{
91
		return isset($this->$key);
92
	}
93
 
94
 
95
	/**
96
	 * Removes the element from this list.
97
	 * @param  string|int  $key
98
	 */
99
	public function offsetUnset($key): void
100
	{
101
		unset($this->$key);
102
	}
103
}