Created
April 22, 2020 07:09
-
-
Save gskema/cb64b74b7ae963b572cd28aa24edc754 to your computer and use it in GitHub Desktop.
Get service ID from Symfony container by object service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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