Last active
October 11, 2015 03:10
-
-
Save lgedeon/81c732c8cc4fb8ae89b7 to your computer and use it in GitHub Desktop.
You can't try/catch a syntax error. You should never have a syntax error. But if you are writing a framework and suggesting that inexperienced users make minor modifications (power to the people!), it would be nice of you to provide a bit of a safety net. Here's how.
This file contains hidden or 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 | |
function helper_syntax_safe_include ( $file, $reset = false ) { | |
$key = sanitize_key( $file ); | |
if ( file_exists( $file) ) { | |
// found it, no more hunting | |
} elseif ( file_exists( trailingslashit( __DIR__ ) . ltrim( $file, '/' ) ) ) { | |
$file = trailingslashit( __DIR__ ) . ltrim( $file, '/' ); | |
} elseif ( file_exists( trailingslashit( get_template_directory() ) . ltrim( $file, '/' ) ) ) { | |
$file = trailingslashit( get_template_directory() ) . ltrim( $file, '/' ); | |
} else { | |
return; | |
} | |
$last_update = filemtime( $file ); | |
$option = (array) get_option( 'helper_syntax_safe_include', array() ); | |
if ( ! isset( $option[$key][1] ) || $option[$key][1] < $last_update || $reset ) { | |
$option[$key] = array( 'failed', $last_update ); | |
update_option( 'helper_syntax_safe_include', $option ); | |
header("Location: index.php"); | |
include_once( $file ); | |
header_remove('Location'); | |
$option[$key][0] = 'success'; | |
update_option( 'helper_syntax_safe_include', $option ); | |
} elseif ( 'success' == $option[$key][0] ) { | |
include_once( $file ); | |
} | |
} | |
helper_syntax_safe_include('test-code.php'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment