Skip to content

Instantly share code, notes, and snippets.

@dvessel
Created March 9, 2011 01:32
Show Gist options
  • Save dvessel/861520 to your computer and use it in GitHub Desktop.
Save dvessel/861520 to your computer and use it in GitHub Desktop.
Class abstract extended from FilterIterator and implements RecursiveIterator.
<?php
/**
* @file RecursiveMultiFilterIterator.php
* @brief Class abstract extended from RecursiveFilterIterator.
* @author Joon Park (joon@dvessel.com)
*/
/**
* This is an abstract class. Extended it with a custom accept() and/or
* acceptChildren() method to make it useful.
*/
abstract class RecursiveMultiFilterIterator extends RecursiveFilterIterator {
private $parent;
private $depth = 0;
/**
* Called after the creation of a new child instance. This is useful for
* carrying over the state of properties from parent iterators. Use
* getParent() to get all parent methods and properties.
*/
public function initChild() {
// do something...
}
/**
* Accept function to decide whether an element of the inner iterator
* should be accessible through the Filteriterator.
*
* @return
* Whether or not to expose the current element of the inner iterator.
*/
public function accept() {
return TRUE;
}
/**
* When the current element has passed accept() and contains children,
* further checks can be made here to allow or prevent further processing of
* child elements.
*/
public function acceptChildren() {
return TRUE;
}
/**
* @return
* The current depth.
*/
public function getDepth() {
return $this->depth;
}
/**
* @return
* The immediate parent instance.
*/
public function getParent() {
return $this->parent;
}
/**
* Called from getChildren() to pass parents into children.
*/
public function pushParent($parent) {
$this->parent = $parent;
$this->depth = $parent->depth + 1;
return $this;
}
/**
* Checks if the current element contains children. It must also pass the
* acceptChildren() method.
*
* @return
* Whether the current element has children.
*/
public function hasChildren() {
return $this->getInnerIterator()->hasChildren() && $this->acceptChildren();
}
/**
* Gets called when hasChildren() returns TRUE.
*
* @return
* An iterator for the elements children in the same class as $this.
*/
public function getChildren() {
$child = new $this($this->getInnerIterator()->getChildren());
$child->pushParent($this)->initChild();
return $child;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment