Skip to content

Commit

Permalink
extracted duplicated REXSTAN_PATHFIX config, windows fixes (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored Jun 14, 2022
1 parent e4c39d0 commit 4e1dbe7
Showing 1 changed file with 44 additions and 17 deletions.
61 changes: 44 additions & 17 deletions lib/RexStan.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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
Expand All @@ -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;
}
}

0 comments on commit 4e1dbe7

Please sign in to comment.