Skip to content

Instantly share code, notes, and snippets.

@joecritch
Last active April 6, 2018 11:11
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 joecritch/b7b8eaf49b3b8e52d83850cc376b8cc1 to your computer and use it in GitHub Desktop.
Save joecritch/b7b8eaf49b3b8e52d83850cc376b8cc1 to your computer and use it in GitHub Desktop.
PHP sanity check

PHP Sanity Check

This is a rudimentary script that checks for runtime errors, such as undefined variables in template partials.

{
"scripts": {
"php-sanity": "php php_sanity.php"
}
<?php
// Get an array of all the files you want to check
// (in this case, I'm looking for directories, then appending a "index.php" later)
$dirs = array_filter(glob('public/pages/**'), 'is_dir');
// Set up a custom error handler, so that `$errors` is appending to
// (Bonus: you can use the $errors array in your views too, to display a "create-react-app" style redbox)
$errors = array();
function handle_errors($no, $str, $file, $line) {
global $errors;
if ($no != 2):
$errors[] = array(
'no' => $no,
'str' => $str,
'file' => $file,
'line' => $line,
);
endif;
}
set_error_handler("handle_errors");
// Loop through the templates to check for errors, but prevent rendering the output
foreach($dirs as $dir) {
$file = $dir . '/index.php';
ob_start();
require $file;
$html = ob_get_clean();
}
if (sizeof($errors)) {
echo "errors: " . print_r($errors, true) . "\n";
set_error_handler(NULL);
// Ensure the toolchain errors and exits if there are errors
trigger_error("Errors were found in the templates.", E_USER_ERROR);
} else {
echo "No PHP errors found in templates.\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment