legacy
[mdref/mdref] / mdref / Repo.php
1 <?php
2
3 namespace mdref;
4
5
6 /**
7 * A reference repo
8 */
9 class Repo implements \IteratorAggregate {
10 /**
11 * The name of the repository
12 * @var string
13 */
14 private $name;
15
16 /**
17 * The path to the repository
18 * @var string
19 */
20 private $path;
21
22 /**
23 * The edit url template
24 * @var string
25 */
26 private $edit;
27
28 /**
29 * Path to the repository containing the name.mdref file
30 * @param string $path
31 * @throws \InvalidArgumentException
32 */
33 public function __construct($path) {
34 if (!($mdref = current(glob("$path/*.mdref")))) {
35 throw new \InvalidArgumentException(
36 sprintf("Not a reference, could not find '*.mdref': '%s'",
37 $path));
38 }
39
40 $this->path = realpath($path);
41 $this->name = basename($mdref, ".mdref");
42 $this->edit = trim(file_get_contents($mdref));
43 }
44
45 /**
46 * Get the repository's name
47 * @return string
48 */
49 public function getName() {
50 return $this->name;
51 }
52
53 /**
54 * Get the path of the repository or a file in it
55 * @param string $file
56 * @return string
57 */
58 public function getPath($file = "") {
59 return $this->path . "/$file";
60 }
61
62 /**
63 * Get the edit url for a ref entry
64 * @param string $entry
65 * @return string
66 */
67 public function getEditUrl($entry) {
68 return sprintf($this->edit, $entry);
69 }
70
71 /**
72 * Get the file path of an entry in this repo
73 * @param string $entry
74 * @return string file path
75 */
76 public function hasEntry($entry, &$canonical = null) {
77 $file = $this->getPath("$entry.md");
78 if (is_file($file)) {
79 return $file;
80 }
81 $file = $this->getPath($this->getName()."/$entry.md");
82 if (is_file($file)) {
83 $canonical = $this->getName() . "/" . $entry;
84 return $file;
85 }
86 }
87
88 /**
89 * Get the canonical entry name of a file in this repo
90 * @param string $file
91 * @return string entry
92 */
93 public function hasFile($file) {
94 if (($file = realpath($file))) {
95 $path = $this->getPath();
96 $plen = strlen($path);
97 if (!strncmp($file, $path, $plen)) {
98 $dirname = dirname(substr($file, $plen));
99 $basename = basename($file, ".md");
100
101 if ($dirname === ".") {
102 return $basename;
103 }
104
105 return $dirname . "/". $basename;
106 }
107 }
108 }
109
110 /**
111 * Get an Entry instance
112 * @param string $entry
113 * @return \mdref\Entry
114 * @throws \OutOfBoundsException
115 */
116 public function getEntry($entry) {
117 return new Entry($entry, $this);
118 }
119
120 /**
121 * Get the root Entry instance
122 * @return \mdref\Entry
123 */
124 public function getRootEntry() {
125 return new Entry($this->name, $this);
126 }
127
128 /**
129 * Implements \IteratorAggregate
130 * @return \mdref\Tree
131 */
132 public function getIterator() {
133 return new Tree($this->path, $this);
134 }
135 }