fix ignore refs
[mdref/mdref] / mdref / File.php
1 <?php
2
3 namespace mdref;
4
5 /**
6 * A ref entry file
7 */
8 class File {
9 /**
10 * @var resource
11 */
12 private $fd;
13
14 /**
15 * Open the file
16 * @param string $path
17 */
18 public function __construct($path) {
19 $this->fd = fopen($path, "rb");
20 }
21
22 /**
23 * Read the title of the refentry
24 * @return string
25 */
26 public function readTitle() {
27 if ($this->rewind(1)) {
28 return fgets($this->fd);
29 }
30 }
31
32 /**
33 * Read the description (first line) of the refentry
34 * @return string
35 */
36 public function readDescription() {
37 if ($this->rewind()
38 && (false !== fgets($this->fd))
39 && (false !== fgets($this->fd))) {
40 return fgets($this->fd);
41 }
42 }
43
44 /**
45 * Read the full description (first section) of the refentry
46 * @return string
47 */
48 public function readFullDescription() {
49 $desc = $this->readDescription();
50 while (false !== ($line = fgets($this->fd))) {
51 if ($line{0} === "#") {
52 break;
53 } else {
54 $desc .= $line;
55 }
56 }
57 return $desc;
58 }
59
60 /**
61 * Read the first subsection of a global refentry
62 * @return string
63 */
64 public function readIntro() {
65 $intro = "";
66 if ($this->rewind()) {
67 $header = false;
68
69 while (!feof($this->fd)) {
70 if (false === ($line = fgets($this->fd))) {
71 break;
72 }
73 /* search first header and read until next header*/
74 if ($this->isHeading($line)) {
75 if ($header) {
76 break;
77 } else {
78 $header = true;
79 continue;
80 }
81 }
82 if ($header) {
83 $intro .= $line;
84 }
85 }
86 }
87 return $intro;
88 }
89
90 public function readSection($title) {
91 $section = "";
92 if ($this->rewind()) {
93 while (!feof($this->fd)) {
94 if (false === ($line = fgets($this->fd))) {
95 break;
96 }
97 /* search for heading with $title and read until next heading */
98 if ($this->isHeading($line, $title)) {
99 do {
100 if (false === $line = fgets($this->fd)) {
101 break;
102 }
103 if ($this->isHeading($line)) {
104 break;
105 }
106 $section .= $line;
107 } while (true);
108 }
109 }
110 }
111 return $section;
112 }
113
114 private function rewind($offset = 0) {
115 return 0 === fseek($this->fd, $offset, SEEK_SET);
116 }
117
118 private function isHeading($line, $title = null) {
119 if ("## " !== substr($line, 0, 3)) {
120 return false;
121 }
122 if (isset($title)) {
123 return !strncmp(substr($line, 3), $title, strlen($title));
124 }
125 return true;
126 }
127 }