diff --git a/Classes/PHPWord/Autoloader.php b/Classes/PHPWord/Autoloader.php index 9bd88596..0e740822 100755 --- a/Classes/PHPWord/Autoloader.php +++ b/Classes/PHPWord/Autoloader.php @@ -31,9 +31,13 @@ if (!defined('PHPWORD_BASE_PATH')) { /** * Class PHPWord_Autoloader + * + * TODO: remove legacy autoloader once everything is moved to namespaces */ class PHPWord_Autoloader { + const PREFIX = 'PHPWord'; + /** * Register the autoloader * @@ -41,7 +45,8 @@ class PHPWord_Autoloader */ public static function register() { - spl_autoload_register(array('PHPWord_Autoloader', 'load')); + spl_autoload_register(array('PHPWord_Autoloader', 'load')); // Legacy + spl_autoload_register(array(new self, 'autoload')); // PSR-4 } /** @@ -60,4 +65,21 @@ class PHPWord_Autoloader return null; } + + /** + * Autoloader + * + * @param string + */ + public static function autoload($class) + { + $prefixLength = strlen(self::PREFIX); + if (0 === strncmp(self::PREFIX, $class, $prefixLength)) { + $file = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, $prefixLength)); + $file = realpath(__DIR__ . (empty($file) ? '' : DIRECTORY_SEPARATOR) . $file . '.php'); + if (file_exists($file)) { + require_once $file; + } + } + } } \ No newline at end of file diff --git a/Tests/PHPWord/AutoloaderTest.php b/Tests/PHPWord/AutoloaderTest.php index 33872466..f24c04e8 100644 --- a/Tests/PHPWord/AutoloaderTest.php +++ b/Tests/PHPWord/AutoloaderTest.php @@ -3,6 +3,7 @@ namespace PHPWord\Tests; use PHPUnit_Framework_TestCase; use PHPWord_Autoloader; +use PHPWord_Autoloader as Autoloader; class AutoloaderTest extends PHPUnit_Framework_TestCase { @@ -10,11 +11,22 @@ class AutoloaderTest extends PHPUnit_Framework_TestCase { PHPWord_Autoloader::register(); $this->assertContains(array('PHPWord_Autoloader', 'load'), spl_autoload_functions()); + $this->assertContains(array('PHPWord_Autoloader', 'autoload'), spl_autoload_functions()); } - public function testAutoload() + public function testAutoloadLegacy() { $this->assertNull(PHPWord_Autoloader::load('Foo'), 'PHPWord_Autoloader::load() is trying to load classes outside of the PHPWord namespace'); $this->assertTrue(PHPWord_Autoloader::load('PHPWord'), 'PHPWord_Autoloader::load() failed to autoload the PHPWord class'); } + + public function testAutoload() + { + $declared = get_declared_classes(); + $declaredCount = count($declared); + Autoloader::autoload('Foo'); + $this->assertEquals($declaredCount, count(get_declared_classes()), 'PHPWord\\Autoloader::autoload() is trying to load classes outside of the PHPWord namespace'); + Autoloader::autoload('PHPWord\\Exceptions\\InvalidStyleException'); // TODO change this class to the main PHPWord class when it is namespaced + $this->assertTrue(in_array('PHPWord\\Exceptions\\InvalidStyleException', get_declared_classes()), 'PHPWord\\Autoloader::autoload() failed to autoload the PHPWord\\Exceptions\\InvalidStyleException class'); + } } \ No newline at end of file