8a628661ad2767c695c28f735a58249e2cfc5847
5 class Container
implements \ArrayAccess
, \RecursiveIterator
, \JsonSerializable
8 * Index for a numerically indexed array
22 * State for the RecursiveIterator
29 * Whether to auto populate a requested property with a new container
36 * Create a new container
37 * @param array $array container data
38 * @param bool $auto whether to auto populate a requested property with a new container
40 function __construct(array $array = null, $auto = true) {
41 $this->props
= new \stdClass
;
44 foreach ((array) $array as $property => $value) {
45 $this->__set($property, $value);
50 * Recursively turn a container and its childs into an array
51 * @param \merry\Container $o the Container instance to convert to an array
54 protected function arrayify(Container
$o) {
57 foreach ($o->props
as $k => $v) {
58 if ($v instanceof Container
) {
59 $a[$k] = $this->arrayify($v);
69 * Apply one or mor modifier callbacks
70 * @param mixed $modifier
71 * @return \merry\Container
73 public function apply($modifier) {
74 if (is_callable($modifier)) {
75 foreach ($this->props
as $prop => $value) {
76 $this->__set($prop, $modifier($value, $prop));
79 foreach ($modifier as $key => $mod) {
80 if (is_callable($mod)) {
81 $this->props
->$key = $mod(isset($this->props
->$key) ?
$this->props
->$key : null, $key);
82 } elseif (is_array($mod)) {
83 $this->props
->$key->apply($mod);
93 * Return the complete config as array
97 return $this->arrayify($this);
103 function &__get($prop) {
104 if ($this->auto
&& !isset($this->props
->$prop)) {
105 $this->props
->$prop = new static;
107 return $this->props
->$prop;
113 function __set($prop, $value) {
114 if (isset($value) && !is_scalar($value) && !($value instanceof Container
)) {
115 $value = new static((array) $value);
117 if (!strlen($prop)) {
118 $prop = $this->index++
;
119 } elseif (is_numeric($prop) && !strcmp($prop, (int) $prop)) {
120 /* update internal index */
121 if ($prop >= $this->index
) {
122 $this->index
= $prop +
1;
126 $this->props
->$prop = $value;
132 function __isset($prop) {
133 return isset($this->props
->$prop);
139 function __unset($prop) {
140 unset($this->props
->$prop);
146 function offsetGet($o) {
147 return $this->props
->$o;
153 function offsetSet($o, $v) {
154 $this->__set($o, $v);
160 function offsetExists($o) {
161 return isset($this->props
->$o);
167 function offsetUnset($o) {
168 unset($this->props
->$o);
175 $this->riter
= (array) $this->props
;
183 return NULL !== key($this->riter
);
197 return key($this->riter
);
204 return current($this->riter
);
210 function hasChildren() {
211 return current($this->riter
) instanceof Container
;
217 function getChildren() {
218 return current($this->riter
);
224 function jsonSerialize() {
225 return $this->arrayify($this);
229 /* vim: set noet ts=4 sw=4: */