reveal full hierarchy in sidebar
[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 (?<name>\w+)
133 (?:\s*=\s*(?P<value>.+))?
134 (?P<desc>(?:\s*\n\s*[^\*\n#].*)*)
135 /x';
136
137 $structs = [];
138 $consts = $this->splitList($pattern, $this->getSection("Constants"));
139 foreach ($consts as $const) {
140 if (!isset($const["value"]) || !strlen($const["value"])) {
141 $const["value"] = $this->getConstantValue($const["name"]);
142 }
143 $structs[$const["name"]] = new StructureOfConst($const);
144 }
145 return $structs;
146 }
147
148 private function getProperties() : array {
149 static $pattern = '/
150 \*\s+
151 (?P<modifiers>\w+\s+)*
152 (?P<type>[\\\\\w]+)\s+
153 (?<name>\$\w+)
154 (?:\s*=\s*(?P<defval>.+))?
155 (?P<desc>(?:\s*\n\s*[^\*].*)*)
156 /x';
157
158 $structs = [];
159 $props = $this->splitList($pattern, $this->getSection("Properties"));
160 foreach ($props as $prop) {
161 $structs[$prop["name"]] = new StructureOfVar($prop);
162 }
163 return $structs;
164 }
165
166 private function getFunctions() : array {
167 $structs = [];
168 foreach ($this->entry as $sub) {
169 if ($sub->isFunction()) {
170 $structs[$sub->getEntryName()] = static::of($sub);
171 }
172 }
173 return $structs;
174 }
175
176 private function getClasses() : array {
177 $structs = [];
178 foreach ($this->entry as $sub) {
179 if ($sub->isNsClass()) {
180 $structs[$sub->getEntryName()] = static::of($sub);
181 }
182 }
183 return $structs;
184 }
185
186 private function getParams() : array {
187 static $pattern = '/
188 \*\s+
189 (?P<modifiers>\w+\s+)*
190 (?P<type>[\\\\\w]+)\s+
191 (?<name>\$\w+)
192 (?:\s*=\s*(?P<defval>.+))?
193 (?P<desc>(?:\s*[^*]*\n(?!\n)\s*[^\*].*)*)
194 /x';
195
196 $structs = [];
197 $params = $this->splitList($pattern, $this->getSection("Params"));
198 foreach ($params as $param) {
199 $structs[$param["name"]] = new StructureOfVar($param);
200 }
201 return $structs;
202 }
203
204 private function getReturns() : array {
205 static $pattern = '/
206 \*\s+
207 (?<type>[\\\\\w]+)
208 \s*,?\s*
209 (?P<desc>(?:.|\n(?!\s*\*))*)
210 /x';
211
212 $returns = $this->splitList($pattern, $this->getSection("Returns"));
213 $retvals = [];
214 foreach ($returns as list(, $type, $desc)) {
215 $retvals[] = [$type, $desc];
216 }
217 return $retvals;
218 return [implode("|", array_unique(array_column($returns, "type"))), $retdesc];
219 }
220
221 private function getThrows() : array {
222 static $pattern = '/
223 \*\s+
224 (?P<exception>[\\\\\w]+)\s*
225 /x';
226
227 $throws = $this->splitList($pattern, $this->getSection("Throws"));
228 return array_column($throws, "exception");
229 }
230 }
231
232 abstract class StructureOf {
233 function __construct(array $props = []) {
234 foreach ($props as $key => $val) {
235 if (is_int($key)) {
236 continue;
237 }
238 if (!property_exists(static::class, $key)) {
239 throw new \UnexpectedValueException(
240 sprintf("Property %s::\$%s does not exist", static::class, $key)
241 );
242 }
243 if ($key === "desc" || $key === "modifiers" || $key === "defval") {
244 $val = trim($val);
245 }
246 $this->$key = $val;
247 }
248 }
249
250 // abstract function format();
251
252 function formatDesc($level, array $tags = []) {
253 $indent = str_repeat("\t", $level);
254 $desc = trim($this->desc);
255 if (false !== stristr($desc, "deprecated in")) {
256 $tags[] = "deprecated";
257 }
258 if ($tags) {
259 $desc .= "\n\n@" . implode("\n@", $tags);
260 }
261 $desc = preg_replace('/[\t ]*\n/',"\n$indent * ", $desc);
262 printf("%s/**\n%s * %s\n%s */\n", $indent, $indent, $desc, $indent);
263 }
264
265 function saneTypes(array $types) {
266 $sane = [];
267 foreach ($types as $type) {
268 if (strlen($s = $this->saneType($type, false))) {
269 $sane[] = $s;
270 }
271 }
272 return $sane;
273 }
274
275 function saneType($type, $strict = true) {
276 switch (strtolower($type)) {
277 case "object":
278 case "resource":
279 case "stream":
280 case "mixed":
281 case "true":
282 case "false":
283 case "null":
284 if ($strict) {
285 break;
286 }
287 /* fallthrough */
288 case "bool":
289 case "int":
290 case "float":
291 case "string":
292 case "array":
293 case "callable":
294 return $type;
295 break;
296 default:
297 return ($type{0} === "\\" ? "":"\\") . $type;
298 break;
299 }
300 }
301 }
302
303 class StructureOfRoot extends StructureOf {
304 public $name;
305 public $desc;
306 public $consts;
307 public $classes;
308
309 function format() {
310 $this->formatDesc(0);
311
312 foreach ($this->consts as $const) {
313 $const->format(0);
314 printf(";\n");
315 }
316
317 printf("namespace %s;\nuse %s;\n", $this->name, $this->name);
318 StructureOfNs::$last = $this->name;
319
320 foreach ($this->getClasses() as $class) {
321 $class->format();
322 }
323 }
324
325 function getClasses() {
326 yield from $this->classes;
327 foreach ($this->classes as $class) {
328 yield from $class->getClasses();
329 }
330 }
331 }
332 class StructureOfNs extends StructureOfRoot {
333 public $funcs;
334
335 public static $last;
336
337 function format() {
338 print $this->formatDesc(0);
339
340 if (strlen($this->name) && $this->name !== StructureOfNs::$last) {
341 StructureOfNs::$last = $this->name;
342 printf("namespace %s;\n", $this->name);
343 }
344 foreach ($this->consts as $const) {
345 $const->format(0);
346 printf(";\n");
347 }
348 }
349 }
350
351 class StructureOfClass extends StructureOfNs
352 {
353 public $ns;
354 public $props;
355
356 static $lastNs;
357
358 function format() {
359 if ($this->ns !== StructureOfNs::$last) {
360 printf("namespace %s;\n", $this->ns);
361 StructureOfNs::$last = $this->ns;
362 }
363
364 print $this->formatDesc(0);
365 printf("%s {\n", $this->name);
366
367 foreach ($this->consts as $const) {
368 $const->format(1);
369 printf(";\n");
370 }
371
372 foreach ($this->props as $prop) {
373 $prop->formatAsProp(1);
374 printf(";\n");
375 }
376
377 foreach ($this->funcs as $func) {
378 $func->format(1);
379 if (strncmp($this->name, "interface", strlen("interface"))) {
380 printf(" {}\n");
381 } else {
382 printf(";\n");
383 }
384 }
385
386 printf("}\n");
387 }
388 }
389
390 class StructureOfFunc extends StructureOf {
391 public $ns;
392 public $class;
393 public $name;
394 public $desc;
395 public $params;
396 public $returns;
397 public $throws;
398
399 function omitParamTypes() {
400 switch ($this->name) {
401 // ArrayAccess
402 case "offsetGet":
403 case "offsetSet":
404 case "offsetExists":
405 case "offsetUnset":
406 // Serializable
407 case "serialize":
408 case "unserialize":
409 return true;
410 }
411 return false;
412 }
413
414 function format(int $level) {
415 $tags = [];
416 foreach ($this->params as $param) {
417 $type = $this->saneType($param->type, false);
418 $tags[] = "param {$type} {$param->name} {$param->desc}";
419 }
420 foreach ($this->throws as $throws) {
421 $tags[] = "throws " . $this->saneType($throws);
422 }
423 if ($this->name !== "__construct" && $this->returns) {
424
425 if (count($this->returns) > 1) {
426 $type = implode("|", $this->saneTypes(array_column($this->returns, 0)));
427 $desc = "";
428 foreach ($this->returns as list($typ, $ret)) {
429 if (strlen($desc)) {
430 $desc .= "\n\t\t or ";
431 }
432 $desc .= $this->saneType($typ, false) . " " . $ret;
433 }
434 } else {
435 $type = $this->saneType($this->returns[0][0], false);
436 $desc = $this->returns[0][1];
437 }
438 $tags[] = "return $type $desc";
439 }
440 $this->formatDesc(1, $tags);
441 printf("\tfunction %s(", $this->name);
442 $comma = "";
443 $omit = $this->omitParamTypes();
444 foreach ($this->params as $param) {
445 print $comma;
446 $param->formatAsParam($level, !$omit);
447 $comma = ", ";
448 }
449 printf(")");
450 }
451 }
452
453 class StructureOfConst extends StructureOf {
454 public $name;
455 public $desc;
456 public $value;
457
458 function format(int $level) {
459 $indent = str_repeat("\t", $level);
460 $this->formatDesc($level);
461 printf("%sconst %s = ", $indent, $this->name);
462 var_export($this->value);
463 }
464 }
465
466 class StructureOfVar extends StructureOf {
467 public $name;
468 public $type;
469 public $desc;
470 public $modifiers;
471 public $defval;
472
473 function formatDefval() {
474 if (strlen($this->defval)) {
475 if (false && defined($this->defval)) {
476 printf(" = ");
477 var_export(constant($this->defval));
478 } else if (strlen($this->defval)) {
479 printf(" = %s", $this->defval);
480 }
481 } elseif ($this->modifiers) {
482 if (stristr($this->modifiers, "optional") !== false) {
483 printf(" = NULL");
484 }
485 }
486 }
487 function formatAsProp($level) {
488 $indent = str_repeat("\t", $level);
489 $this->formatDesc($level,
490 preg_split('/\s+/', $this->modifiers, -1, PREG_SPLIT_NO_EMPTY)
491 + [-1 => "var " . $this->saneType($this->type)]
492 );
493 printf("%s%s %s", $indent, $this->modifiers, $this->name);
494 $this->formatDefval();
495 }
496
497 function formatAsParam($level, $with_type = true) {
498 if ($with_type && strlen($type = $this->saneType($this->type))) {
499 printf("%s ", $type);
500 }
501 printf("%s", $this->name);
502 $this->formatDefval();
503 }
504 }