Skip to content

Squiz.PHP.EmbeddedPhp false positive when using PHP short open tag #588

Closed
@rodrigoprimo

Description

@rodrigoprimo

Describe the bug

When the short_open_tag ini directive is enabled, the sniff Squiz.PHP.EmbeddedPhp raises a false positive error for code that uses a single-line statement with the short open tag.

Code sample

<? echo 'This is a short open tag'; ?>

To reproduce

Steps to reproduce the behavior:

  1. Enable the short_open_tag ini directive in the PHP configuration file.
  2. Create a file called test.php with the code sample above.
  3. Run phpcs --standard=Squiz --sniffs=Squiz.PHP.EmbeddedPhp test.php
  4. See the error message displayed
FILE: test.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 9 | ERROR | [x] Expected 1 space after opening PHP tag; 2 found
----------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Expected behavior

PHPCS should report no errors.

Versions (please complete the following information)

Operating System Ubuntu 24.04
PHP version 8.3
PHP_CodeSniffer version master
Standard Squiz
Install type git clone

Additional context

The sniff assumes that there is always a space after the PHP open tag that is part of the content of the T_OPEN_TAG token. That is true for the PHP long open tag, but not for the PHP short open tag. When processing a short open tag, the sniff "sees" an extra space that doesn't exist, causing it to report the error, saying that it expected one space but found two.

Here is the code which was added in 3172a21:

// Check that there is one, and only one space at the start of the statement.
$leadingSpace = 0;
if ($tokens[$stackPtr]['code'] === T_OPEN_TAG) {
// The long open tag token in a single line tag set always contains a single space after it.
$leadingSpace = 1;
}

I believe the sniff should be fixed by changing the if condition highlighted above to differentiate between the short open tag and the long open tag when the directive short_open_tag is enabled. This could be done by checking the value of $tokens[$stackPtr]['cotent']. I wonder if there is a better way to do it.

Please confirm

  • I have searched the issue list and am not opening a duplicate issue.
  • I have read the Contribution Guidelines and this is not a support question.
  • I confirm that this bug is a bug in PHP_CodeSniffer and not in one of the external standards.
  • I have verified the issue still exists in the master branch of PHP_CodeSniffer.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions