Last active
January 26, 2024 00:10
-
-
Save vuon9/be16429f751e12f72e220c18777d9bc7 to your computer and use it in GitHub Desktop.
Custom php-cs-fixer script to make it runnable with stdout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/php | |
<?php | |
// Inspired from https://gist.github.com/Epskampie/427c512722b8e6c4cbf5f1340b87986b | |
// To use this script: | |
// - Change #!/usr/local/bin/php to your PHP binary path | |
// - chmod +x php-cs-fixer-std.php | |
// - Make symlink: ln -s ~/Downloads/php-cs-fixer-std.php /usr/local/bin/php-cs-fixer-std | |
// - Use: php-cs-fixer-std fix --rules=@Symfony src/PhpFile.php | |
// - This supports only one file and --debug flag to see the file content before and after the fix | |
function is_fixer_command(string $a) { | |
return in_array($a, [ | |
"check", | |
"describe", | |
"fix", | |
"help", | |
"list", | |
"list-files", | |
"list-sets", | |
"self-update", | |
]); | |
} | |
$temp_file = tempnam(sys_get_temp_dir(), 'fix_'); | |
$isDebug = false; | |
array_shift($argv); | |
$files = []; | |
$commandFound = false; | |
$commandAndArguments = []; | |
foreach ($argv as $k => $param) { | |
if ($param == "") { | |
continue; | |
} | |
if ($param == "--debug") { | |
$isDebug = true; | |
continue; | |
} | |
if (is_fixer_command($param)) { | |
if (!$commandFound) { | |
$commandFound = true; | |
} | |
$commandAndArguments[] = $param; | |
continue; | |
} | |
if (substr($param, 0, 1) == '-') { | |
$commandAndArguments[] = $param; | |
continue; | |
} | |
$files[] = $param; | |
} | |
if (!$commandFound) { | |
die('No php-cs-fixer command provided\n'); | |
} | |
if (count($files) === 0) { | |
die('No files provided\n'); | |
} | |
if (count($files) > 1) { | |
die('Only one file allowed\n'); | |
} | |
$filePath = $files[0]; | |
if ($isDebug) { | |
echo 'Current dir: ' . $currentDir . PHP_EOL; | |
echo 'Absolute file path: ' . $filePath . PHP_EOL; | |
} | |
@file_put_contents($temp_file, file_get_contents($filePath)); | |
$checkFixerBinaryResult = exec('which php-cs-fixer'); | |
if ($checkFixerBinaryResult === '') { | |
die('php-cs-fixer binary not found in $PATH folders'); | |
} | |
$output = []; | |
$returnCode = 0; | |
$arguments = implode(' ', $commandAndArguments); | |
if ($isDebug) { | |
echo 'Command and arguments: ' . $arguments . PHP_EOL; | |
} | |
$cmd = sprintf('php-cs-fixer %s %s', $arguments, $temp_file); | |
if ($isDebug) { | |
echo 'Forwarded command: ' . $cmd . PHP_EOL; | |
} | |
// Actually run the command | |
exec($cmd, $output, $returnCode); | |
if ($returnCode) { | |
// Error occurred | |
exit($returnCode); | |
} | |
echo file_get_contents($temp_file); | |
unlink($temp_file); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment