Skip to content

Instantly share code, notes, and snippets.

@ctf0
Last active December 21, 2020 03:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ctf0/142e1433c10da2e726cd9b4fe49ac3a7 to your computer and use it in GitHub Desktop.
Save ctf0/142e1433c10da2e726cd9b4fe49ac3a7 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Closure;
class CommandEventsListener
{
protected $startCallbacks = [];
protected $finishCallbacks = [];
public function __construct($commandName)
{
app('events')->listen('Illuminate\Console\Events\CommandStarting', function ($event) use ($commandName) {
if ($event->command == $commandName) {
$this->callStartCallbacks();
}
});
app('events')->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);
}
}
@ctf0
Copy link
Author

ctf0 commented Dec 21, 2020

if you want to also check for the command params u can do

$event->input->getParameterOption('migrate:fresh') == '--seed'

so the full condition would be

$cmnd = 'migrate:fresh';

return $event->command == $cmnd && $event->input->getParameterOption($cmnd) == '--seed';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment