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

Skip to content

Commit 83a786b

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 83a786b

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 in the global namespace. Leaving out the "class" attribute is only allowed '
55+
.'for namespaced classes. Please specify the class attribute explicitly to get '
56+
.'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 in the global namespace.
11101110
*/
11111111
public function testNoClassFromGlobalNamespaceClassId()
11121112
{

0 commit comments

Comments
 (0)
0