Skip to content

Instantly share code, notes, and snippets.

@finagin
Last active January 21, 2024 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finagin/9f6e0673dd95657023c067665c88be1c to your computer and use it in GitHub Desktop.
Save finagin/9f6e0673dd95657023c067665c88be1c to your computer and use it in GitHub Desktop.
{
"name": "finagin/dryrunnable",
"license": "MIT",
"keywords": ["laravel", "database", "console"],
"authors": [
{
"name": "Igor Finagin",
"email": "Igor@Finag.in"
}
],
"require": {
"php": "^7.0",
"illuminate/console": "*",
"illuminate/database": "*"
},
"autoload": {
"psr-4": {
"Finagin\\Support\\": ""
}
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev"
}
<?php
namespace Finagin\Support;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Database\ConnectionInterface;
use LogicException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @mixin \Illuminate\Console\Command
*/
trait DryRunnableTrait
{
use ConfirmableTrait;
protected function execute(InputInterface $input, OutputInterface $output)
{
if (! $this->hasOption('dry-run')) {
throw new LogicException('Option "dry-run" is not defined in '.static::class.' command signature');
}
return $this->wrap(function () use ($input, $output) {
return parent::execute($input, $output);
});
}
private function wrap(callable $callback, ...$args)
{
$wrapper = $this->option('dry-run')
? function (callable $callback, ...$args) {
$this->alert('Executing in dry run mode');
$this->database()->beginTransaction();
try {
return $callback(...$args) ?: 138;
} finally {
$this->database()->rollBack();
}
}
: function (callable $callback, ...$args) {
if (! $this->confirmToProceed($this->confirmationWarning ?? 'Dangerous operation.', true)) {
return 1;
}
return $callback(...$args);
};
return $wrapper($callback, ...$args);
}
/**
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
private function database(): ConnectionInterface
{
return $this->getLaravel()->make(ConnectionInterface::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment