Skip to content

Instantly share code, notes, and snippets.

@Addvilz
Last active August 30, 2016 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Addvilz/3e566f5a1a5cb769b4ad to your computer and use it in GitHub Desktop.
Save Addvilz/3e566f5a1a5cb769b4ad to your computer and use it in GitHub Desktop.
php-cs-precommit
#!/usr/bin/php
<?php
function progress($i, $total, $label = null, $end=null){
$percent = ceil(($i / $total) * 100);
$barSize = ceil($percent/2);
$blankSize = 50 - $barSize;
if(($blankSize + $barSize) < 50){
$blankSize += (50 - ($blankSize + $barSize));
}
$bar = str_repeat("\033[42m \033[0m",$barSize);
$blank = str_repeat("\033[43m \033[0m",$blankSize);
$percentString = "\033[0;32m".str_pad($percent.'%',5)."\033[0m";
echo "\033[2K".$label.$percentString.$bar.$blank.$end."\r";
}
function parseFiles($lines, $staged = false){
foreach ($lines as $k=>$line) {
$fileName = trim(substr($line, 1));
if (pathinfo($line,PATHINFO_EXTENSION) != "php" && pathinfo($line,PATHINFO_EXTENSION) != "yml") {
unset($lines[$k]);
}
}
$label = ($staged ? 'GIT Staged ' : 'GIT Unstaged').' ';
$total = count($lines);
$i = 1;
foreach ($lines as $file) {
$fileName = trim(substr($file, 1));
progress($i, $total, $label, ' '.$fileName);
/**
* Only PHP file
*/
if (pathinfo($fileName,PATHINFO_EXTENSION) == "php") {
// echo 'Checking '.$fileName.PHP_EOL;
/**
* Check for error
*/
$lint_output = array();
exec("php -l " . escapeshellarg($fileName), $lint_output, $return);
if ($return == 0) {
/**
* PHP-CS-Fixer && add it back
*/
exec("php-cs-fixer fix {$fileName}");
if($staged){
exec("git add {$fileName}");
}
} else {
echo implode("\n", $lint_output), "\n";
}
}
$i++;
}
if($total > 0){
echo PHP_EOL;
}
}
$output = [];
exec('git diff --name-status --diff-filter=ACMR', $output);
parseFiles($output);
$output = [];
exec('git diff --name-status --diff-filter=ACMR --cached', $output);
parseFiles($output, true);
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment