/** * @param IItem $item Start item */ public function __construct(IItem $item) { $current = $item->getParent(); if ($current) { // If root isn't the only item in structure // Until we get to the root item while ($current->getParent()) { $this->itemPath[] = $current; $current = $current->getParent(); } } $this->itemPath = array_reverse($this->itemPath); }
/** * {@inheritDoc} * * Shouldn't be called manually. */ public function setParent(IItem $item) { if (!$item->hasChild($this)) { throw new Exception('Please do not call this function manually. Parent assignation is managed automatically.'); } if ($item->equals($this)) { throw new Exception('Item can\'t be a child to itself'); } $this->parent = $item; return $this; }
/** * Builds fake item structure by looping through iterator. * * @param IIterator $iterator * @param IItem $root * * @return IItem */ public function getProxy(IIterator $iterator, IItem $root) { $depth = 0; // Set iterator callbacks $stepDown = function () use(&$depth) { $depth++; }; $stepUp = function () use(&$depth) { $depth--; }; $iterator->setDescendCallback($stepDown); $iterator->setAscendCallback($stepUp); // Create root item $proxyRoot = $root->isolatedClone(); // Setup loop starting values $currentItem = $proxyRoot; $lastItem = $proxyRoot; $lastDepth = $depth; foreach ($iterator as $item) { /** @var $item IItem */ $proxy = $item->isolatedClone(); // Descended if ($lastDepth < $depth) { $currentItem = $lastItem; } // Ascended if ($lastDepth > $depth) { for ($i = 0; $i < $lastDepth - $depth; $i++) { $currentItem = $currentItem->getParent(); } } $currentItem->addChild($proxy); $lastItem = $proxy; $lastDepth = $depth; } return $proxyRoot; }
/** * @param IItem $item * @return null|IItem * @throws Component\Exception\Exception */ public function remove(IItem $item) { if (null === $item->getParent()) { throw new Exception('Root item can\'t be removed'); } $parent = $item->getParent(); $parent->removeChild($item); return $parent; }
/** * Checks if current position is valid * * @return bool */ public function valid() { return $this->current->getParent() !== null; }