mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 12:05:37 +00:00
MINOR: Refactored ClassInfo::ancestry() to use inbuilt PHP methods rather than the parent manifest.
This commit is contained in:
parent
0d03348926
commit
eba1a85ead
@ -148,20 +148,31 @@ class ClassInfo {
|
||||
}
|
||||
|
||||
/**
|
||||
* @todo Improve documentation
|
||||
* Returns the passed class name along with all its parent class names in an
|
||||
* array, sorted with the root class first.
|
||||
*
|
||||
* @param string $class
|
||||
* @param bool $tablesOnly Only return classes that have a table in the db.
|
||||
* @return array
|
||||
*/
|
||||
static function ancestry($class, $onlyWithTables = false) {
|
||||
global $_ALL_CLASSES;
|
||||
public static function ancestry($class, $tablesOnly = false) {
|
||||
$ancestry = array();
|
||||
|
||||
if(is_object($class)) $class = $class->class;
|
||||
else if(!is_string($class)) user_error("Bad class value " . var_export($class, true) . " passed to ClassInfo::ancestry()", E_USER_WARNING);
|
||||
|
||||
$items = $_ALL_CLASSES['parents'][$class];
|
||||
$items[$class] = $class;
|
||||
if($onlyWithTables) foreach($items as $item) {
|
||||
if(!DataObject::has_own_table($item)) unset($items[$item]);
|
||||
if (is_object($class)) {
|
||||
$class = get_class($class);
|
||||
} elseif (!is_string($class)) {
|
||||
throw new Exception(sprintf(
|
||||
'Invalid class value %s, must be an object or string', var_export($class, true)
|
||||
));
|
||||
}
|
||||
return $items;
|
||||
|
||||
do {
|
||||
if (!$tablesOnly || DataObject::has_own_table($class)) {
|
||||
$ancestry[$class] = $class;
|
||||
}
|
||||
} while ($class = get_parent_class($class));
|
||||
|
||||
return array_reverse($ancestry);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -46,6 +46,26 @@ class ClassInfoTest extends SapphireTest {
|
||||
ClassInfo::baseDataClass('DataObject');
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ClassInfo::ancestry()
|
||||
*/
|
||||
public function testAncestry() {
|
||||
$ancestry = ClassInfo::ancestry('SiteTree');
|
||||
$expect = ArrayLib::valuekey(array(
|
||||
'Object',
|
||||
'ViewableData',
|
||||
'DataObject',
|
||||
'SiteTree'
|
||||
));
|
||||
$this->assertEquals($expect, $ancestry);
|
||||
|
||||
$ancestry = ClassInfo::ancestry('SiteTree', true);
|
||||
$this->assertEquals(array('SiteTree' => 'SiteTree'), $ancestry);
|
||||
|
||||
$this->setExpectedException('Exception');
|
||||
ClassInfo::ancestry(42);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class ClassInfoTest_BaseClass extends DataObject {
|
||||
|
Loading…
x
Reference in New Issue
Block a user