Skip to content

[DI] Improve service not found in service subscribers #25261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,21 @@

use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Container;

class AbstractControllerTest extends ControllerTraitTest
{
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
* @expectedExceptionMessage You have requested a non-existent service "unknown". Did you forget to add it to "Symfony\Bundle\FrameworkBundle\Tests\Controller\TestAbstractController::getSubscribedServices()"?
*/
public function testServiceNotFound()
{
$controller = $this->createController();
$controller->setContainer(new Container());
$controller->serviceNotFoundAction();
}

protected function createController()
{
return new TestAbstractController();
Expand Down Expand Up @@ -60,4 +72,9 @@ public function setContainer(ContainerInterface $container)
public function fooAction()
{
}

public function serviceNotFoundAction()
{
$this->get('unknown');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Exception;

use Psr\Container\NotFoundExceptionInterface;
use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;

/**
* This exception is thrown when a non-existent service is requested.
Expand All @@ -34,7 +35,17 @@ public function __construct(string $id, string $sourceId = null, \Exception $pre
$msg = sprintf('The service "%s" has a dependency on a non-existent service "%s".', $sourceId, $id);
}

if ($alternatives) {
$subscriber = null;
foreach (array_reverse(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)) as $trace) {
if (isset($trace['class']) && in_array(ServiceSubscriberInterface::class, class_implements($trace['class']))) {
$subscriber = $trace['class'];
break;
}
}

if (null !== $subscriber) {
$msg .= sprintf(' Did you forget to add it to "%s::getSubscribedServices()"?', $subscriber);
} elseif ($alternatives) {
if (1 == count($alternatives)) {
$msg .= ' Did you mean this: "';
} else {
Expand Down