From 4e1dbe77116fc37aab4e67a5a2631f87d2bab6b4 Mon Sep 17 00:00:00 2001 From: Markus Staab Date: Tue, 14 Jun 2022 11:17:58 +0200 Subject: [PATCH] extracted duplicated REXSTAN_PATHFIX config, windows fixes (#19) --- lib/RexStan.php | 61 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/lib/RexStan.php b/lib/RexStan.php index 5ceb2390e..b5cc04b5c 100644 --- a/lib/RexStan.php +++ b/lib/RexStan.php @@ -2,19 +2,24 @@ final class RexStan { /** - * @return array|string + * @return string */ static public function runFromCli() { - $phpstanBinary = realpath(__DIR__.'/../vendor/bin/phpstan'); - $configPath = realpath(__DIR__.'/../phpstan.neon'); + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + $phpstanBinary = realpath(__DIR__.'/../vendor/bin/phpstan.bat'); + } else { + $phpstanBinary = realpath(__DIR__.'/../vendor/bin/phpstan'); + } + $configPath = realpath(__DIR__.'/../phpstan.neon'); if (rex::getConsole()) { - $cmd = 'REXSTAN_PATHFIX=1 '.$phpstanBinary .' analyse -c '. $configPath; + $pathFix = true; } else { - $cmd = $phpstanBinary .' analyse -c '. $configPath; + $pathFix = false; } - - $output = shell_exec($cmd); + + $cmd = $phpstanBinary .' analyse -c '. $configPath; + $output = self::execCmd($cmd, $pathFix, $lastError); return $output; } @@ -23,18 +28,15 @@ static public function runFromCli() { * @return array|string */ static public function runFromWeb() { - $phpstanBinary = realpath(__DIR__.'/../vendor/bin/phpstan'); + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + $phpstanBinary = realpath(__DIR__.'/../vendor/bin/phpstan.bat'); + } else { + $phpstanBinary = realpath(__DIR__.'/../vendor/bin/phpstan'); + } $configPath = realpath(__DIR__.'/../phpstan.neon'); - $cmd = 'REXSTAN_PATHFIX=1 '. $phpstanBinary .' analyse -c '. $configPath .' --error-format=json --no-progress 2>&1'; - - $lastError = ''; - set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; }); - try { - $output = @shell_exec($cmd); - } finally { - restore_error_handler(); - } + $cmd = $phpstanBinary .' analyse -c '. $configPath .' --error-format=json --no-progress 2>&1'; + $output = self::execCmd($cmd, true, $lastError); if ($output[0] === '{') { // return the analysis result as an array @@ -48,4 +50,29 @@ static public function runFromWeb() { // return the error string as is return $output; } + + /** + * @param string $lastError + * @return string + */ + static private function execCmd(string $cmd, bool $pathFix, &$lastError) { + $lastError = ''; + set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; }); + try { + if ($pathFix) { + // cross os compatible way of setting a env var. + // the var will be inherited by the child process + putenv('REXSTAN_PATHFIX=1'); + } + $output = @shell_exec($cmd); + } finally { + if ($pathFix) { + // remove the env var + putenv('REXSTAN_PATHFIX'); + } + restore_error_handler(); + } + + return $output; + } }