4197de1afa015c8aa6d14beefd81af125018ec69
[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 * @var Formatter
23 */
24 private $fmt;
25
26 /**
27 * @param array $refs list of mdref repository paths
28 */
29 public function __construct(array $refs, Formatter $fmt = null) {
30 foreach ($refs as $path) {
31 $repo = new Repo($path);
32 $this->repos[$repo->getName()] = $repo;
33 }
34 $this->fmt = $fmt ?: new Formatter;
35 }
36
37 /**
38 * Get the formatter.
39 * @return Formatter
40 */
41 public function getFormatter() : Formatter {
42 return $this->fmt;
43 }
44
45 /**
46 * Lookup the repo containing a ref entry
47 * @param string $entry requested reference entry, e.g. "pq/Connection/exec"
48 * @param string $canonical
49 * @return \mdref\Repo|NULL
50 */
51 public function getRepoForEntry(string $entry, string &$canonical = null) : ?Repo {
52 foreach ($this->repos as $repo) {
53 /** @var $repo Repo */
54 if ($repo->hasEntry($entry, $canonical)) {
55 return $repo;
56 }
57 }
58 return null;
59 }
60
61 /**
62 * Implements IteratorAggregate
63 * @return ArrayIterator repository list
64 */
65 public function getIterator() : Iterator {
66 return new ArrayIterator($this->repos);
67 }
68
69 /**
70 * @param string $anchor
71 * @return string
72 */
73 public function formatAnchor(string $anchor, string $location = null) : string {
74 if (is_numeric($anchor)) {
75 return "L$anchor";
76 }
77 return preg_replace("/[^[:alnum:]\.:_]/", ".", $anchor);
78 }
79
80 /**
81 * @param string $string
82 * @return string
83 * @throws \Exception, Exception
84 */
85 public function formatString(string $string, string $location = null) : string {
86 return $this->fmt->formatString($string, $location);
87 }
88
89 /**
90 * @param string $file
91 * @return string
92 * @throws \Exception, Exception
93 */
94 public function formatFile(string $file, string $location = null) : string {
95 return $this->fmt->formatFile($file, $location);
96 }
97 }