Skip to content

Instantly share code, notes, and snippets.

@alexandresalome
Last active August 29, 2015 14:11
Show Gist options
  • Save alexandresalome/da05ff6834526dce84a8 to your computer and use it in GitHub Desktop.
Save alexandresalome/da05ff6834526dce84a8 to your computer and use it in GitHub Desktop.
Command example
<?php
use Symfony\Component\Console\Application;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\EventDispatcher\EventDispatcher;
require_once __DIR__.'/vendor/autoload.php';
$sentences = array(
'en' => 'Hello %s!',
'fr' => 'Bonjour %s!',
'es' => '¡ Hola %s !',
);
$dispatcher = new EventDispatcher();
$dispatcher->addListener(ConsoleEvents::EXCEPTION, function ($e) use ($sentences) {
if (!$e->getOutput()->isVerbose()) {
return;
}
$message = $e->getException()->getMessage().' Available are: '.implode(', ', array_keys($sentences));
$e->setException(new \RuntimeException($message));
});
$app = new Application();
$app->setDispatcher($dispatcher);
$app
->register('hello')
->addArgument('name', InputArgument::IS_ARRAY, '', array('world'))
->addOption('lang', null, InputOption::VALUE_OPTIONAL, '', 'en')
->setCode(function($i, $o) use ($sentences) {
$names = $i->getArgument('name');
$lang = $i->getOption('lang');
if (!isset($sentences[$lang])) {
throw new \RuntimeException(sprintf(
'No message configured for language "%s".',
$lang
));
}
foreach ($names as $name) {
$o->writeln(sprintf($sentences[$lang], $name));
}
})
;
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment