<?php declare(strict_types=1); final class RecursiveFixedArrayProxy implements IteratorAggregate, RecursiveIterator { private SplFixedArray $splFixedArray; public function __construct(iterable $iterable = []) { $this->splFixedArray = new SplFixedArray( is_countable($iterable) ? count($iterable) : iterator_count($iterable) ); $offset = 0; $size = $this->splFixedArray->count(); foreach ($iterable as $key => $value) { if($offset === $size){ // resize the SplFixedArray when nessary. (if the iterable passed in via the __construct implements countable differently eg. where count() returns the capacity/size of the iterable) $this->splFixedArray->setSize(++$size); } if(is_array($value)){ // save arrays as RecursiveFixedArrayProxy $this->splFixedArray->offsetSet($offset++, new self($value)); continue; } // save all other values as stdClass via Closure $this->splFixedArray->offsetSet( $offset++, (static function(mixed $key = null, mixed $value = null): stdClass{ $stdClass = new stdClass(); $stdClass->key = $key; $stdClass->value = $value; return $stdClass; })($key, $value) ); } $this->splFixedArray->setSize($offset); } // required from IteratorAggregate public function getIterator(): Generator { // to provide a Recursive SplFixedArray implemtation. yield from new RecursiveArrayIterator( // is this wrong? trying to avoid using arrays, for memory boost // avoids: $this->splFixedArray->toArray() $this->splFixedArray ); } // required from RecursiveIterator public function getChildren(): ?RecursiveIterator { /** @return RecursiveFixedArray */ return $this->current(); } // required from RecursiveIterator public function hasChildren(): bool { // traverse recursively if *current* is instance of RecursiveFixedArray return $this->current() instanceof RecursiveFixedArray; } }
You have javascript disabled. You will not be able to edit any code.