diff --git a/core/ClassInfo.php b/core/ClassInfo.php index 54fb52bdf..2f5981e0e 100644 --- a/core/ClassInfo.php +++ b/core/ClassInfo.php @@ -88,25 +88,30 @@ class ClassInfo { return $dataClasses; } - + /** - * Return the root data class for that class. - * This root table has a lot of special use in the DataObject system. - * - * @param mixed $class string of the classname or instance of the class - * @return array + * Returns the root class (the first to extend from DataObject) for the + * passed class. + * + * @param string|object $class + * @return string */ - static function baseDataClass($class) { - global $_ALL_CLASSES; + public static function baseDataClass($class) { if (is_object($class)) $class = get_class($class); - reset($_ALL_CLASSES['parents'][$class]); - while($val = next($_ALL_CLASSES['parents'][$class])) { - if($val == 'DataObject') break; + + if (!self::is_subclass_of($class, 'DataObject')) { + throw new Exception("$class is not a subclass of DataObject"); + } + + while ($next = get_parent_class($class)) { + if ($next == 'DataObject') { + return $class; + } + + $class = $next; } - $baseDataClass = next($_ALL_CLASSES['parents'][$class]); - return $baseDataClass ? $baseDataClass : $class; } - + /** * Returns a list of classes that inherit from the given class. * The resulting array includes the base class passed diff --git a/tests/ClassInfoTest.php b/tests/ClassInfoTest.php index 81ba1dd8f..27e012f39 100644 --- a/tests/ClassInfoTest.php +++ b/tests/ClassInfoTest.php @@ -33,10 +33,22 @@ class ClassInfoTest extends SapphireTest { // 'ClassInfo::classes_for_folder() returns additional classes not matching the filename' // ); } - + + /** + * @covers ClassInfo::baseDataClass() + */ + public function testBaseDataClass() { + $this->assertEquals('ClassInfoTest_BaseClass', ClassInfo::baseDataClass('ClassInfoTest_BaseClass')); + $this->assertEquals('ClassInfoTest_BaseClass', ClassInfo::baseDataClass('ClassInfoTest_ChildClass')); + $this->assertEquals('ClassInfoTest_BaseClass', ClassInfo::baseDataClass('ClassInfoTest_GrandChildClass')); + + $this->setExpectedException('Exception'); + ClassInfo::baseDataClass('DataObject'); + } + } -class ClassInfoTest_BaseClass { +class ClassInfoTest_BaseClass extends DataObject { } @@ -46,5 +58,4 @@ class ClassInfoTest_ChildClass extends ClassInfoTest_BaseClass { class ClassInfoTest_GrandChildClass extends ClassInfoTest_ChildClass { -} -?> \ No newline at end of file +} \ No newline at end of file