Last active
August 29, 2015 14:11
-
-
Save alexandresalome/da05ff6834526dce84a8 to your computer and use it in GitHub Desktop.
Command example
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 | |
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