ConsoleErrorEvent.php 2.1 KB

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