gemorroj / syntax
PHP code syntax checker.
Requires
- php: >=8.2
- symfony/process: ^7.4.8||^8.0.8
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- phpunit/phpunit: ^11.5||^12.5||^13
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Example:
<?php use Syntax\Php; $syntax = new Php(); // uses `php -l` by default $resultCheck = $syntax->check('<?php echo 1; ?>'); print_r($resultCheck); $resultCheckFile = $syntax->checkFile('example.php'); print_r($resultCheckFile);
Checkers
Php accepts a checker via the constructor. CliChecker is used by default:
use Syntax\Checker\CliChecker; use Syntax\Php; $syntax = new Php(new CliChecker('/usr/bin/php')); $resultCheck = $syntax->check('<?php echo 1; ?>'); print_r($resultCheck);
CliChecker accepts an executable path or an argument list:
$syntax = new Php(new CliChecker(['/usr/local/bin/php', '-n']));
The source is passed to php -l via stdin, so no temporary files are created.
Without PHP CLI
If no PHP CLI is available (for example inside a FrankenPHP worker), use the tokenizer checker:
use Syntax\Checker\TokenizerChecker; use Syntax\Php; $syntax = new Php(new TokenizerChecker()); $resultCheck = $syntax->check('<?php echo 1; ?>'); print_r($resultCheck);
This mode catches parse errors but does not perform a full compilation, so compile-time errors such as break outside a loop are not detected.
frankenphp php-cli is not a replacement for a real PHP CLI: on PHP < 8.6 and on Windows it ignores -l and executes the file instead. Use TokenizerChecker in that environment.
Charset
Source and result charsets are constructor arguments:
use Syntax\Php; $syntax = new Php(sourceCharset: 'CP1251', resultCharset: 'UTF-8');
Requirements:
- PHP >= 8.2
- ext-tokenizer — for
TokenizerChecker - proc_open — for
CliChecker
Installation:
composer require gemorroj/syntax