8000 [DependencyInjection] Throw helpful error when shortcutting global cl… · symfony/symfony@b9e7b4f · GitHub
[go: up one dir, main page]

Skip to content

Commit b9e7b4f

Browse files
committed
[DependencyInjection] Throw helpful error when shortcutting global classes
As discussed in #22146 the error message received when trying to use a class in the global namespace as a service without defined class is confusing. Helpful information was added pointing out this current limitation.
1 parent 2dfd136 commit b9e7b4f

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,15 @@ public function process(ContainerBuilder $container)
4848
if ($definition->getFactory()) {
4949
throw new RuntimeException(sprintf('Please add the class to service "%s" even if it is constructed by a factory since we might need to add method calls based on compile-time checks.', $id));
5050
}
51+
if (class_exists($id) || interface_exists($id, false)) {
52+
throw new RuntimeException(sprintf(
53+
'The definition for "%s" has no class attribute, and appears to reference a '
54+
.'class or interface in the global namespace. Leaving out the "class" attribute '
55+
.'is only allowed for namespaced classes. Please specify the class attribute '
56+
.'explicitly to get rid of this error.',
57+
$id
58+
));
59+
}
5160

5261
throw new RuntimeException(sprintf(
5362
'The definition for "%s" has no class. If you intend to inject '

src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1106,7 +1106,7 @@ public function testClassFromId()
11061106

11071107
/**
11081108
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
1109-
* @expectedExceptionMessage The definition for "DateTime" has no class.
1109+
* @expectedExceptionMessage The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.
11101110
*/
11111111
public function testNoClassFromGlobalNamespaceClassId()
11121112
{

0 commit comments

Comments
 (0)
0