Created
June 28, 2016 17:31
-
-
Save felixcarpena/f582f819f83d55f1d87e935298bc0225 to your computer and use it in GitHub Desktop.
Symfony ConsoleEvents: Create a Listener that add a "--time" global option to all commands and print the start/end time
This file contains 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 | |
//app.console_event_listener: | |
// class: AppBundle\Listener\CommandTimeOptionEventListener | |
// tags: | |
// - { name: kernel.event_listener, event: console.command, method: onConsoleCommand } | |
// - { name: kernel.event_listener, event: console.terminate, method: onConsoleTerminate } | |
namespace AppBundle\Listener; | |
use Symfony\Component\Console\Event\ConsoleCommandEvent; | |
use Symfony\Component\Console\Event\ConsoleTerminateEvent; | |
use Symfony\Component\Console\Input\ArgvInput; | |
use Symfony\Component\Console\Input\InputOption; | |
class CommandTimeOptionEventListener | |
{ | |
/** @var boolean */ | |
private $optionTime; | |
/** | |
* @param ConsoleCommandEvent $event | |
*/ | |
public function onConsoleCommand(ConsoleCommandEvent $event) | |
{ | |
$inputDefinition = $event->getCommand()->getApplication()->getDefinition(); | |
$message = 'To display in stdout the start and finish time take for the command'; | |
$inputDefinition->addOption(new InputOption('time', null, InputOption::VALUE_NONE, $message)); | |
$event->getCommand()->mergeApplicationDefinition(true); | |
$input = $event->getInput(); | |
$input->bind($event->getCommand()->getDefinition()); | |
if ($this->optionTime = $input->getOption('time')) { | |
$name = $event->getCommand()->getName(); | |
$event->getOutput()->writeln( | |
sprintf('<info>[Command: %s] started at: %s</info>', $name, $this->displayTime()) | |
); | |
} | |
} | |
/** | |
* @param ConsoleTerminateEvent $event | |
*/ | |
public function onConsoleTerminate(ConsoleTerminateEvent $event) | |
{ | |
if ($this->optionTime) { | |
$name = $event->getCommand()->getName(); | |
$event->getOutput()->writeln( | |
sprintf('<info>[Command: %s] finished at: %s</info>', $name, $this->displayTime()) | |
); | |
} | |
} | |
/** | |
* @return string | |
*/ | |
private function displayTime() | |
{ | |
return \DateTime::createFromFormat('U.u', microtime(true))->format("Y-m-d H:i:s.u"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment