Skip to content
GemorrojPublic

About

Check php code syntax

Topics

Resources

Stars

4 stars

Watchers

3 watching

Forks

Repository files navigation

Check php code syntax

Continuous Integration

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

About

Check php code syntax

Topics

Resources

Stars

4 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages