refactoaaar
[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 = trim($entry ?: $path->getPathName(), DIRECTORY_SEPARATOR);
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 }
36
37 private function joinLink(array $parts) {
38 $link = "";
39 $upper = ctype_upper($parts[0][0]);;
40 for ($i = 0; $i < count($parts); ++$i) {
41 if (!strlen($parts[$i]) || $parts[$i] === ".") {
42 continue;
43 }
44 if (strlen($link)) {
45 if ($upper && !ctype_upper($parts[$i][0])) {
46 $link .= "::";
47 } else {
48 $link .= "\\";
49 }
50 }
51 $link .= $parts[$i];
52 $upper = ctype_upper($parts[$i][0]);
53 }
54 return $link;
55 }
56
57 function formatLink($basename = false) {
58 $link = "";
59 if (strlen($this->entry)) {
60 $parts = explode(DIRECTORY_SEPARATOR, $this->entry);
61 $link = $basename ? end($parts) : $this->joinLink($parts);
62 }
63 return htmlspecialchars($link);
64 }
65
66 function getPath() {
67 $path = $this->path;
68 $file = $path($this->entry);
69 return $file;
70 }
71
72 private function openFile() {
73 if (!is_resource($this->file)) {
74 $file = $this->getPath();
75
76 if (!$file->isFile()) {
77 throw new \Exception("Not a file: '{$this->entry}'");
78 }
79 if (!$this->file = fopen($file->getFullPath(".md"), "r")) {
80 throw new \Exception("Could not open {$this->entry}");
81 }
82 }
83 }
84
85 function readTitle() {
86 $this->openFile();
87 fseek($this->file, 1, SEEK_SET);
88 return htmlspecialchars(fgets($this->file));
89 }
90
91 function readDescription() {
92 $this->openFile();
93 fseek($this->file, 0, SEEK_SET);
94 fgets($this->file);
95 fgets($this->file);
96 return htmlspecialchars(fgets($this->file));
97 }
98
99 function formatEditUrl() {
100 $path = $this->path;
101 $base = current(explode(DIRECTORY_SEPARATOR, $path->getPathName()));
102 $file = $path($base);
103 if ($file->isFile(".mdref")) {
104 return sprintf(file_get_contents($file->getFullPath(".mdref")),
105 $this->entry);
106 }
107 }
108 }