PHP Syntax Checking with lint and how to do this on a String, not a File

时光怂恿深爱的人放手 提交于 2019-12-05 03:27:29

If you want lint code (not within a file) the only option is to write a wrapper.

Assuming your $HOME/bin precedes /usr/bin, you could install your wrapper in $HOME/bin/php that has a different option for command-line linting. The wrapper would create a temporary file, put the code in there, run /usr/bin/php -l file and then delete the temporary file.

HTH.

You can check code with php -l from STDIN by piping it in. Example:

$ echo "<?php echo 'hello world'" | php -l

Parse error: syntax error, unexpected end of file, expecting ',' or ';' in - on line 2

Errors parsing -

Here the ending semicolon ; is missing after the single quoted string. If you add it, the error goes away and PHP tells you so:

$ echo "<?php echo 'hello world';" | php -l
No syntax errors detected in -

The dash - in Errors parsing - or No syntax errors detected in - stands for STDIN. It's commonly used for that.

Another way is to write the code you want to lint your own (or copy and paste it). This works by using the lint switch with --, entering the code and finishing it by entering Ctrl + D (Linux) / Ctrl + Z (Win) on a line of its own:

$ php -l --
<?php echo "1"
^Z

Parse error: syntax error, unexpected end of file, expecting ',' or ';' in - on line 2

Errors parsing -

BTW, the -r switch which is normally intended to provide code for executing, doesn't work in this case and it gives an error:

$ php -l -r "echo 1"
Either execute direct code, process stdin or use a file.

Most likely because it is intended for running code and thats it for, no linting. Also it is without the opening PHP tag.


From all these options, the first one makes probably most sense if you want to pipe it in (you could also operate with proc_open in case you need more control). Here is a quick example using PHP's exec:

<?php
/**
 * PHP Syntax Checking with lint and how to do this on a string, NOT a FILE
 *
 * @link http://stackoverflow.com/q/12152765/367456
 * @author hakre
 */

$code = "<?php echo 'hello world'";

$result = exec(sprintf('echo %s | php -l', escapeshellarg($code)), $output, $exit);

printf("Parsing the code resulted in; %s\n", $result);

echo "The whole output is:\n";

print_r($output);

The output is as follows:

Parsing the code resulted in; Errors parsing -
The whole output is:
Array
(
    [0] => 
    [1] => Parse error: syntax error, unexpected '"', expecting ',' or ';' in - on line 1
    [2] => Errors parsing -
)

I would suggest checking out phpstan. It is a linter built with PHP, and works a lot like phpunit but for linting code. You can write configs, control linting levels, and include/ignore folders.

It also has proper exit codes.

https://github.com/phpstan/phpstan

If using that isn't possible, I used this script here and it works nicely.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!