Skip to content

Commit

Permalink
added PhpReflection::getClassTree()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed May 23, 2016
1 parent 8af006c commit 4fc765d
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/DI/PhpReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,27 @@ public static function isBuiltinType($type)
}


/**
* Returns class and all its descendants.
* @return string[]
*/
public static function getClassTree(\ReflectionClass $class)
{
$getTraits = function ($type) use (& $getTraits) {
return array_reduce(class_uses($type) + class_parents($type), function ($carry, $type) use (& $getTraits) {
return array_merge($carry, $getTraits($type), trait_exists($type) ? [$type] : []);
}, []);
};
$class = $class->getName();
return array_merge(
[$class],
array_values(class_parents($class)),
array_values(class_implements($class)),
$getTraits($class)
);
}


/**
* Expands class name into full name.
* @param string
Expand Down
41 changes: 41 additions & 0 deletions tests/DI/PhpReflection.getClassTree.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/**
* Test: Nette\DI\PhpReflection::getClassTree
*/

use Nette\DI\PhpReflection;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


trait T1 {
}

trait T2 {
use T1;
}

interface I1 {
}

interface I2 extends I1 {
}

class C1 implements I2
{
use T2;
}

class C2 extends C1
{
}

Assert::same(['I1'], PhpReflection::getClassTree(new ReflectionClass('I1')));
Assert::same(['I2', 'I1'], PhpReflection::getClassTree(new ReflectionClass('I2')));
Assert::same(['T1'], PhpReflection::getClassTree(new ReflectionClass('T1')));
Assert::same(['T2', 'T1'], PhpReflection::getClassTree(new ReflectionClass('T2')));
Assert::same(['C1', 'I2', 'I1', 'T1', 'T2'], PhpReflection::getClassTree(new ReflectionClass('C1')));
Assert::same(['C2', 'C1', 'I1', 'I2', 'T1', 'T2'], PhpReflection::getClassTree(new ReflectionClass('C2')));

0 comments on commit 4fc765d

Please sign in to comment.