My pre-commit PHP implementation checks if the modified files in git are "error free" and conform to the PSR2 standard using either "php-code-sniffer" or "php-cs-fixer"
#!/usr/local/bin/php <?php /** * Collect all files which have been added, copied or * modified and store them in an array - output */ exec('git diff --cached --name-only --diff-filter=ACM', $output); $isViolated = 0; $violatedFiles = array(); // $php_cs_path = "/usr/local/bin/php-cs-fixer"; $php_cs_path = "~/.composer/vendor/bin/phpcs"; foreach ($output as $fileName) { // Consider only PHP file for processing if (pathinfo($fileName, PATHINFO_EXTENSION) == "php") { $psr_output = array(); // Put the changes to be made in $psr_output, if not as per PSR2 standard // php-cs-fixer // exec("{$php_cs_path} fix {$fileName} --rules=@PSR2 --dry-run --diff", $psr_output, $return); // php-code-sniffer exec("{$php_cs_path} --standard=PSR2 --colors -n {$fileName}", $psr_output, $return); if ($return != 0) { $isViolated = 1; $violatedFiles[] = $fileName; echo implode("\n", $psr_output), "\n"; } } } if ($isViolated == 1) { echo "\n---------------------------- IMPORTANT --------------------------------\n"; echo "\nPlease use the suggestions above to fix the code in the following file: \n"; echo " => " . implode("\n => ", $violatedFiles); echo "\n-----------------------------------------------------------------------\n\n\n"; exit(1); } else { echo "\n => Committed Successfully :-)\n\n"; exit(0); }
Sudheesh.MS
source share