For a quick, dirty, and unsafe solution, you could have node installed on the server, and call PHP's exec() to validate the code.
From the documentation, exec is defined as:
string exec ( string $command [, array &$output [, int &$return_var ]] )
and with node, we can evaluate a JavaScript string by using the -e flag. Example using the command line:
> node -e 'invalid javascript'
SyntaxError: Unexpected identifier
> $?
-bash: 8: command not found # <-- return status!
Tying it together with PHP's exec, you could have something like this:
<? php
$userJavaScript = getUserJavaScriptSomehow();
exec("node -e '" + $userJavaScript + "'", $output, $return_var);
if ($return_var !== 0) {
// something went wrong with parsing it.
}
?>
Note that this is a horrible solution. You're better off validating the JavaScript on the client side and forget doing validation on the server side all together considering the user can execute any arbitrary code. You would have to safeguard against file access, infinite loops, etc.
json_decodeis used to handle data in JSON representation, and your javascript objectboxis not. Either exclude attributeclick, or parsing the javascript code with UglifyJS.php which I got from this question