| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Symfony package. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier <fabien@symfony.com> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Symfony\Component\Console\Event; |
| 13 |
|
| 14 |
use Symfony\Component\Console\Command\Command; |
| 15 |
use Symfony\Component\Console\Exception\InvalidArgumentException; |
| 16 |
use Symfony\Component\Console\Input\InputInterface; |
| 17 |
use Symfony\Component\Console\Output\OutputInterface; |
| 18 |
|
| 19 |
/** |
| 20 |
* Allows to handle throwables thrown while running a command. |
| 21 |
* |
| 22 |
* @author Wouter de Jong <wouter@wouterj.nl> |
| 23 |
*/ |
| 24 |
final class ConsoleErrorEvent extends ConsoleEvent |
| 25 |
{ |
| 26 |
private $error; |
| 27 |
private $exitCode; |
| 28 |
|
| 29 |
public function __construct(InputInterface $input, OutputInterface $output, $error, Command $command = null) |
| 30 |
{ |
| 31 |
parent::__construct($command, $input, $output); |
| 32 |
|
| 33 |
$this->setError($error); |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Returns the thrown error/exception. |
| 38 |
* |
| 39 |
* @return \Throwable |
| 40 |
*/ |
| 41 |
public function getError() |
| 42 |
{ |
| 43 |
return $this->error; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Replaces the thrown error/exception. |
| 48 |
* |
| 49 |
* @param \Throwable $error |
| 50 |
*/ |
| 51 |
public function setError($error) |
| 52 |
{ |
| 53 |
if (!$error instanceof \Throwable && !$error instanceof \Exception) { |
| 54 |
throw new InvalidArgumentException(sprintf('The error passed to ConsoleErrorEvent must be an instance of \Throwable or \Exception, "%s" was passed instead.', \is_object($error) ? \get_class($error) : \gettype($error))); |
| 55 |
} |
| 56 |
|
| 57 |
$this->error = $error; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Sets the exit code. |
| 62 |
* |
| 63 |
* @param int $exitCode The command exit code |
| 64 |
*/ |
| 65 |
public function setExitCode($exitCode) |
| 66 |
{ |
| 67 |
$this->exitCode = (int) $exitCode; |
| 68 |
|
| 69 |
$r = new \ReflectionProperty($this->error, 'code'); |
| 70 |
$r->setAccessible(true); |
| 71 |
$r->setValue($this->error, $this->exitCode); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Gets the exit code. |
| 76 |
* |
| 77 |
* @return int The command exit code |
| 78 |
*/ |
| 79 |
public function getExitCode() |
| 80 |
{ |
| 81 |
return null !== $this->exitCode ? $this->exitCode : (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1); |
| 82 |
} |
| 83 |
} |
| 84 |
|