Chris@14: Chris@14: * Chris@14: * For the full copyright and license information, please view the LICENSE Chris@14: * file that was distributed with this source code. Chris@14: */ Chris@14: Chris@14: namespace Symfony\Component\Console\Event; Chris@14: Chris@14: use Symfony\Component\Console\Command\Command; Chris@14: use Symfony\Component\Console\Exception\InvalidArgumentException; Chris@14: use Symfony\Component\Console\Input\InputInterface; Chris@14: use Symfony\Component\Console\Output\OutputInterface; Chris@14: Chris@14: /** Chris@14: * Allows to handle throwables thrown while running a command. Chris@14: * Chris@14: * @author Wouter de Jong Chris@14: */ Chris@14: final class ConsoleErrorEvent extends ConsoleEvent Chris@14: { Chris@14: private $error; Chris@14: private $exitCode; Chris@14: Chris@14: public function __construct(InputInterface $input, OutputInterface $output, $error, Command $command = null) Chris@14: { Chris@14: parent::__construct($command, $input, $output); Chris@14: Chris@14: $this->setError($error); Chris@14: } Chris@14: Chris@14: /** Chris@14: * Returns the thrown error/exception. Chris@14: * Chris@14: * @return \Throwable Chris@14: */ Chris@14: public function getError() Chris@14: { Chris@14: return $this->error; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Replaces the thrown error/exception. Chris@14: * Chris@14: * @param \Throwable $error Chris@14: */ Chris@14: public function setError($error) Chris@14: { Chris@14: if (!$error instanceof \Throwable && !$error instanceof \Exception) { Chris@17: 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))); Chris@14: } Chris@14: Chris@14: $this->error = $error; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Sets the exit code. Chris@14: * Chris@14: * @param int $exitCode The command exit code Chris@14: */ Chris@14: public function setExitCode($exitCode) Chris@14: { Chris@14: $this->exitCode = (int) $exitCode; Chris@14: Chris@14: $r = new \ReflectionProperty($this->error, 'code'); Chris@14: $r->setAccessible(true); Chris@14: $r->setValue($this->error, $this->exitCode); Chris@14: } Chris@14: Chris@14: /** Chris@14: * Gets the exit code. Chris@14: * Chris@14: * @return int The command exit code Chris@14: */ Chris@14: public function getExitCode() Chris@14: { Chris@17: return null !== $this->exitCode ? $this->exitCode : (\is_int($this->error->getCode()) && 0 !== $this->error->getCode() ? $this->error->getCode() : 1); Chris@14: } Chris@14: }