Skip to content

Commit d7d14a7

Browse files
authored
Merge pull request PHP-DI#862 from 050media/issue-861
Fix wildcard definition global namespace matching any namespace
2 parents 9ea40a5 + 9d5fc52 commit d7d14a7

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/Definition/Source/DefinitionArray.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ public function getDefinition(string $name) : Definition|null
8686
foreach ($this->wildcardDefinitions as $key => $definition) {
8787
// Turn the pattern into a regex
8888
$key = preg_quote($key, '#');
89-
$key = '#' . str_replace('\\' . self::WILDCARD, self::WILDCARD_PATTERN, $key) . '#';
89+
$key = '#^' . str_replace('\\' . self::WILDCARD, self::WILDCARD_PATTERN, $key) . '#';
9090
if (preg_match($key, $name, $matches) === 1) {
9191
array_shift($matches);
9292

tests/UnitTest/Definition/Source/DefinitionArrayTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ public function testWildcards()
180180
'Namespaced\*Interface' => \DI\create('Namespaced\*'),
181181
'Namespaced2\*Interface' => \DI\create('Namespaced2\Foo'),
182182
'Multiple\*\*\Matches' => \DI\create('Multiple\*\*\Implementation'),
183+
'*Interface' => \DI\create('GlobalImplementation'),
183184
]);
184185

185186
$definition = $source->getDefinition('foo1');
@@ -201,6 +202,11 @@ public function testWildcards()
201202
$this->assertInstanceOf(ObjectDefinition::class, $definition);
202203
$this->assertEquals('Multiple\Foo\Bar\Matches', $definition->getName());
203204
$this->assertEquals('Multiple\Foo\Bar\Implementation', $definition->getClassName());
205+
206+
$definition = $source->getDefinition('GlobalInterface');
207+
$this->assertInstanceOf(ObjectDefinition::class, $definition);
208+
$this->assertEquals('GlobalInterface', $definition->getName());
209+
$this->assertEquals('GlobalImplementation', $definition->getClassName());
204210
}
205211

206212
/**
@@ -240,6 +246,17 @@ public function testWildcardShouldNotMatchAcrossNamespaces()
240246
$this->assertNull($source->getDefinition('My\Foo\BarInterface'));
241247
}
242248

249+
/**
250+
* The wildcard for global namespace should not match across namespaces.
251+
*/
252+
public function testGlobalNamespaceWildcardShouldNotMatchAcrossNamespace()
253+
{
254+
$source = new DefinitionArray([
255+
'*Interface' => \DI\create(),
256+
]);
257+
$this->assertNull($source->getDefinition('My\FooInterface'));
258+
}
259+
243260
/**
244261
* @see https://github.com/PHP-DI/PHP-DI/issues/379
245262
*/

0 commit comments

Comments
 (0)