<?phpnamespace ProjectBiz\PortalBundle\View\TableView\Accessor;use ProjectBiz\PortalBundle\View\TableView\HasKeys;use ProjectBiz\PortalBundle\View\TableView\HasRawData;class KeyBasedAccessor implements \Iterator, \ArrayAccess, HasKeys, HasRawData{ protected $data; private $keys; private $currentIndex; public function __construct( $data = null ) { $this->data = $data; $this->currentIndex = -1; } /* * Iterator */ public function current() { return $this[$this->getKeys()[$this->currentIndex]]; } public function next() { ++$this->currentIndex; } public function key() { return $this->getKeys()[$this->currentIndex]; } public function valid() { return ($this->currentIndex >=0) && ($this->currentIndex < count($this->getKeys())); } public function rewind() { $this->currentIndex = 0; } /* * ArrayAccess */ public function offsetExists($offset) { return array_key_exists($offset, $this->getKeys()); } public function offsetGet($offset) { return $this->data[$offset]; } public function offsetSet($offset, $value) { throw new \Exception('Unable to set value in read-only array'); } public function offsetUnset($offset) { throw new \Exception('Unable to unset value in read-only array'); } /* * HasKeys */ public function getKeys() { if (!$this->keys) { $this->keys = $this->buildKeys(); } return $this->keys; } /* * helpers */ protected function buildKeys() { $keys = []; if (is_array($this->data)) { $keys = array_keys($this->data); } else if($this->data instanceof HasKeys) { $keys = $this->data->getKeys(); } else if($this->data instanceof \Iterator) { $this->data->rewind(); while ($this->data->valid()) { $keys[] = $this->data->key(); } } else { foreach ($this->data as $key => $_){ $keys[] = $key; } } return $keys; } function getRawData() { if ($this->data instanceof HasRawData) { return $this->data->getRawData(); } return $this->data; }}