Skip to content

Instantly share code, notes, and snippets.

@sunel
Forked from phpfunk/pre-commit
Created December 10, 2015 12:00
Show Gist options
  • Save sunel/6aaa3fe6a8cc4bbdbe89 to your computer and use it in GitHub Desktop.
Save sunel/6aaa3fe6a8cc4bbdbe89 to your computer and use it in GitHub Desktop.
PHP Syntax Check on Git Commit

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