6 use InvalidArgumentException
;
10 use function file_get_contents
;
13 use function realpath
;
21 class Repo
implements IteratorAggregate
{
23 * The name of the repository
29 * The path to the repository
35 * The edit url template
41 * Path to the repository containing the name.mdref file
43 * @throws \InvalidArgumentException
45 public function __construct(string $path) {
46 if (!($glob = glob("$path/*.mdref"))) {
47 throw new InvalidArgumentException(
48 sprintf("Not a reference, could not find '*.mdref': '%s'", $path));
51 $mdref = current($glob);
52 $this->path
= realpath($path);
53 $this->name
= basename($mdref, ".mdref");
54 $this->edit
= trim(file_get_contents($mdref));
58 * Get the repository's name
61 public function getName() : string {
66 * Get the path of the repository or a file in it
70 public function getPath(string $file = "") : string {
71 return $this->path
. "/$file";
75 * Get the edit url for a ref entry
76 * @param string $entry
79 public function getEditUrl(string $entry) : string {
80 return sprintf($this->edit
, $entry);
84 * Get the file path of an entry in this repo
86 * @param string $entry
87 * @param string|null $canonical
88 * @return string file path
90 public function hasEntry(string $entry, ?
string &$canonical = null) : ?
string {
91 $trim = rtrim($entry, "/");
92 $file = $this->getPath("$trim.md");
94 if ($trim !== $entry) {
99 $file = $this->getPath($this->getName()."/$entry.md");
100 if (is_file($file)) {
101 $canonical = $this->getName() . "/" . $entry;
108 * Get the canonical entry name of a file in this repo
109 * @param string $file
110 * @return string entry
112 public function hasFile(string $file) : ?
string {
113 if (($file = realpath($file))) {
114 $path = $this->getPath();
115 $plen = strlen($path);
116 if (!strncmp($file, $path, $plen)) {
117 $dirname = dirname(substr($file, $plen));
118 $basename = basename($file, ".md");
120 if ($dirname === ".") {
124 return $dirname . "/". $basename;
131 * Check whether the repo has a stub file to serve
132 * @param string|null $path receives the path if there's a stub
135 public function hasStub(string &$path = null) : bool {
136 $path = $this->getPath($this->getName() . ".stub.php");
137 return is_file($path) && is_readable($path);
141 * Get an Entry instance
142 * @param string $entry
143 * @return \mdref\Entry
144 * @throws \OutOfBoundsException
146 public function getEntry(string $entry) : Entry
{
147 return new Entry($entry, $this);
151 * Get the root Entry instance
152 * @return \mdref\Entry
154 public function getRootEntry() : Entry
{
155 return new Entry($this->name
, $this);
159 * Implements \IteratorAggregate
160 * @return \mdref\Tree
162 public function getIterator() : Tree
{
163 return new Tree($this->path
, $this);