MINOR: Refactored ClassInfo::ancestry() to use inbuilt PHP methods rather than the parent manifest.

This commit is contained in:
ajshort 2011-02-19 14:18:26 +11:00
parent 0d03348926
commit eba1a85ead
2 changed files with 43 additions and 12 deletions

View File

@ -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) { public static function ancestry($class, $tablesOnly = false) {
global $_ALL_CLASSES; $ancestry = array();
if(is_object($class)) $class = $class->class; if (is_object($class)) {
else if(!is_string($class)) user_error("Bad class value " . var_export($class, true) . " passed to ClassInfo::ancestry()", E_USER_WARNING); $class = get_class($class);
} elseif (!is_string($class)) {
$items = $_ALL_CLASSES['parents'][$class]; throw new Exception(sprintf(
$items[$class] = $class; 'Invalid class value %s, must be an object or string', var_export($class, true)
if($onlyWithTables) foreach($items as $item) { ));
if(!DataObject::has_own_table($item)) unset($items[$item]);
} }
return $items;
do {
if (!$tablesOnly || DataObject::has_own_table($class)) {
$ancestry[$class] = $class;
}
} while ($class = get_parent_class($class));
return array_reverse($ancestry);
} }
/** /**

View File

@ -46,6 +46,26 @@ class ClassInfoTest extends SapphireTest {
ClassInfo::baseDataClass('DataObject'); 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 { class ClassInfoTest_BaseClass extends DataObject {