From 4056b94f750cb088ca1ddf9f51bf3fe61738baef Mon Sep 17 00:00:00 2001 From: Ingo Schommer Date: Mon, 2 Jan 2012 14:01:16 +0100 Subject: [PATCH] BUGFIX Improved ClassInfo::ancestry() performance through in-memory caching and removal of unnecessary is_object() check - get_class() will complain if its not passed an object already) --- core/ClassInfo.php | 32 ++++++++++++++++++-------------- tests/core/ClassInfoTest.php | 3 --- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/core/ClassInfo.php b/core/ClassInfo.php index f22c8c3e9..8dec66979 100644 --- a/core/ClassInfo.php +++ b/core/ClassInfo.php @@ -26,6 +26,11 @@ class ClassInfo { * Cache for {@link hasTable()} */ private static $_cache_all_tables = null; + + /** + * @var Array Cache for {@link ancestry()}. + */ + private static $_cache_ancestry = array(); /** * @todo Move this to SS_Database or DB @@ -46,6 +51,7 @@ class ClassInfo { static function reset_db_cache() { self::$_cache_all_tables = null; + self::$_cache_ancestry = array(); } /** @@ -143,23 +149,21 @@ class ClassInfo { * @return array */ public static function ancestry($class, $tablesOnly = false) { - $ancestry = array(); + if (!is_string($class)) $class = get_class($class); - if (is_object($class)) { - $class = get_class($class); - } elseif (!is_string($class)) { - throw new InvalidArgumentException(sprintf( - 'Invalid class value %s, must be an object or string', var_export($class, true) - )); + $cacheKey = $class . '_' . (string)$tablesOnly; + $parent = $class; + if(!isset(self::$_cache_ancestry[$cacheKey])) { + $ancestry = array(); + do { + if (!$tablesOnly || DataObject::has_own_table($parent)) { + $ancestry[$parent] = $parent; + } + } while ($parent = get_parent_class($parent)); + self::$_cache_ancestry[$cacheKey] = array_reverse($ancestry); } - do { - if (!$tablesOnly || DataObject::has_own_table($class)) { - $ancestry[$class] = $class; - } - } while ($class = get_parent_class($class)); - - return array_reverse($ancestry); + return self::$_cache_ancestry[$cacheKey]; } /** diff --git a/tests/core/ClassInfoTest.php b/tests/core/ClassInfoTest.php index 619a496c3..9d97bfd4f 100644 --- a/tests/core/ClassInfoTest.php +++ b/tests/core/ClassInfoTest.php @@ -70,9 +70,6 @@ class ClassInfoTest extends SapphireTest { $this->assertEquals(array('ClassInfoTest_BaseClass' => 'ClassInfoTest_BaseClass'), $ancestry, '$tablesOnly option excludes memory-only inheritance classes' ); - - $this->setExpectedException('InvalidArgumentException'); - ClassInfo::ancestry(42); } /**