summaryrefslogtreecommitdiff
path: root/ext/spl/examples/recursivetreeiterator.inc
blob: 62198c8d3646b649ae1ddf028e15358dbfe088a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php

/** @file recursivetreeiterator.inc
 * @ingroup Examples
 * @brief   class RecursiveTreeIterator
 * @author  Marcus Boerger, Johannes Schlueter
 * @date    2005
 *
 * SPL - Standard PHP Library
 */


/** @ingroup Examples
 * @brief   RecursiveIteratorIterator to generate ASCII graphic trees for the
 *          entries in a RecursiveIterator
 * @author  Marcus Boerger, Johannes Schlueter
 * @version 1.0
 */
class RecursiveTreeIterator extends RecursiveIteratorIterator
{
	private $callToString;

	/**
	 * @param it         iterator to use as inner iterator
	 * @param flags      flags passed to RecursiveIteratoIterator (parent)
	 * @param cit_flags  flags passed to RecursiveCachingIterator (for hasNext)
	 */
	function __construct(RecursiveIterator $it, $flags = self::SELF_FIRST, $cit_flags = CachingIterator::CATCH_GET_CHILD)
	{
		parent::__construct(new RecursiveCachingIterator($it, $cit_flags), $flags);
		$this->callToString = (bool)($cit_flags & CachingIterator::CALL_TOSTRING);
	}

	/**  Prefix strings used in getPrefix()
	 *
	 * 0: prefix used to start elements
	 * 1: prefix used if $level < depth and hasNext($level) == true
	 * 2: prefix used if $level < depth and hasNext($level) == false
	 * 3: prefix used if $level == depth and hasNext($level) == true
	 * 4: prefix used if $level == depth and hasNext($level) == false
	 * 5: prefix used right in front of the current element
	 */
	public $prefix = array(0=>'', 1=>'| ', 2=>'  ', 3=>'|-', 4=>'\-', 5=>'');

	/** @return string to place in front of current element
	 */
	function getPrefix()
	{
		$tree = '';
		for ($level = 0; $level < $this->getDepth(); $level++)
		{
			$tree .= $this->getSubIterator($level)->hasNext() ? $this->prefix[1] : $this->prefix[2];
		}
		$tree .= $this->getSubIterator($level)->hasNext() ? $this->prefix[3] : $this->prefix[4];

		return $this->prefix[0] . $tree . $this->prefix[5];
	}

	/** @return string presentation build for current element
	 */
	function getEntry()
	{
		return $this->callToString ? $this->__toString() : parent::current();
	}

	/** @return string to place after the current element
	 */
	function getPostfix()
	{
		return '';
	}

	/** @return the current element prefixed and postfixed
	 */
	function current()
	{		
		return $this->getPrefix() . $this->getEntry() .  $this->getPostfix();
	}

	/** Aggregates the inner iterator
	 */
	function __call($func, $params)
	{
		return call_user_func_array(array($this->getSubIterator(), $func), $params);
	}
}

?>