Add safe application

2.x
Julien Rosset 2 years ago
parent ec84de08fb
commit 218f8b3af0

@ -0,0 +1,75 @@
<?php
namespace jrosset\CliProgram;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
/**
* A “safe” application: runtime exception are treated by {@see SafeApplication::processRuntimeException()}
*/
class SafeApplication extends Application {
/**
* @var int The exit code used when command failed with an exception
*
* @see SafeApplication::processRuntimeException()
*/
private int $exceptionFailureExitCode = Command::FAILURE;
/**
* Runs the current application.
*
* @param InputInterface|null $input The input (i.e. argv)
* @param OutputInterface|null $output The output (i.e. STDOUT and STDERR)
*
* @return int The exit code: 0 if everything went fine, or an error code
*/
public function run (?InputInterface $input = null, ?OutputInterface $output = null): int {
try {
return parent::run($input, $output);
}
catch (Throwable $exception) {
return $this->processRuntimeException($exception, $input, $output);
}
}
/**
* The exit code used when command failed with an exception
*
* @return int The exit code used when command failed with an exception
*/
public function getExceptionFailureExitCode (): int {
return $this->exceptionFailureExitCode;
}
/**
* Set the exit code used when command failed with an exception
*
* @param int $exceptionFailureExitCode The new exit code used when command failed with an exception
*
* @return $this
*/
public function setExceptionFailureExitCode (int $exceptionFailureExitCode): self {
$this->exceptionFailureExitCode = $exceptionFailureExitCode;
return $this;
}
/**
* Process runtime exception
*
* Default behavior: write exception message to <b>$output</b> (error) and return {@see SafeApplication::$exceptionFailureExitCode}
*
* @param Throwable $exception The exception
* @param InputInterface $input The input (i.e. argv)
* @param OutputInterface $output The output (i.e. STDOUT and STDERR)
*
* @return int The exit code
*
* @noinspection PhpUnusedParameterInspection
*/
protected function processRuntimeException (Throwable $exception, InputInterface $input, OutputInterface $output): int {
$output->writeln('<error>' . $exception->getMessage() . '</error>');
return $this->exceptionFailureExitCode;
}
}
Loading…
Cancel
Save