From a10963bcd62286928e0d8a2f5caee92de1eb3354 Mon Sep 17 00:00:00 2001 From: Greg Sherwood Date: Fri, 30 Aug 2019 13:29:40 +1000 Subject: [PATCH] Added check to make sure the file header is the first thing in the file (ref #750) --- package.xml | 1 + .../PSR12/Sniffs/Files/FileHeaderSniff.php | 21 ++++++++++++++++++- .../Tests/Files/FileHeaderUnitTest.5.inc | 18 ++++++++++++++++ .../PSR12/Tests/Files/FileHeaderUnitTest.php | 2 ++ 4 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.5.inc diff --git a/package.xml b/package.xml index 9dd5fc420e..974582f3a3 100644 --- a/package.xml +++ b/package.xml @@ -1155,6 +1155,7 @@ http://pear.php.net/dtd/package-2.0.xsd"> + diff --git a/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php b/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php index d1b0a075bb..c2488f2b80 100644 --- a/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php +++ b/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php @@ -130,6 +130,13 @@ public function process(File $phpcsFile, $stackPtr) $next = $phpcsFile->findNext(T_WHITESPACE, ($next + 1), null, true); } while ($next !== false); + if (count($headerLines) === 1) { + // This is only an open tag and doesn't contain the file header. + // We need to keep checking for one in case they put it further + // down in the file. + return; + } + /* Next, check the spacing and grouping of the statements inside each header block. @@ -213,7 +220,7 @@ public function process(File $phpcsFile, $stackPtr) }//end foreach /* - Finally, check that the order of the header blocks + Next, check that the order of the header blocks is correct: Opening php tag. File-level docblock. @@ -269,6 +276,18 @@ public function process(File $phpcsFile, $stackPtr) }//end if }//end foreach + /* + Finally, make sure this header block is at the very + top of the file. + */ + + if ($stackPtr !== 0) { + $error = 'The file header must be the first content in the file'; + $phpcsFile->addError($error, $stackPtr, 'HeaderPosition'); + } + + return $phpcsFile->numTokens; + }//end process() diff --git a/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.5.inc b/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.5.inc new file mode 100644 index 0000000000..813bc79724 --- /dev/null +++ b/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.5.inc @@ -0,0 +1,18 @@ + + 1, 7 => 1, ]; + case 'FileHeaderUnitTest.5.inc': + return [4 => 1]; default: return []; }//end switch