Skip to content

Instantly share code, notes, and snippets.

@adamhut
Forked from ctf0/CommandEventsListener.php
Created January 19, 2018 13:55
Show Gist options
  • Save adamhut/dafe53c3b92a8e74e4d21d6b270c5406 to your computer and use it in GitHub Desktop.
Save adamhut/dafe53c3b92a8e74e4d21d6b270c5406 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Event;
use Closure;
class CommandEventsListener
{
protected $startCallbacks = [];
protected $finishCallbacks = [];
public function __construct($commandName)
{
Event::listen('Illuminate\Console\Events\CommandStarting', function ($event) use ($commandName) {
if ($event->command == $commandName) {
$this->callStartCallbacks();
}
});
Event::listen('Illuminate\Console\Events\CommandFinished', function ($event) use ($commandName) {
if ($event->command == $commandName) {
$this->callFinishCallbacks();
}
});
}
public function onStart(Closure $callback)
{
$this->startCallbacks[] = $callback;
return $this;
}
public function onFinish(Closure $callback)
{
$this->finishCallbacks[] = $callback;
return $this;
}
protected function callStartCallbacks()
{
foreach ($this->startCallbacks as $callback) {
$this->exec($callback);
}
}
protected function callFinishCallbacks()
{
foreach ($this->finishCallbacks as $callback) {
$this->exec($callback);
}
}
protected function exec($callBack)
{
return call_user_func($callBack);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment