Skip to content

Instantly share code, notes, and snippets.

@thunderer
Created February 13, 2013 01:44
Show Gist options
  • Save thunderer/4837269 to your computer and use it in GitHub Desktop.
Save thunderer/4837269 to your computer and use it in GitHub Desktop.
Custom command registering strategies inside Symfony2 application.
<?php
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Bundle\FrameworkBundle\Console\Shell;
class Application extends BaseApplication
{
private $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
parent::__construct('Symfony', Kernel::VERSION.' - '.$kernel->getName().'/'.$kernel->getEnvironment().($kernel->isDebug() ? '/debug' : ''));
$this->getDefinition()->addOption(new InputOption('--shell', '-s', InputOption::VALUE_NONE, 'Launch the shell.'));
$this->getDefinition()->addOption(new InputOption('--process-isolation', null, InputOption::VALUE_NONE, 'Launch commands from shell as a separate processes.'));
$this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment()));
$this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.'));
$this->getDefinition()->addOption(new InputOption('--strategy', null, InputOption::VALUE_REQUIRED, 'Command registering strategy.'));
}
public function getKernel()
{
return $this->kernel;
}
public function doRun(InputInterface $input, OutputInterface $output)
{
$this->registerCommands($input->getParameterOption('--strategy', 'all'));
if(true === $input->hasParameterOption(array('--shell', '-s')))
{
$shell = new Shell($this);
$shell->setProcessIsolation($input->hasParameterOption(array('--process-isolation')));
$shell->run();
return 0;
}
return parent::doRun($input, $output);
}
protected function registerCommands($strategy)
{
$this->kernel->boot();
if('none' === $strategy)
{
return;
}
foreach($this->kernel->getBundles() as $bundle)
{
if('project' === $strategy && false === strpos($bundle->getPath(), dirname(__DIR__).'/src/'))
{
continue;
}
if($bundle instanceof Bundle)
{
$bundle->registerCommands($this);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment