fix repos containing supplementary .md files
[mdref/mdref] / mdref / Tree.php
1 <?php
2
3 namespace mdref;
4
5 class Tree implements \RecursiveIterator {
6 /**
7 * The repository
8 * @var \mdref\Repo
9 */
10 private $repo;
11
12 /**
13 * List of first level entries
14 * @var array
15 */
16 private $list = array();
17
18 /**
19 * The list iterator
20 * @var array
21 */
22 private $iter;
23
24 /**
25 * @param string $path
26 * @param \mdref\Repo $repo
27 */
28 public function __construct($path, Repo $repo) {
29 if (realpath($path)."/" === $repo->getPath()) {
30 $list = [$path ."/". $repo->getName() .".md"];
31 } elseif (!($list = glob("$path/*.md"))) {
32 $list = glob("$path/*/*.md");
33 }
34 if ($list) {
35 $this->list = array_filter($list, $this->generateFilter($list));
36 sort($this->list, SORT_STRING);
37 }
38 $this->repo = $repo;
39 }
40
41 /**
42 * @param array $list
43 * @return callable
44 */
45 private function generateFilter(array $list) {
46 return function($v) use($list) {
47 if ($v{0} === ".") {
48 return false;
49 }
50 if (false !== array_search("$v.md", $list, true)) {
51 return false;
52 }
53
54 $pi = pathinfo($v);
55 if (isset($pi["extension"]) && "md" !== $pi["extension"]) {
56 return false;
57 }
58
59 return true;
60 };
61 }
62
63 /**
64 * Implements \Iterator
65 * @return \mdref\Entry
66 */
67 public function current() {
68 return $this->repo->getEntry($this->repo->hasFile(current($this->iter)));
69 }
70
71 /**
72 * Implements \Iterator
73 */
74 public function next() {
75 next($this->iter);
76 }
77
78 /**
79 * Implements \Iterator
80 * @return int
81 */
82 public function key() {
83 return key($this->iter);
84 }
85
86 /**
87 * Implements \Iterator
88 */
89 public function rewind() {
90 $this->iter = $this->list;
91 reset($this->iter);
92 }
93
94 /**
95 * Implements \Iterator
96 * @return bool
97 */
98 public function valid() {
99 return null !== key($this->iter);
100 }
101
102 /**
103 * Implements \RecursiveIterator
104 * @return bool
105 */
106 public function hasChildren() {
107 return $this->current()->hasIterator();
108 }
109
110 /**
111 * Implements \RecursiveIterator
112 * @return \mdref\Tree
113 */
114 public function getChildren() {
115 return $this->current()->getIterator();
116 }
117 }