ProcessLintingResult.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * This file is part of PHP CS Fixer.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace PhpCsFixer\Linter;
  12. use Symfony\Component\Process\Process;
  13. /**
  14. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  15. *
  16. * @internal
  17. */
  18. final class ProcessLintingResult implements LintingResultInterface
  19. {
  20. /**
  21. * @var bool
  22. */
  23. private $isSuccessful;
  24. /**
  25. * @var Process
  26. */
  27. private $process;
  28. /**
  29. * @var null|string
  30. */
  31. private $path;
  32. /**
  33. * @param null|string $path
  34. */
  35. public function __construct(Process $process, $path = null)
  36. {
  37. $this->process = $process;
  38. $this->path = $path;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function check()
  44. {
  45. if (!$this->isSuccessful()) {
  46. // on some systems stderr is used, but on others, it's not
  47. throw new LintingException($this->getProcessErrorMessage(), $this->process->getExitCode());
  48. }
  49. }
  50. private function getProcessErrorMessage()
  51. {
  52. $output = strtok(ltrim($this->process->getErrorOutput() ?: $this->process->getOutput()), "\n");
  53. if (false === $output) {
  54. return 'Fatal error: Unable to lint file.';
  55. }
  56. if (null !== $this->path) {
  57. $needle = sprintf('in %s ', $this->path);
  58. $pos = strrpos($output, $needle);
  59. if (false !== $pos) {
  60. $output = sprintf('%s%s', substr($output, 0, $pos), substr($output, $pos + \strlen($needle)));
  61. }
  62. }
  63. $prefix = substr($output, 0, 18);
  64. if ('PHP Parse error: ' === $prefix) {
  65. return sprintf('Parse error: %s.', substr($output, 18));
  66. }
  67. if ('PHP Fatal error: ' === $prefix) {
  68. return sprintf('Fatal error: %s.', substr($output, 18));
  69. }
  70. return sprintf('%s.', $output);
  71. }
  72. private function isSuccessful()
  73. {
  74. if (null === $this->isSuccessful) {
  75. $this->process->wait();
  76. $this->isSuccessful = $this->process->isSuccessful();
  77. }
  78. return $this->isSuccessful;
  79. }
  80. }