Skip to content

Commit 4fc765d

Browse files
committed
added PhpReflection::getClassTree()
1 parent 8af006c commit 4fc765d

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/DI/PhpReflection.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,27 @@ public static function isBuiltinType($type)
101101
}
102102

103103

104+
/**
105+
* Returns class and all its descendants.
106+
* @return string[]
107+
*/
108+
public static function getClassTree(\ReflectionClass $class)
109+
{
110+
$getTraits = function ($type) use (& $getTraits) {
111+
return array_reduce(class_uses($type) + class_parents($type), function ($carry, $type) use (& $getTraits) {
112+
return array_merge($carry, $getTraits($type), trait_exists($type) ? [$type] : []);
113+
}, []);
114+
};
115+
$class = $class->getName();
116+
return array_merge(
117+
[$class],
118+
array_values(class_parents($class)),
119+
array_values(class_implements($class)),
120+
$getTraits($class)
121+
);
122+
}
123+
124+
104125
/**
105126
* Expands class name into full name.
106127
* @param string
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\DI\PhpReflection::getClassTree
5+
*/
6+
7+
use Nette\DI\PhpReflection;
8+
use Tester\Assert;
9+
10+
11+
require __DIR__ . '/../bootstrap.php';
12+
13+
14+
trait T1 {
15+
}
16+
17+
trait T2 {
18+
use T1;
19+
}
20+
21+
interface I1 {
22+
}
23+
24+
interface I2 extends I1 {
25+
}
26+
27+
class C1 implements I2
28+
{
29+
use T2;
30+
}
31+
32+
class C2 extends C1
33+
{
34+
}
35+
36+
Assert::same(['I1'], PhpReflection::getClassTree(new ReflectionClass('I1')));
37+
Assert::same(['I2', 'I1'], PhpReflection::getClassTree(new ReflectionClass('I2')));
38+
Assert::same(['T1'], PhpReflection::getClassTree(new ReflectionClass('T1')));
39+
Assert::same(['T2', 'T1'], PhpReflection::getClassTree(new ReflectionClass('T2')));
40+
Assert::same(['C1', 'I2', 'I1', 'T1', 'T2'], PhpReflection::getClassTree(new ReflectionClass('C1')));
41+
Assert::same(['C2', 'C1', 'I1', 'I2', 'T1', 'T2'], PhpReflection::getClassTree(new ReflectionClass('C2')));

0 commit comments

Comments
 (0)