This is a rudimentary script that checks for runtime errors, such as undefined variables in template partials.
Last active
April 6, 2018 11:11
-
-
Save joecritch/b7b8eaf49b3b8e52d83850cc376b8cc1 to your computer and use it in GitHub Desktop.
PHP sanity check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"scripts": { | |
"php-sanity": "php php_sanity.php" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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