fix var names and references
[mdref/mdref] / mdref / Reference.php
1 <?php
2
3 namespace mdref;
4
5 use ArrayIterator;
6 use Iterator;
7 use IteratorAggregate;
8 use function is_numeric;
9 use function preg_replace;
10
11 /**
12 * The complete available reference
13 */
14 class Reference implements IteratorAggregate {
15 /**
16 * List of mdref repositories
17 * @var Repo[]
18 */
19 private $repos = array();
20
21 /**
22 * @param array $refs list of mdref repository paths
23 */
24 public function __construct(array $refs) {
25 foreach ($refs as $path) {
26 $repo = new Repo($path);
27 $this->repos[$repo->getName()] = $repo;
28 }
29 }
30
31 /**
32 * Lookup the repo containing a ref entry
33 * @param string $entry requested reference entry, e.g. "pq/Connection/exec"
34 * @param string $canonical
35 * @return \mdref\Repo|NULL
36 */
37 public function getRepoForEntry(string $entry, string &$canonical = null) : ?Repo {
38 foreach ($this->repos as $repo) {
39 /** @var $repo Repo */
40 if ($repo->hasEntry($entry, $canonical)) {
41 return $repo;
42 }
43 }
44 return null;
45 }
46
47 /**
48 * Implements IteratorAggregate
49 * @return ArrayIterator repository list
50 */
51 public function getIterator() : Iterator {
52 return new ArrayIterator($this->repos);
53 }
54
55 /**
56 * @param string $anchor
57 * @return string
58 */
59 public function formatAnchor(string $anchor) : string {
60 if (is_numeric($anchor)) {
61 return "L$anchor";
62 }
63 return preg_replace("/[^[:alnum:]\.:_]/", ".", $anchor);
64 }
65
66 /**
67 * @param string $string
68 * @return string
69 * @throws \Exception
70 */
71 public function formatString(string $string) : string {
72 if (extension_loaded("discount")) {
73 $md = \MarkdownDocument::createFromString($string);
74 $md->compile(\MarkdownDocument::AUTOLINK);
75 return $md->getHtml();
76 }
77 if (extension_loaded("cmark")) {
78 $node = \CommonMark\Parse($string);
79 return \CommonMark\Render\HTML($node);
80 }
81 throw new \Exception("No Markdown implementation found");
82 }
83
84 /**
85 * @param string $file
86 * @return string
87 * @throws \Exception
88 */
89 public function formatFile(string $file) : string {
90 if (extension_loaded("discount")) {
91 $fd = fopen($file, "r");
92 $md = \MarkdownDocument::createFromStream($fd);
93 $md->compile(\MarkdownDocument::AUTOLINK | \MarkdownDocument::TOC);
94 $html = $md->getHtml();
95 fclose($fd);
96 return $html;
97 }
98 if (extension_loaded("cmark")) {
99 $node = \CommonMark\Parse(file_get_contents($file));
100 return \CommonMark\Render\HTML($node);
101 }
102 throw new \Exception("No Markdown implementation found");
103 }
104 }