From c9b6d1fc322daa76ed80f6cc9463ba45a2cb10e2 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 2 Nov 2022 21:13:06 +0100 Subject: [PATCH] Generic/CharacterBeforePHPOpeningTag: prevent false positive in mixed PHP/HTML files When a file would contain a short open echo tag ` + + diff --git a/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php b/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php index f52180dd35..120eb21684 100644 --- a/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php +++ b/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php @@ -36,7 +36,10 @@ class CharacterBeforePHPOpeningTagSniff implements Sniff */ public function register() { - return [T_OPEN_TAG]; + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; }//end register() @@ -52,10 +55,15 @@ public function register() */ public function process(File $phpcsFile, $stackPtr) { + $tokens = $phpcsFile->getTokens(); + if ($tokens[$stackPtr]['code'] === T_OPEN_TAG_WITH_ECHO) { + // Mixed PHP/HTML file, ignore. + return $phpcsFile->numTokens; + } + $expected = 0; if ($stackPtr > 0) { // Allow a byte-order mark. - $tokens = $phpcsFile->getTokens(); foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { $bomByteLength = (strlen($expectedBomHex) / 2); $htmlBomHex = bin2hex(substr($tokens[0]['content'], 0, $bomByteLength)); diff --git a/src/Standards/Generic/Tests/PHP/CharacterBeforePHPOpeningTagUnitTest.4.inc b/src/Standards/Generic/Tests/PHP/CharacterBeforePHPOpeningTagUnitTest.4.inc new file mode 100644 index 0000000000..185d1c3bd1 --- /dev/null +++ b/src/Standards/Generic/Tests/PHP/CharacterBeforePHPOpeningTagUnitTest.4.inc @@ -0,0 +1,5 @@ +Foo + + + + diff --git a/src/Standards/Generic/Tests/PHP/CharacterBeforePHPOpeningTagUnitTest.5.inc b/src/Standards/Generic/Tests/PHP/CharacterBeforePHPOpeningTagUnitTest.5.inc new file mode 100644 index 0000000000..e387376d6c --- /dev/null +++ b/src/Standards/Generic/Tests/PHP/CharacterBeforePHPOpeningTagUnitTest.5.inc @@ -0,0 +1,4 @@ + + +