Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP test for fatal error

Tags:

php

runtime

This is a bit of a long shot, but I figured I'd ask anyway. I have an application that has web-based code editing, like you find on Github, using the ACE editor. The problem is, it is possible to edit code that is within the application itself.

I have managed to detect parse errors before saving the file, which works great, but if the user creates a runtime error, such as MyClass extends NonExistentClass, the file passes the parse check, but saves to the filesystem, killing the application.

Is there anyway to test if the new code will cause a runtime error before I save it to the filesystem? Seems completely counter-intuitive, but I figured I'd ask.

like image 247
UncleCheese Avatar asked Nov 15 '11 19:11

UncleCheese


Video Answer


1 Answers

Possibly use register_shutdown_function to build a JSON object containing information about the fatal error. Then use an AJAX call to test the file; parse the returned value from the call to see if there is an error. (Obviously you could also run the PHP file and parse the JSON object without using AJAX, just thinking about what would be the best from a UX standpoint)

function my_shutdown() {
    $error = error_get_last();
    if( $error['type'] == 1 ) {
        echo json_encode($error);
    }
}
register_shutdown_function('my_shutdown');

Will output something like

{"type":1,"message":"Fatal error message","line":1}

Prepend that to the beginning of the test file, then:

$.post('/test.php', function(data) {
    var json = $.parseJSON(data);
    if( json.type == 1 ) {
        // Don't allow test file to save?
    }
});
like image 155
andrewtweber Avatar answered Oct 21 '22 13:10

andrewtweber