convert to autocracy
[mdref/mdref] / mdref / RefEntry.php
1 <?php
2
3 namespace mdref;
4
5 class RefEntry
6 {
7 /**
8 * @var \mdref\Path
9 */
10 protected $path;
11
12 /**
13 * @var string
14 */
15 protected $entry;
16
17 /**
18 * @var resource
19 */
20 protected $file;
21
22 function __construct(Path $path, $entry = null) {
23 $this->path = $path;
24 $this->entry = $entry ?: $path->getPathName();
25 }
26
27 function __destruct() {
28 if (is_resource($this->file)) {
29 fclose($this->file);
30 }
31 }
32
33 function formatUrl() {
34 return htmlspecialchars($this->entry);
35 return implode("/", explode(DIRECTORY_SEPARATOR, trim(substr(
36 $this->entry, strlen($this->path->getBaseDir())),
37 DIRECTORY_SEPARATOR)));
38 }
39
40 protected function joinLink(array $parts) {
41 $link = "";
42 $upper = ctype_upper($parts[0][0]);;
43 for ($i = 0; $i < count($parts); ++$i) {
44 if (!strlen($parts[$i]) || $parts[$i] === ".") {
45 continue;
46 }
47 if (strlen($link)) {
48 if ($upper && !ctype_upper($parts[$i][0])) {
49 $link .= "::";
50 } else {
51 $link .= "\\";
52 }
53 }
54 $link .= $parts[$i];
55 $upper = ctype_upper($parts[$i][0]);
56 }
57 return $link;
58 }
59
60 function formatLink($basename = false) {
61 $link = "";
62 if (strlen($entry = trim($this->entry, DIRECTORY_SEPARATOR))) {
63 $parts = explode(DIRECTORY_SEPARATOR, $entry);
64 $link = $basename ? end($parts) : $this->joinLink($parts);
65 }
66 return htmlspecialchars($link);
67 }
68
69 protected function openFile() {
70 if (!is_resource($this->file)) {
71 $path = $this->path;
72 $file = $path($this->entry);
73 if (!$file->isFile()) {
74 throw new \Exception("Not a file: '$this->entry'");
75 }
76 if (!$this->file = fopen($file->getFullPath(".md"), "r")) {
77 throw new \Exception("Could not open {$this->entry}");
78 }
79 }
80 }
81
82 function readTitle() {
83 $this->openFile();
84 fseek($this->file, 1, SEEK_SET);
85 return htmlspecialchars(fgets($this->file));
86 }
87
88 function readDescription() {
89 $this->openFile();
90 fseek($this->file, 0, SEEK_SET);
91 fgets($this->file);
92 fgets($this->file);
93 return htmlspecialchars(fgets($this->file));
94 }
95 }