diff --git a/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php b/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php index ba05bb08e4..04f4d67004 100644 --- a/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php +++ b/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php @@ -177,21 +177,62 @@ protected function checkLineLength(File $phpcsFile, array $tokens, int $stackPtr if ($this->absoluteLineLimit > 0 && $lineLength > $this->absoluteLineLimit ) { + $code = 'MaxExceeded'; + if ($this->isNamespacedNameExceedingLength($tokens, $stackPtr, $this->absoluteLineLimit) === true) { + $code = 'NamespacedNameMaxExceeded'; + } + $data = [ $this->absoluteLineLimit, $lineLength, ]; $error = 'Line exceeds maximum limit of %s characters; contains %s characters'; - $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + $phpcsFile->addError($error, $stackPtr, $code, $data); } elseif ($lineLength > $this->lineLimit) { + $code = 'TooLong'; + if ($this->isNamespacedNameExceedingLength($tokens, $stackPtr, $this->lineLimit) === true) { + $code = 'NamespacedNameTooLong'; + } + $data = [ $this->lineLimit, $lineLength, ]; $warning = 'Line exceeds %s characters; contains %s characters'; - $phpcsFile->addWarning($warning, $stackPtr, 'TooLong', $data); + $phpcsFile->addWarning($warning, $stackPtr, $code, $data); } } + + + /** + * Checks if a line is a namespaced name + * + * @param array $tokens The token stack. + * @param int $stackPtr The last token on the line. + * @param int $lineLimit The line limit. + * + * @return bool + */ + private function isNamespacedNameExceedingLength(array $tokens, int $stackPtr, int $lineLimit): bool + { + $line = $tokens[$stackPtr]['line']; + + for ($i = $stackPtr; $tokens[$i]['line'] === $line; $i--) { + $length = ($tokens[$i]['column'] + $tokens[$i]['length'] - 1); + + // Check the line limit of the namespaced name is equal or over the line length. This check accounts for the + // fact that namespaced names are or closed by ; or opened by ( or {. + if ($length >= $lineLimit + && ($tokens[$i]['code'] === T_NAME_QUALIFIED + || $tokens[$i]['code'] === T_NAME_FULLY_QUALIFIED + || $tokens[$i]['code'] === T_NAME_RELATIVE) + ) { + return true; + } + } + + return false; + } } diff --git a/src/Standards/Generic/Tests/Files/LineLengthUnitTest.5.inc b/src/Standards/Generic/Tests/Files/LineLengthUnitTest.5.inc new file mode 100644 index 0000000000..9c72008b63 --- /dev/null +++ b/src/Standards/Generic/Tests/Files/LineLengthUnitTest.5.inc @@ -0,0 +1,45 @@ + 1]; + case 'LineLengthUnitTest.5.inc': + return [ + 10 => 1, + 23 => 1, + 24 => 1, + 25 => 1, + 36 => 1, + 37 => 1, + 44 => 1, + 45 => 1, + ]; default: return []; @@ -103,6 +114,17 @@ public function getWarningList($testFile = '') 10 => 1, 14 => 1, ]; + case 'LineLengthUnitTest.5.inc': + return [ + 7 => 1, + 18 => 1, + 19 => 1, + 20 => 1, + 32 => 1, + 33 => 1, + 40 => 1, + 41 => 1, + ]; default: return [];