Skip to content

Instantly share code, notes, and snippets.

@gskema
Created April 22, 2020 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gskema/cb64b74b7ae963b572cd28aa24edc754 to your computer and use it in GitHub Desktop.
Save gskema/cb64b74b7ae963b572cd28aa24edc754 to your computer and use it in GitHub Desktop.
Get service ID from Symfony container by object service
<?php
namespace Vrt\UtilsBundle\Service;
use RuntimeException;
use Symfony\Component\DependencyInjection\Container;
// AppKernel::initializeContainer()
// if ('dev' === $this->environment) {
// ContainerServiceId::setContainer($this->container);
// }
/**
* For debugging container service IDs in dev environment.
* Can be used while debugging.
*/
final class ContainerServiceId
{
/** @var Container|null */
private static $container;
public static function setContainer(Container $container): void
{
self::$container = $container;
}
/**
* @param object $object
*
* @return string|null
*/
public static function get($object): ?string
{
if (null === self::$container) {
throw new RuntimeException('ContainerServiceId::get() only works in dev environment');
}
$helper = new class extends Container
{
public function findServiceId(Container $container, $object): ?string
{
foreach ($container->services as $serviceId => $service) {
if ($object === $service) {
return $serviceId;
}
}
return null;
}
};
return $helper->findServiceId(self::$container, $object);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment