add og:title
[mdref/mdref] / mdref / Structure.php
1 <?php
2
3 namespace mdref;
4
5 /**
6 * Structure of an entry
7 */
8 class Structure {
9 const OF_OTHER = "other";
10 const OF_NAMESPACE = "ns";
11 const OF_CLASS = "class";
12 const OF_FUNC = "func";
13
14 private $type;
15 private $struct;
16 private $entry;
17
18 function __construct(Entry $entry) {
19 $this->entry = $entry;
20
21 if ($entry->isRoot() || $entry->isNsClass()) {
22 if ($entry->isRoot()) {
23 $this->type = self::OF_NAMESPACE;
24 $this->getStructureOfRoot();
25 } elseif (!strncmp($entry->getTitle(), "namespace", strlen("namespace"))) {
26 $this->type = self::OF_NAMESPACE;
27 $this->getStructureOfNs();
28 } else {
29 $this->type = self::OF_CLASS;
30 $this->getStructureOfClass();
31 }
32 } elseif ($entry->isFunction()) {
33 $this->type = self::OF_FUNC;
34 $this->getStructureOfFunc();
35 } else {
36 $this->type = self::OF_OTHER;
37 }
38 }
39
40 static function of(Entry $entry) : StructureOf {
41 return (new static($entry))->getStruct();
42 }
43
44 function getStruct() : StructureOf {
45 return $this->struct;
46 }
47
48 function format() {
49 $this->struct->format();
50 }
51
52 private function getStructureOfFunc() : StructureOfFunc {
53 return $this->struct = new StructureOfFunc([
54 "ns" => $this->entry->getParent()->getNsName(),
55 "name" => $this->entry->getEntryName(),
56 "desc" => $this->entry->getFullDescription(),
57 "returns" => $this->getReturns(),
58 "params" => $this->getParams(),
59 "throws" => $this->getThrows()
60 ]);
61 }
62
63 private function getStructureOfClass() : StructureOfClass {
64 return $this->struct = new StructureOfClass([
65 "ns" => $this->entry->getParent()->getNsName(),
66 "name" => $this->prepareClassName(),
67 "desc" => $this->entry->getFullDescription(),
68 "consts" => $this->getConstants(),
69 "props" => $this->getProperties(),
70 "funcs" => $this->getFunctions(),
71 "classes" => $this->getClasses(),
72 ]);
73 }
74
75 private function getStructureOfNs() : StructureOfNs {
76 return $this->struct = new StructureOfNs([
77 "name" => $this->entry->getNsName(),
78 "desc" => $this->entry->getFullDescription(),
79 "consts" => $this->getConstants(),
80 "classes" => $this->getClasses(),
81 ]);
82 }
83
84 private function getStructureOfRoot() : StructureOfRoot {
85 return $this->struct = new StructureOfRoot([
86 "name" => $this->entry->getName(),
87 "desc" => $this->entry->getFile()->readIntro(),
88 "consts" => $this->getConstants(),
89 "classes" => $this->getClasses()
90 ]);
91 }
92
93 private function getSection(string $section) : string {
94 return $this->entry->getFile()->readSection($section);
95 }
96
97 private function prepareClassName() {
98 return preg_replace_callback_array([
99 '/(?P<type>class|interface|trait)\s+([\\\\\w]+\\\)?(?P<name>\w+)\s*/' => function($match) {
100 return $match["type"] . " " . $match["name"] . " ";
101 },
102 '/(?P<op>extends|implements)\s+(?P<names>[\\w]+(?:(?:,\s*[\\\\\w]+)*))/' => function ($match) {
103 return $match["op"] . " " . preg_replace('/\b(?<!\\\)(\w)/', '\\\\\\1', $match["names"]);
104 }
105 ], $this->entry->getTitle());
106 }
107
108 private function splitList(string $pattern, string $text) : array {
109 $text = trim($text);
110 if (strlen($text) && !preg_match("/^None/", $text)) {
111 if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
112 return $matches;
113 }
114 }
115 return [];
116 }
117
118 private function getConstantValue(string $name) {
119 $ns = $this->entry->getNsName();
120 if (defined("\\$ns::$name")) {
121 return constant("\\$ns::$name");
122 }
123 if (defined("\\$ns\\$name")) {
124 return constant("\\$ns\\$name");
125 }
126 return null;
127 }
128
129 private function getConstants() : array {
130 static $pattern = '/
131 \*\s+
132 (?:[<]span[ ]class="constant"[>])?
133 (?<name>\w+)
134 (?:[<]\/span[>])?
135 (?:\s*=\s*(?P<value>.+))?
136 (?P<desc>(?:\s*\n\s*[^\*\n#].*)*)
137 /x';
138
139 $structs = [];
140 $consts = $this->splitList($pattern, $this->getSection("Constants"));
141 foreach ($consts as $const) {
142 if (!isset($const["value"]) || !strlen($const["value"])) {
143 $const["value"] = $this->getConstantValue($const["name"]);
144 }
145 $structs[$const["name"]] = new StructureOfConst($const);
146 }
147 return $structs;
148 }
149
150 private function getProperties() : array {
151 static $pattern = '/
152 \*\s+
153 (?P<modifiers>\w+\s+)*
154 (?:\((?P<usages>(?:(?:\w+)\s*)*)\))*\s*
155 (?P<type>[\\\\\w]+)\s+
156 (?<name>\$\w+)
157 (?:\s*=\s*(?P<defval>.+))?
158 (?P<desc>(?:\s*\n\s*[^\*].*)*)
159 /x';
160
161 $structs = [];
162 $props = $this->splitList($pattern, $this->getSection("Properties"));
163 foreach ($props as $prop) {
164 $structs[$prop["name"]] = new StructureOfVar($prop);
165 }
166 return $structs;
167 }
168
169 private function getFunctions() : array {
170 $structs = [];
171 foreach ($this->entry as $sub) {
172 if ($sub->isFunction()) {
173 $structs[$sub->getEntryName()] = static::of($sub);
174 }
175 }
176 return $structs;
177 }
178
179 private function getClasses() : array {
180 $structs = [];
181 foreach ($this->entry as $sub) {
182 if ($sub->isNsClass()) {
183 $structs[$sub->getEntryName()] = static::of($sub);
184 }
185 }
186 return $structs;
187 }
188
189 private function getParams() : array {
190 static $pattern = '/
191 \*\s+
192 (?P<modifiers>\w+\s+)*
193 (?P<type>[\\\\\w_]+)\s+
194 (?P<ref>&)?(?P<name>\$[\w_]+)
195 (?:\s*=\s*(?P<defval>.+))?
196 (?P<desc>(?:\s*[^*]*\n(?!\n)\s*[^\*].*)*)
197 /x';
198
199 $structs = [];
200 $params = $this->splitList($pattern, $this->getSection("Params"));
201 foreach ($params as $param) {
202 $structs[$param["name"]] = new StructureOfVar($param);
203 }
204 return $structs;
205 }
206
207 private function getReturns() : array {
208 static $pattern = '/
209 \*\s+
210 (?<type>[\\\\\w_]+)
211 \s*,?\s*
212 (?P<desc>(?:.|\n(?!\s*\*))*)
213 /x';
214
215 $returns = $this->splitList($pattern, $this->getSection("Returns"));
216 $retvals = [];
217 foreach ($returns as list(, $type, $desc)) {
218 $retvals[] = [$type, $desc];
219 }
220 return $retvals;
221 return [implode("|", array_unique(array_column($returns, "type"))), $retdesc];
222 }
223
224 private function getThrows() : array {
225 static $pattern = '/
226 \*\s+
227 (?P<exception>[\\\\\w]+)\s*
228 /x';
229
230 $throws = $this->splitList($pattern, $this->getSection("Throws"));
231 return array_column($throws, "exception");
232 }
233 }
234
235 abstract class StructureOf {
236 function __construct(array $props = []) {
237 foreach ($props as $key => $val) {
238 if (is_int($key)) {
239 continue;
240 }
241 if (!property_exists(static::class, $key)) {
242 throw new \UnexpectedValueException(
243 sprintf("Property %s::\$%s does not exist", static::class, $key)
244 );
245 }
246 if ($key === "desc" || $key === "modifiers" || $key === "defval") {
247 $val = trim($val);
248 }
249 $this->$key = $val;
250 }
251 }
252
253 // abstract function format();
254
255 function formatDesc($level, array $tags = []) {
256 $indent = str_repeat("\t", $level);
257 $desc = trim($this->desc);
258 if (false !== stristr($desc, "deprecated in")) {
259 $tags[] = "deprecated";
260 }
261 if ($tags) {
262 $desc .= "\n\n@" . implode("\n@", $tags);
263 }
264 $desc = preg_replace('/[\t ]*\n/',"\n$indent * ", $desc);
265 printf("%s/**\n%s * %s\n%s */\n", $indent, $indent, $desc, $indent);
266 }
267
268 function saneTypes(array $types) {
269 $sane = [];
270 foreach ($types as $type) {
271 if (strlen($s = $this->saneType($type, false))) {
272 $sane[] = $s;
273 }
274 }
275 return $sane;
276 }
277
278 function saneType($type, $strict = true) {
279 switch (strtolower($type)) {
280 case "object":
281 case "resource":
282 case "stream":
283 case "mixed":
284 case "true":
285 case "false":
286 case "null":
287 if ($strict) {
288 break;
289 }
290 /* fallthrough */
291 case "bool":
292 case "int":
293 case "float":
294 case "string":
295 case "array":
296 case "callable":
297 return $type;
298 break;
299 default:
300 return ($type[0] === "\\" ? "":"\\") . $type;
301 break;
302 }
303 }
304 }
305
306 class StructureOfRoot extends StructureOf {
307 public $name;
308 public $desc;
309 public $consts;
310 public $classes;
311
312 function format() {
313 $this->formatDesc(0);
314
315 foreach ($this->consts as $const) {
316 $const->format(0);
317 printf(";\n");
318 }
319
320 printf("namespace %s;\nuse %s;\n", $this->name, $this->name);
321 StructureOfNs::$last = $this->name;
322
323 foreach ($this->getClasses() as $class) {
324 $class->format();
325 }
326 }
327
328 function getClasses() {
329 yield from $this->classes;
330 foreach ($this->classes as $class) {
331 yield from $class->getClasses();
332 }
333 }
334 }
335 class StructureOfNs extends StructureOfRoot {
336 public $funcs;
337
338 public static $last;
339
340 function format() {
341 print $this->formatDesc(0);
342
343 if (strlen($this->name) && $this->name !== StructureOfNs::$last) {
344 StructureOfNs::$last = $this->name;
345 printf("namespace %s;\n", $this->name);
346 }
347 foreach ($this->consts as $const) {
348 $const->format(0);
349 printf(";\n");
350 }
351 }
352 }
353
354 class StructureOfClass extends StructureOfNs
355 {
356 public $ns;
357 public $props;
358
359 function format() {
360 if ($this->ns !== StructureOfNs::$last) {
361 printf("namespace %s;\n", $this->ns);
362 StructureOfNs::$last = $this->ns;
363 }
364
365 print $this->formatDesc(0);
366 printf("%s {\n", $this->name);
367
368 foreach ($this->consts as $const) {
369 $const->format(1);
370 printf(";\n");
371 }
372
373 foreach ($this->props as $prop) {
374 $prop->formatAsProp(1);
375 printf(";\n");
376 }
377
378 foreach ($this->funcs as $func) {
379 $func->format(1);
380 if (strncmp($this->name, "interface", strlen("interface"))) {
381 printf(" {}\n");
382 } else {
383 printf(";\n");
384 }
385 }
386
387 printf("}\n");
388 }
389 }
390
391 class StructureOfFunc extends StructureOf {
392 public $ns;
393 public $class;
394 public $name;
395 public $desc;
396 public $params;
397 public $returns;
398 public $throws;
399
400 function omitParamTypes() {
401 switch ($this->name) {
402 // ArrayAccess
403 case "offsetGet":
404 case "offsetSet":
405 case "offsetExists":
406 case "offsetUnset":
407 // Serializable
408 case "serialize":
409 case "unserialize":
410 return true;
411 }
412 return false;
413 }
414
415 function format(int $level) {
416 $tags = [];
417 foreach ($this->params as $param) {
418 $type = $this->saneType($param->type, false);
419 $tags[] = "param {$type} {$param->name} {$param->desc}";
420 }
421 foreach ($this->throws as $throws) {
422 $tags[] = "throws " . $this->saneType($throws);
423 }
424 if ($this->name !== "__construct" && $this->returns) {
425
426 if (count($this->returns) > 1) {
427 $type = implode("|", $this->saneTypes(array_column($this->returns, 0)));
428 $desc = "";
429 foreach ($this->returns as list($typ, $ret)) {
430 if (strlen($desc)) {
431 $desc .= "\n\t\t or ";
432 }
433 $desc .= $this->saneType($typ, false) . " " . $ret;
434 }
435 } else {
436 $type = $this->saneType($this->returns[0][0], false);
437 $desc = $this->returns[0][1];
438 }
439 $tags[] = "return $type $desc";
440 }
441 $this->formatDesc(1, $tags);
442 printf("\tfunction %s(", $this->name);
443 $comma = "";
444 $omit = $this->omitParamTypes();
445 foreach ($this->params as $param) {
446 print $comma;
447 $param->formatAsParam($level, !$omit);
448 $comma = ", ";
449 }
450 printf(")");
451 }
452 }
453
454 class StructureOfConst extends StructureOf {
455 public $name;
456 public $desc;
457 public $value;
458
459 function format(int $level) {
460 $indent = str_repeat("\t", $level);
461 $this->formatDesc($level);
462 printf("%sconst %s = ", $indent, $this->name);
463 var_export($this->value);
464 }
465 }
466
467 class StructureOfVar extends StructureOf {
468 public $name;
469 public $type;
470 public $desc;
471 public $modifiers;
472 public $usages;
473 public $defval;
474 public $ref;
475
476 function formatDefval() {
477 if (strlen($this->defval)) {
478 if (false && defined($this->defval)) {
479 printf(" = ");
480 var_export(constant($this->defval));
481 } else if (strlen($this->defval)) {
482 if (false !== strchr($this->defval, "\\") && $this->defval[0] != "\\") {
483 $this->defval = "\\" . $this->defval;
484 }
485 printf(" = %s", $this->defval);
486 }
487 } elseif ($this->modifiers) {
488 if (stristr($this->modifiers, "optional") !== false) {
489 printf(" = NULL");
490 }
491 }
492 }
493 function formatAsProp($level) {
494 $indent = str_repeat("\t", $level);
495 $this->formatDesc($level,
496 preg_split('/\s+/', $this->modifiers ." " . $this->usages, -1, PREG_SPLIT_NO_EMPTY)
497 + [-1 => "var " . $this->saneType($this->type, false)]
498 );
499 printf("%s%s %s", $indent, $this->modifiers, $this->name);
500 $this->formatDefval();
501 }
502
503 function formatAsParam($level, $with_type = true) {
504 if ($with_type && strlen($type = $this->saneType($this->type))) {
505 printf("%s ", $type);
506 }
507 printf("%s%s", $this->ref, $this->name);
508 $this->formatDefval();
509 }
510 }