Skip to content

Instantly share code, notes, and snippets.

@iArnaud
Forked from phpfunk/pre-commit
Last active August 29, 2015 14:13
Show Gist options
  • Save iArnaud/9b7b7b4c9e3173516a19 to your computer and use it in GitHub Desktop.
Save iArnaud/9b7b7b4c9e3173516a19 to your computer and use it in GitHub Desktop.

This is a very easy way to check your PHP syntax before each commit. Git will call the script before it runs your commit. If there are syntax errors found, they won't be committed and they will be reported.

It will only check files that have one of the extensions listed in the $extensions array. It's a pretty simple script and comes in handy if you are working locally before you push to a remote for testing.

Things to note:

  • You may have to change the #!/usr/bin/php to point to your path for PHP
  • If you don't want to check untracked files, remove the $untracked variable.
  • Place pre-commit file in your .git/hooks folder and chmod +x .git/hooks/pre-commit
#!/usr/bin/php
<?php
// Set empty files array
$files = array();
// Get untracked files
// Get modified files
exec('git ls-files --others --exclude-standard', $untracked);
exec('git diff --cached --diff-filter=ACMRTUX --name-only', $modified);
// Merge em
$files = array_merge($untracked, $modified);
// Set extensions to check
$extensions = array('php', 'tmpl');
// Check their syntax
foreach ($files as $file) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $extensions)) {
$output = array();
exec('php -l ' . escapeshellarg($file), $output, $return);
if ($return == 0) {
continue;
}
echo implode("\n", $output) . "\n";
$status = 1;
}
}
// Set exit status
// 0 = good, 1 = fail
$status = (!isset($status)) ? 0 : 1;
exit($status);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment