Skip to content

Instantly share code, notes, and snippets.

@joecritch joecritch/README.md
Last active Apr 6, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.