diff --git a/src/ClassNameMapper.php b/src/ClassNameMapper.php index 6932aaa..d18c3d8 100644 --- a/src/ClassNameMapper.php +++ b/src/ClassNameMapper.php @@ -90,6 +90,23 @@ public static function createFromComposerFile($composerJsonPath = null, $rootPat return $classNameMapper; } + /** + * @param string|null $composerAutoloadPath + * @return ClassNameMapper + */ + public static function createFromComposerAutoload($composerAutoloadPath = null) + { + $classNameMapper = new ClassNameMapper(); + + if ($composerAutoloadPath === null) { + $composerAutoloadPath = __DIR__ . '/../../../autoload.php'; + } + + $classNameMapper->loadComposerAutoload($composerAutoloadPath); + + return $classNameMapper; + } + /** * * @param string $composerJsonPath Path to the composer file @@ -121,6 +138,7 @@ public function loadComposerFile($composerJsonPath, $rootPath = null, $useAutolo if (isset($composer["autoload"]["psr-4"])) { $psr4 = $composer["autoload"]["psr-4"]; + foreach ($psr4 as $namespace => $paths) { if ($relativePath != null) { if (!is_array($paths)) { @@ -169,6 +187,27 @@ public function loadComposerFile($composerJsonPath, $rootPath = null, $useAutolo return $this; } + /** + * @param string $composerAutoloadPath + * @return self + */ + public function loadComposerAutoload($composerAutoloadPath) + { + if (file_exists($composerAutoloadPath)) { + $loader = require $composerAutoloadPath; + + foreach ($loader->getPrefixes() as $namespace => $paths) { + $this->registerPsr0Namespace($namespace, $paths); + } + + foreach ($loader->getPrefixesPsr4() as $namespace => $paths) { + $this->registerPsr4Namespace($namespace, $paths); + } + } + + return $this; + } + /** * Given an existing path, convert it to a path relative to a given starting path. * Shamelessly borrowed to Symfony :). Thanks guys. @@ -325,4 +364,4 @@ private static function unfactorizeAutoload(array $autoload) { private static function normalizeDirectory($dir) { return $dir === '' ? '' : rtrim($dir, '\\/').'/'; } -} \ No newline at end of file +} diff --git a/tests/ClassNameMapperTest.php b/tests/ClassNameMapperTest.php index d4fd073..aca5a74 100644 --- a/tests/ClassNameMapperTest.php +++ b/tests/ClassNameMapperTest.php @@ -14,6 +14,15 @@ public function testGetPossibleFiles() { $this->assertEquals([ 'src/Foo/Bar.php', 'src2/Bar.php' ], $possibleFiles); + //From autoloader instead of composer.json + $mapper = ClassNameMapper::createFromComposerAutoload(__DIR__ . '/Fixtures/test_autoload.php'); + $possibleFiles = $mapper->getPossibleFileNames('Mouf\\Composer\\ClassNameMapper'); + + $this->assertEquals([ + 'src/ClassNameMapper.php' + ], + $possibleFiles + ); } public function testUseAutoloadDev() { diff --git a/tests/Fixtures/test_autoload.php b/tests/Fixtures/test_autoload.php new file mode 100644 index 0000000..b66f2f0 --- /dev/null +++ b/tests/Fixtures/test_autoload.php @@ -0,0 +1,8 @@ +setPsr4('Mouf\\Composer\\', ['src/']); + +return $classLoader;