From eba1a85ead9a4149d536e67dcf2da4ea5bf9ca67 Mon Sep 17 00:00:00 2001 From: ajshort Date: Sat, 19 Feb 2011 14:18:26 +1100 Subject: [PATCH] MINOR: Refactored ClassInfo::ancestry() to use inbuilt PHP methods rather than the parent manifest. --- core/ClassInfo.php | 33 ++++++++++++++++++++++----------- tests/ClassInfoTest.php | 22 +++++++++++++++++++++- 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/core/ClassInfo.php b/core/ClassInfo.php index 2f5981e0e..3c0a3daa2 100644 --- a/core/ClassInfo.php +++ b/core/ClassInfo.php @@ -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); } /** diff --git a/tests/ClassInfoTest.php b/tests/ClassInfoTest.php index 27e012f39..194bc5757 100644 --- a/tests/ClassInfoTest.php +++ b/tests/ClassInfoTest.php @@ -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 { @@ -58,4 +78,4 @@ class ClassInfoTest_ChildClass extends ClassInfoTest_BaseClass { class ClassInfoTest_GrandChildClass extends ClassInfoTest_ChildClass { -} \ No newline at end of file +}