From 5c9931c07aba7410fed30982749c4a0fc54b17b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81d=C3=A1m=20B=C3=A1lint?= Date: Fri, 3 Jun 2022 11:05:51 +0200 Subject: [PATCH 1/2] fix: Build namespace in FactoryCreator with preg_replace to support namespaces which contains class name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ádám Bálint --- src/Tool/FactoryCreator.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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, From c17d8014fba087e6118650a4e522581235c203a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81d=C3=A1m=20B=C3=A1lint?= Date: Fri, 3 Jun 2022 11:08:20 +0200 Subject: [PATCH 2/2] test: Write test for namespace generation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ádám Bálint --- test/Tool/FactoryCreatorTest.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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]); + } + } }