stub2ref
[mdref/mdref] / mdref / Inspector.php
1 <?php
2
3 namespace mdref;
4
5 class Inspector {
6 /**
7 * @var array
8 */
9 private $constants = [];
10 /**
11 * @var array
12 */
13 private $classes = [];
14 /**
15 * @var array
16 */
17 private $functions = [];
18
19 public function inspectExtension($ext) {
20 if (!($ext instanceof \ReflectionExtension)) {
21 $ext = new \ReflectionExtension($ext);
22 }
23
24 $this->addClasses($ext->getClasses());
25 $this->addFunctions($ext->getFunctions());
26 $this->addConstants($ext->getConstants());
27 }
28
29 public function inspectNamespace(string $namespace) {
30 $grep = function(array $a) use($namespace) {
31 return preg_grep("/^" . preg_quote($namespace) . "\\\\/", $a);
32 };
33
34 $this->addClasses($this->wrap(\ReflectionClass::class, $grep(get_declared_interfaces())));
35 $this->addClasses($this->wrap(\ReflectionClass::class, array_filter(
36 $grep(get_declared_classes()),
37 fn($cn) => !is_subclass_of($cn, \UnitEnum::class)
38 )));
39 $this->addClasses($this->wrap(\ReflectionEnum::class, array_filter(
40 $grep(get_declared_classes()),
41 fn($cn) => is_subclass_of($cn, \UnitEnum::class)
42 )));
43 $this->addFunctions($this->wrap(\ReflectionFunction::class, $grep(get_defined_functions()["internal"])));
44 $this->addFunctions($this->wrap(\ReflectionFunction::class, $grep(get_defined_functions()["user"])));
45 $this->addConstants($grep(get_defined_constants()));
46 }
47
48 private function wrap(string $klass, array $list) : array {
49 $res = [];
50 foreach ($list as $entry) {
51 $res[] = new $klass($entry);
52 }
53 return $res;
54 }
55
56 private function addClasses(array $classes) {
57 foreach ($classes as $c) {
58 /* @var $c \ReflectionClass */
59 $ns_name = $c->inNamespace() ? $c->getNamespaceName() : "";
60 $this->classes[$ns_name][$c->getShortName()] = $c;
61 }
62 }
63
64 private function addFunctions(array $functions) {
65 foreach ($functions as $f) {
66 /* @var $f \ReflectionFunction */
67 $ns_name = $f->inNamespace() ? $f->getNamespaceName() : "";
68 $this->functions[$ns_name][$f->getShortName()] = $f;
69 }
70 }
71
72 private function addConstants(array $constants) {
73 foreach ($constants as $constant => $value) {
74 $ns_name = ($ns_end = strrpos($constant, "\\")) ? substr($constant, 0, $ns_end++) : "";
75 $cn = substr($constant, $ns_end);
76 $this->constants[$ns_name][$cn] = $value;
77 }
78 }
79
80 /**
81 * @return array
82 */
83 public function getConstants() : array {
84 return $this->constants;
85 }
86
87 /**
88 * @return array
89 */
90 public function getClasses(): array {
91 return $this->classes;
92 }
93
94 /**
95 * @return array
96 */
97 public function getFunctions(): array {
98 return $this->functions;
99 }
100 }