Last active
January 21, 2024 06:24
-
-
Save finagin/9f6e0673dd95657023c067665c88be1c to your computer and use it in GitHub Desktop.
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
{ | |
"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" | |
} |
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 | |
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