diff --git a/src/Tool/FactoryCreator.php b/src/Tool/FactoryCreator.php index 2e8325e1..ae8f3984 100644 --- a/src/Tool/FactoryCreator.php +++ b/src/Tool/FactoryCreator.php @@ -16,10 +16,10 @@ use function array_shift; use function count; use function implode; +use function preg_replace; use function sort; use function sprintf; use function str_repeat; -use function str_replace; use function strrpos; use function substr; @@ -65,7 +65,7 @@ public function createFactory($className) return sprintf( self::FACTORY_TEMPLATE, - str_replace('\\' . $class, '', $className), + preg_replace('/\\\\' . $class . '$/', '', $className), $this->createImportStatements($className), $class, $class, diff --git a/test/Tool/FactoryCreatorTest.php b/test/Tool/FactoryCreatorTest.php index fecc3e25..2433d356 100644 --- a/test/Tool/FactoryCreatorTest.php +++ b/test/Tool/FactoryCreatorTest.php @@ -6,11 +6,14 @@ use Laminas\ServiceManager\Tool\FactoryCreator; use LaminasTest\ServiceManager\TestAsset\ComplexDependencyObject; +use LaminasTest\ServiceManager\TestAsset\Foo; use LaminasTest\ServiceManager\TestAsset\InvokableObject; use LaminasTest\ServiceManager\TestAsset\SimpleDependencyObject; use PHPUnit\Framework\TestCase; +use function class_alias; use function file_get_contents; +use function preg_match; class FactoryCreatorTest extends TestCase { @@ -47,4 +50,20 @@ public function testCreateFactoryCreatesForComplexDependencies(): void $this->assertEquals($factory, $this->factoryCreator->createFactory($className)); } + + public function testNamespaceGeneration(): void + { + $testClassNames = [ + 'Foo\\Bar\\Service' => 'Foo\\Bar', + 'Foo\\Service\\Bar\\Service' => 'Foo\\Service\\Bar', + ]; + foreach ($testClassNames as $testFqcn => $expectedNamespace) { + class_alias(Foo::class, $testFqcn); + $generatedFactory = $this->factoryCreator->createFactory($testFqcn); + preg_match('/^namespace\s([^;]+)/m', $generatedFactory, $namespaceMatch); + + $this->assertNotEmpty($namespaceMatch); + $this->assertEquals($expectedNamespace, $namespaceMatch[1]); + } + } }