Skip to content

Instantly share code, notes, and snippets.

@romaricdrigon
Created September 7, 2016 07:59
Show Gist options
  • Select an option

  • Save romaricdrigon/4b4ca416ea53ad9acb73292a8b81520a to your computer and use it in GitHub Desktop.

Select an option

Save romaricdrigon/4b4ca416ea53ad9acb73292a8b81520a to your computer and use it in GitHub Desktop.
Command to test that all services within a Symfony project build successfully
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
class TestServicesCommand extends ContainerAwareCommand
{
/**
* @var ContainerBuilder|null
*/
private $containerBuilder;
public function configure()
{
$this
->setName('test:services')
->addArgument('prefix', InputArgument::OPTIONAL, 'Check only services with this prefix')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$containerBuilder = $this->getContainerBuilder();
$ids = $containerBuilder->getServiceIds();
if (null !== $prefix = $input->getArgument('prefix')) {
$ids = array_filter($ids, function($id) use ($prefix) {
return 0 === strpos($id, $prefix);
});
}
// We get - and then build - each service from tje container
foreach ($ids as $id) {
try {
$container->get($id);
$output->writeln(sprintf('<info>Able to build %s service!</info>', $id));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Error while building service %s, got "%s"', $id, $e->getMessage()));
}
}
}
/**
* Loads the ContainerBuilder from the cache.
* From Symfony container:debug command
*
* @return ContainerBuilder
*
* @throws \LogicException
*/
protected function getContainerBuilder()
{
if ($this->containerBuilder) {
return $this->containerBuilder;
}
if (!$this->getApplication()->getKernel()->isDebug()) {
throw new \LogicException(sprintf('Debug information about the container is only available in debug mode.'));
}
if (!is_file($cachedFile = $this->getContainer()->getParameter('debug.container.dump'))) {
throw new \LogicException(sprintf('Debug information about the container could not be found. Please clear the cache and try again.'));
}
$container = new ContainerBuilder();
$loader = new XmlFileLoader($container, new FileLocator());
$loader->load($cachedFile);
return $this->containerBuilder = $container;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment