From 737280161c22ae9b8fdc2124aa29254dddb1d639 Mon Sep 17 00:00:00 2001 From: Chirayu Chiripal Date: Thu, 26 Feb 2015 03:13:28 +0530 Subject: Update PMAStandard as per PHP_CodeSniffer 2.x Signed-off-by: Chirayu Chiripal --- .../Sniffs/Commenting/ClassCommentSniff.php | 188 ++--- PMAStandard/Sniffs/Commenting/FileCommentSniff.php | 830 ++++++++------------- .../Sniffs/Commenting/FunctionCommentSniff.php | 608 +++++++-------- .../Sniffs/Commenting/InlineCommentSniff.php | 70 -- PMAStandard/Sniffs/Files/LineLengthSniff.php | 169 ----- PMAStandard/ruleset.xml | 9 +- 6 files changed, 598 insertions(+), 1276 deletions(-) delete mode 100644 PMAStandard/Sniffs/Commenting/InlineCommentSniff.php delete mode 100644 PMAStandard/Sniffs/Files/LineLengthSniff.php (limited to 'PMAStandard') diff --git a/PMAStandard/Sniffs/Commenting/ClassCommentSniff.php b/PMAStandard/Sniffs/Commenting/ClassCommentSniff.php index 51481c60b5..c7478f6e98 100644 --- a/PMAStandard/Sniffs/Commenting/ClassCommentSniff.php +++ b/PMAStandard/Sniffs/Commenting/ClassCommentSniff.php @@ -8,42 +8,21 @@ * @package PHP_CodeSniffer * @author Greg Sherwood * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ -if (class_exists('PHP_CodeSniffer_CommentParser_ClassCommentParser', true) === false) { - $error = 'Class PHP_CodeSniffer_CommentParser_ClassCommentParser not found'; - throw new PHP_CodeSniffer_Exception($error); -} - -if (class_exists('PMAStandard_Sniffs_Commenting_FileCommentSniff', true) === false) { - $error = 'Class PMAStandard_Sniffs_Commenting_FileCommentSniff not found'; - throw new PHP_CodeSniffer_Exception($error); -} - /** * Parses and verifies the doc comments for classes. * - * Verifies that : - *
    - *
  • A doc comment exists.
  • - *
  • There is a blank newline after the short description.
  • - *
  • There is a blank newline between the long and short description.
  • - *
  • There is a blank newline between the long description and tags.
  • - *
  • Check the order of the tags.
  • - *
  • Check the indentation of each tag.
  • - *
  • Check required and optional tags and the format of their content.
  • - *
- * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.3.3 + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: 2.2.0 * @link http://pear.php.net/package/PHP_CodeSniffer */ class PMAStandard_Sniffs_Commenting_ClassCommentSniff extends PMAStandard_Sniffs_Commenting_FileCommentSniff @@ -81,123 +60,48 @@ class PMAStandard_Sniffs_Commenting_ClassCommentSniff extends PMAStandard_Sniffs $tokens = $phpcsFile->getTokens(); $type = strtolower($tokens[$stackPtr]['content']); $errorData = array($type); - $find = array( - T_ABSTRACT, - T_WHITESPACE, - T_FINAL, - ); - // Extract the class comment docblock. - $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); + $find = PHP_CodeSniffer_Tokens::$methodPrefixes; + $find[] = T_WHITESPACE; - if ($commentEnd !== false && $tokens[$commentEnd]['code'] === T_COMMENT) { - $error = 'You must use "/**" style comments for a %s comment'; - $phpcsFile->addError($error, $stackPtr, 'WrongStyle', $errorData); - return; - } else if ($commentEnd === false - || $tokens[$commentEnd]['code'] !== T_DOC_COMMENT + $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG + && $tokens[$commentEnd]['code'] !== T_COMMENT ) { - $phpcsFile->addError('Missing %s doc comment', $stackPtr, 'Missing', $errorData); - return; - } - - $commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1); - $commentNext = $phpcsFile->findPrevious(T_WHITESPACE, ($commentEnd + 1), $stackPtr, false, $phpcsFile->eolChar); - - // Distinguish file and class comment. - $prevClassToken = $phpcsFile->findPrevious(T_CLASS, ($stackPtr - 1)); - if ($prevClassToken === false) { - // This is the first class token in this file, need extra checks. - $prevNonComment = $phpcsFile->findPrevious(T_DOC_COMMENT, ($commentStart - 1), null, true); - if ($prevNonComment !== false) { - $prevComment = $phpcsFile->findPrevious(T_DOC_COMMENT, ($prevNonComment - 1)); - if ($prevComment === false) { - // There is only 1 doc comment between open tag and class token. - $newlineToken = $phpcsFile->findNext(T_WHITESPACE, ($commentEnd + 1), $stackPtr, false, $phpcsFile->eolChar); - if ($newlineToken !== false) { - $newlineToken = $phpcsFile->findNext( - T_WHITESPACE, - ($newlineToken + 1), - $stackPtr, - false, - $phpcsFile->eolChar - ); - - if ($newlineToken !== false) { - // Blank line between the class and the doc block. - // The doc block is most likely a file comment. - $error = 'Missing %s doc comment'; - $phpcsFile->addError($error, ($stackPtr + 1), 'Missing', $errorData); - return; - } - }//end if - }//end if - }//end if - }//end if - - $comment = $phpcsFile->getTokensAsString( - $commentStart, - ($commentEnd - $commentStart + 1) - ); - - // Parse the class comment.docblock. - try { - $this->commentParser = new PHP_CodeSniffer_CommentParser_ClassCommentParser($comment, $phpcsFile); - $this->commentParser->parse(); - } catch (PHP_CodeSniffer_CommentParser_ParserException $e) { - $line = ($e->getLineWithinComment() + $commentStart); - $phpcsFile->addError($e->getMessage(), $line, 'FailedParse'); - return; - } - - $comment = $this->commentParser->getComment(); - if (is_null($comment) === true) { - $error = 'Doc comment is empty for %s'; - $phpcsFile->addError($error, $commentStart, 'Empty', $errorData); + $phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing'); + $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'no'); return; + } else { + $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'yes'); } - // No extra newline before short description. - $short = $comment->getShortComment(); - $newlineCount = 0; - $newlineSpan = strspn($short, $phpcsFile->eolChar); - if ($short !== '' && $newlineSpan > 0) { - $error = 'Extra newline(s) found before %s comment short description'; - $phpcsFile->addError($error, ($commentStart + 1), 'SpacingBeforeShort', $errorData); + // Try and determine if this is a file comment instead of a class comment. + // We assume that if this is the first comment after the open PHP tag, then + // it is most likely a file comment instead of a class comment. + if ($tokens[$commentEnd]['code'] === T_DOC_COMMENT_CLOSE_TAG) { + $start = ($tokens[$commentEnd]['comment_opener'] - 1); + } else { + $start = $phpcsFile->findPrevious(T_COMMENT, ($commentEnd - 1), null, true); } - $newlineCount = (substr_count($short, $phpcsFile->eolChar) + 1); - - // Exactly one blank line between short and long description. - $long = $comment->getLongComment(); - if (empty($long) === false) { - $between = $comment->getWhiteSpaceBetween(); - $newlineBetween = substr_count($between, $phpcsFile->eolChar); - if ($newlineBetween !== 2) { - $error = 'There must be exactly one blank line between descriptions in %s comments'; - $phpcsFile->addError($error, ($commentStart + $newlineCount + 1), 'SpacingAfterShort', $errorData); + $prev = $phpcsFile->findPrevious(T_WHITESPACE, $start, null, true); + if ($tokens[$prev]['code'] === T_OPEN_TAG) { + $prevOpen = $phpcsFile->findPrevious(T_OPEN_TAG, ($prev - 1)); + if ($prevOpen === false) { + // This is a comment directly after the first open tag, + // so probably a file comment. + $phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing'); + return; } - - $newlineCount += $newlineBetween; } - // Exactly one blank line before tags. - $tags = $this->commentParser->getTagOrders(); - if (count($tags) > 1) { - $newlineSpan = $comment->getNewlineAfter(); - if ($newlineSpan !== 2) { - $error = 'There must be exactly one blank line before the tags in %s comments'; - if ($long !== '') { - $newlineCount += (substr_count($long, $phpcsFile->eolChar) - $newlineSpan + 1); - } - - $phpcsFile->addError($error, ($commentStart + $newlineCount), 'SpacingBeforeTags', $errorData); - $short = rtrim($short, $phpcsFile->eolChar.' '); - } + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a class comment', $stackPtr, 'WrongStyle'); + return; } // Check each tag. - $this->processTags($commentStart, $commentEnd); + $this->processTags($phpcsFile, $stackPtr, $tokens[$commentEnd]['comment_opener']); }//end process() @@ -205,23 +109,25 @@ class PMAStandard_Sniffs_Commenting_ClassCommentSniff extends PMAStandard_Sniffs /** * Process the version tag. * - * @param int $errorPos The line number where the error occurs. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processVersion($errorPos) + protected function processVersion(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $version = $this->commentParser->getVersion(); - if ($version !== null) { - $content = $version->getContent(); - $matches = array(); - if (empty($content) === true) { - $error = 'Content missing for @version tag in doc comment'; - $this->currentFile->addError($error, $errorPos, 'EmptyVersion'); - } else if ((strstr($content, 'Release:') === false)) { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if ((strstr($content, 'Release:') === false)) { $error = 'Invalid version "%s" in doc comment; consider "Release: " instead'; $data = array($content); - $this->currentFile->addWarning($error, $errorPos, 'InvalidVersion', $data); + $phpcsFile->addWarning($error, $tag, 'InvalidVersion', $data); } } @@ -229,5 +135,3 @@ class PMAStandard_Sniffs_Commenting_ClassCommentSniff extends PMAStandard_Sniffs }//end class - -?> diff --git a/PMAStandard/Sniffs/Commenting/FileCommentSniff.php b/PMAStandard/Sniffs/Commenting/FileCommentSniff.php index fcca9928bd..19872af4c2 100644 --- a/PMAStandard/Sniffs/Commenting/FileCommentSniff.php +++ b/PMAStandard/Sniffs/Commenting/FileCommentSniff.php @@ -8,118 +8,78 @@ * @package PHP_CodeSniffer * @author Greg Sherwood * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ -if (class_exists('PHP_CodeSniffer_CommentParser_ClassCommentParser', true) === false) { - throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_CommentParser_ClassCommentParser not found'); -} - /** * Parses and verifies the doc comments for files. * - * Verifies that : - *
    - *
  • A doc comment exists.
  • - *
  • There is a blank newline after the short description.
  • - *
  • There is a blank newline between the long and short description.
  • - *
  • There is a blank newline between the long description and tags.
  • - *
  • Check the order of the tags.
  • - *
  • Check the indentation of each tag.
  • - *
  • Check required and optional tags and the format of their content.
  • - *
- * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.3.3 + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: 2.2.0 * @link http://pear.php.net/package/PHP_CodeSniffer */ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_Sniff { - /** - * The header comment parser for the current file. - * - * @var PHP_CodeSniffer_Comment_Parser_ClassCommentParser - */ - protected $commentParser = null; - - /** - * The current PHP_CodeSniffer_File object we are processing. - * - * @var PHP_CodeSniffer_File - */ - protected $currentFile = null; - /** * Tags in correct order and related info. * * @var array */ protected $tags = array( - 'category' => array( - 'required' => false, - 'allow_multiple' => false, - 'order_text' => 'precedes @package', - ), - 'package' => array( - 'required' => true, - 'allow_multiple' => false, - 'order_text' => 'follows @category', - ), - 'subpackage' => array( - 'required' => false, - 'allow_multiple' => false, - 'order_text' => 'follows @package', - ), - 'author' => array( - 'required' => false, - 'allow_multiple' => true, - 'order_text' => 'follows @subpackage (if used) or @package', - ), - 'copyright' => array( - 'required' => false, - 'allow_multiple' => true, - 'order_text' => 'follows @author', - ), - 'license' => array( - 'required' => false, - 'allow_multiple' => false, - 'order_text' => 'follows @copyright (if used) or @author', - ), - 'version' => array( - 'required' => false, - 'allow_multiple' => false, - 'order_text' => 'follows @license', - ), - 'link' => array( - 'required' => false, - 'allow_multiple' => true, - 'order_text' => 'follows @version', - ), - 'see' => array( - 'required' => false, - 'allow_multiple' => true, - 'order_text' => 'follows @link', - ), - 'since' => array( - 'required' => false, - 'allow_multiple' => false, - 'order_text' => 'follows @see (if used) or @link', - ), - 'deprecated' => array( - 'required' => false, - 'allow_multiple' => false, - 'order_text' => 'follows @since (if used) or @see (if used) or @link', - ), - ); + '@category' => array( + 'required' => false, + 'allow_multiple' => false, + ), + '@package' => array( + 'required' => true, + 'allow_multiple' => false, + ), + '@subpackage' => array( + 'required' => false, + 'allow_multiple' => false, + ), + '@author' => array( + 'required' => false, + 'allow_multiple' => true, + ), + '@copyright' => array( + 'required' => false, + 'allow_multiple' => true, + ), + '@license' => array( + 'required' => false, + 'allow_multiple' => false, + ), + '@version' => array( + 'required' => false, + 'allow_multiple' => false, + ), + '@link' => array( + 'required' => false, + 'allow_multiple' => true, + ), + '@see' => array( + 'required' => false, + 'allow_multiple' => true, + ), + '@since' => array( + 'required' => false, + 'allow_multiple' => false, + ), + '@deprecated' => array( + 'required' => false, + 'allow_multiple' => false, + ), + ); /** @@ -141,30 +101,19 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ * @param int $stackPtr The position of the current token * in the stack passed in $tokens. * - * @return void + * @return int */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { - $this->currentFile = $phpcsFile; - - // We are only interested if this is the first open tag. - if ($stackPtr !== 0) { - if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) { - return; - } - } - $tokens = $phpcsFile->getTokens(); // Find the next non whitespace token. - $commentStart - = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); // Allow declare() statements at the top of the file. if ($tokens[$commentStart]['code'] === T_DECLARE) { - $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($commentStart + 1)); - $commentStart - = $phpcsFile->findNext(T_WHITESPACE, ($semicolon + 1), null, true); + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($commentStart + 1)); + $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($semicolon + 1), null, true); } // Ignore vim header. @@ -186,133 +135,27 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ if ($tokens[$commentStart]['code'] === T_CLOSE_TAG) { // We are only interested if this is the first open tag. - return; + return ($phpcsFile->numTokens + 1); } else if ($tokens[$commentStart]['code'] === T_COMMENT) { $error = 'You must use "/**" style comments for a file comment'; $phpcsFile->addError($error, $errorToken, 'WrongStyle'); - return; + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); + return ($phpcsFile->numTokens + 1); } else if ($commentStart === false - || $tokens[$commentStart]['code'] !== T_DOC_COMMENT + || $tokens[$commentStart]['code'] !== T_DOC_COMMENT_OPEN_TAG ) { $phpcsFile->addError('Missing file doc comment', $errorToken, 'Missing'); - return; + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'no'); + return ($phpcsFile->numTokens + 1); } else { + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); + } - // Extract the header comment docblock. - $commentEnd = $phpcsFile->findNext( - T_DOC_COMMENT, - ($commentStart + 1), - null, - true - ); - - $commentEnd--; - - // Check if there is only 1 doc comment between the - // open tag and class token. - $nextToken = array( - T_ABSTRACT, - T_CLASS, - T_FUNCTION, - T_DOC_COMMENT, - ); - - $commentNext = $phpcsFile->findNext($nextToken, ($commentEnd + 1)); - if ($commentNext !== false - && $tokens[$commentNext]['code'] !== T_DOC_COMMENT - ) { - // Found a class token right after comment doc block. - $newlineToken = $phpcsFile->findNext( - T_WHITESPACE, - ($commentEnd + 1), - $commentNext, - false, - $phpcsFile->eolChar - ); - - if ($newlineToken !== false) { - $newlineToken = $phpcsFile->findNext( - T_WHITESPACE, - ($newlineToken + 1), - $commentNext, - false, - $phpcsFile->eolChar - ); - - if ($newlineToken === false) { - // No blank line between the class token and the doc block. - // The doc block is most likely a class comment. - $error = 'Missing file doc comment'; - $phpcsFile->addError($error, $errorToken, 'Missing'); - return; - } - } - }//end if - - $comment = $phpcsFile->getTokensAsString( - $commentStart, - ($commentEnd - $commentStart + 1) - ); - - // Parse the header comment docblock. - try { - $this->commentParser = new PHP_CodeSniffer_CommentParser_ClassCommentParser($comment, $phpcsFile); - $this->commentParser->parse(); - } catch (PHP_CodeSniffer_CommentParser_ParserException $e) { - $line = ($e->getLineWithinComment() + $commentStart); - $phpcsFile->addError($e->getMessage(), $line, 'FailedParse'); - return; - } - - $comment = $this->commentParser->getComment(); - if (is_null($comment) === true) { - $error = 'File doc comment is empty'; - $phpcsFile->addError($error, $commentStart, 'Empty'); - return; - } - - // No extra newline before short description. - $short = $comment->getShortComment(); - $newlineCount = 0; - $newlineSpan = strspn($short, $phpcsFile->eolChar); - if ($short !== '' && $newlineSpan > 0) { - $error = 'Extra newline(s) found before file comment short description'; - $phpcsFile->addError($error, ($commentStart + 1), 'SpacingBefore'); - } - - $newlineCount = (substr_count($short, $phpcsFile->eolChar) + 1); - - // Exactly one blank line between short and long description. - $long = $comment->getLongComment(); - if (empty($long) === false) { - $between = $comment->getWhiteSpaceBetween(); - $newlineBetween = substr_count($between, $phpcsFile->eolChar); - if ($newlineBetween !== 2) { - $error = 'There must be exactly one blank line between descriptions in file comment'; - $phpcsFile->addError($error, ($commentStart + $newlineCount + 1), 'DescriptionSpacing'); - } - - $newlineCount += $newlineBetween; - } - - // Exactly one blank line before tags. - $tags = $this->commentParser->getTagOrders(); - if (count($tags) > 1) { - $newlineSpan = $comment->getNewlineAfter(); - if ($newlineSpan !== 2) { - $error = 'There must be exactly one blank line before the tags in file comment'; - if ($long !== '') { - $newlineCount += (substr_count($long, $phpcsFile->eolChar) - $newlineSpan + 1); - } - - $phpcsFile->addError($error, ($commentStart + $newlineCount), 'SpacingBeforeTags'); - $short = rtrim($short, $phpcsFile->eolChar.' '); - } - } + // Check each tag. + $this->processTags($phpcsFile, $stackPtr, $commentStart); - // Check each tag. - $this->processTags($commentStart, $commentEnd); - }//end if + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); }//end process() @@ -320,233 +163,140 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ /** * Processes each required or optional tag. * - * @param int $commentStart Position in the stack where the comment started. - * @param int $commentEnd Position in the stack where the comment ended. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart Position in the stack where the comment started. * * @return void */ - protected function processTags($commentStart, $commentEnd) + protected function processTags(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart) { - $docBlock = (get_class($this) === 'PMAStandard_Sniffs_Commenting_FileCommentSniff') ? 'file' : 'class'; - $foundTags = $this->commentParser->getTagOrders(); - $orderIndex = 0; - $indentation = array(); - $longestTag = 0; - $errorPos = 0; - - foreach ($this->tags as $tag => $info) { - - // Required tag missing. - if ($info['required'] === true && in_array($tag, $foundTags) === false) { - $error = 'Missing @%s tag in %s comment'; - $data = array( - $tag, - $docBlock, - ); - $this->currentFile->addError($error, $commentEnd, 'MissingTag', $data); - continue; - } + $tokens = $phpcsFile->getTokens(); - // Get the line number for current tag. - $tagName = ucfirst($tag); - if ($info['allow_multiple'] === true) { - $tagName .= 's'; - } + if (get_class($this) === 'PMAStandard_Sniffs_Commenting_FileCommentSniff') { + $docBlock = 'file'; + } else { + $docBlock = 'class'; + } - $getMethod = 'get'.$tagName; - $tagElement = $this->commentParser->$getMethod(); - if (is_null($tagElement) === true || empty($tagElement) === true) { + $commentEnd = $tokens[$commentStart]['comment_closer']; + + $foundTags = array(); + $tagTokens = array(); + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + $name = $tokens[$tag]['content']; + if (isset($this->tags[$name]) === false) { continue; } - $errorPos = $commentStart; - if (is_array($tagElement) === false) { - $errorPos = ($commentStart + $tagElement->getLine()); + if ($this->tags[$name]['allow_multiple'] === false && isset($tagTokens[$name]) === true) { + $error = 'Only one %s tag is allowed in a %s comment'; + $data = array( + $name, + $docBlock, + ); + $phpcsFile->addError($error, $tag, 'Duplicate'.ucfirst($name).'Tag', $data); } - // Get the tag order. - $foundIndexes = array_keys($foundTags, $tag); + $foundTags[] = $name; + $tagTokens[$name][] = $tag; + + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) { + $error = 'Content missing for %s tag in %s comment'; + $data = array( + $name, + $docBlock, + ); + $phpcsFile->addError($error, $tag, 'Empty'.ucfirst($name).'Tag', $data); + continue; + } + }//end foreach - if (count($foundIndexes) > 1) { - // Multiple occurance not allowed. - if ($info['allow_multiple'] === false) { - $error = 'Only 1 @%s tag is allowed in a %s comment'; + // Check if the tags are in the correct position. + $pos = 0; + foreach ($this->tags as $tag => $tagData) { + if (isset($tagTokens[$tag]) === false) { + if ($tagData['required'] === true) { + $error = 'Missing %s tag in %s comment'; $data = array( $tag, $docBlock, ); - $this->currentFile->addError($error, $errorPos, 'DuplicateTag', $data); - } else { - // Make sure same tags are grouped together. - $i = 0; - $count = $foundIndexes[0]; - foreach ($foundIndexes as $index) { - if ($index !== $count) { - $errorPosIndex - = ($errorPos + $tagElement[$i]->getLine()); - $error = '@%s tags must be grouped together'; - $data = array($tag); - $this->currentFile->addError($error, $errorPosIndex, 'TagsNotGrouped', $data); - } - - $i++; - $count++; - } + $phpcsFile->addError($error, $commentEnd, 'Missing'.ucfirst(substr($tag, 1)).'Tag', $data); } - }//end if - // Check tag order. - if ($foundIndexes[0] > $orderIndex) { - $orderIndex = $foundIndexes[0]; + continue; } else { - if (is_array($tagElement) === true && empty($tagElement) === false) { - $errorPos += $tagElement[0]->getLine(); + $method = 'process'.substr($tag, 1); + if (method_exists($this, $method) === true) { + // Process each tag if a method is defined. + call_user_func(array($this, $method), $phpcsFile, $tagTokens[$tag]); } - - $error = 'The @%s tag is in the wrong order; the tag %s'; - $data = array( - $tag, - $info['order_text'], - ); - $this->currentFile->addError($error, $errorPos, 'WrongTagOrder', $data); } - // Store the indentation for checking. - $len = strlen($tag); - if ($len > $longestTag) { - $longestTag = $len; + if (isset($foundTags[$pos]) === false) { + break; } - if (is_array($tagElement) === true) { - foreach ($tagElement as $key => $element) { - $indentation[] = array( - 'tag' => $tag, - 'space' => $this->getIndentation($tag, $element), - 'line' => $element->getLine(), - ); - } - } else { - $indentation[] = array( - 'tag' => $tag, - 'space' => $this->getIndentation($tag, $tagElement), - ); + if ($foundTags[$pos] !== $tag) { + $error = 'The tag in position %s should be the %s tag'; + $data = array( + ($pos + 1), + $tag, + ); + $phpcsFile->addError($error, $tokens[$commentStart]['comment_tags'][$pos], ucfirst($tag).'TagOrder', $data); } - $method = 'process'.$tagName; - if (method_exists($this, $method) === true) { - // Process each tag if a method is defined. - call_user_func(array($this, $method), $errorPos); - } else { - if (is_array($tagElement) === true) { - foreach ($tagElement as $key => $element) { - $element->process( - $this->currentFile, - $commentStart, - $docBlock - ); - } - } else { - $tagElement->process( - $this->currentFile, - $commentStart, - $docBlock - ); - } + // Account for multiple tags. + $pos++; + while (isset($foundTags[$pos]) === true && $foundTags[$pos] === $tag) { + $pos++; } }//end foreach - foreach ($indentation as $indentInfo) { - if ($indentInfo['space'] !== 0 - && $indentInfo['space'] !== ($longestTag + 1) - ) { - $expected = (($longestTag - strlen($indentInfo['tag'])) + 1); - $space = ($indentInfo['space'] - strlen($indentInfo['tag'])); - $error = '@%s tag comment indented incorrectly; expected %s spaces but found %s'; - $data = array( - $indentInfo['tag'], - $expected, - $space, - ); - - $getTagMethod = 'get'.ucfirst($indentInfo['tag']); - - if ($this->tags[$indentInfo['tag']]['allow_multiple'] === true) { - $line = $indentInfo['line']; - } else { - $tagElem = $this->commentParser->$getTagMethod(); - $line = $tagElem->getLine(); - } - - $this->currentFile->addError($error, ($commentStart + $line), 'TagIndent', $data); - } - } - }//end processTags() - /** - * Get the indentation information of each tag. - * - * @param string $tagName The name of the - * doc comment - * element. - * @param PHP_CodeSniffer_CommentParser_DocElement $tagElement The doc comment - * element. - * - * @return string|int - */ - protected function getIndentation($tagName, $tagElement) - { - if ($tagElement instanceof PHP_CodeSniffer_CommentParser_SingleElement) { - if ($tagElement->getContent() !== '') { - return (strlen($tagName) + substr_count($tagElement->getWhitespaceBeforeContent(), ' ')); - } - } else if ($tagElement instanceof PHP_CodeSniffer_CommentParser_PairElement) { - if ($tagElement->getValue() !== '') { - return (strlen($tagName) + substr_count($tagElement->getWhitespaceBeforeValue(), ' ')); - } - } - - return 0; - - }//end getIndentation() - - /** * Process the category tag. * - * @param int $errorPos The line number where the error occurs. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processCategory($errorPos) + protected function processCategory(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $category = $this->commentParser->getCategory(); - if ($category !== null) { - $content = $category->getContent(); - if ($content !== '') { - if (PHP_CodeSniffer::isUnderscoreName($content) !== true) { - $newContent = str_replace(' ', '_', $content); - $nameBits = explode('_', $newContent); - $firstBit = array_shift($nameBits); - $newName = ucfirst($firstBit).'_'; - foreach ($nameBits as $bit) { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if (PHP_CodeSniffer::isUnderscoreName($content) !== true) { + $newContent = str_replace(' ', '_', $content); + $nameBits = explode('_', $newContent); + $firstBit = array_shift($nameBits); + $newName = ucfirst($firstBit).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { $newName .= ucfirst($bit).'_'; } - - $error = 'Category name "%s" is not valid; consider "%s" instead'; - $validName = trim($newName, '_'); - $data = array( - $content, - $validName, - ); - $this->currentFile->addError($error, $errorPos, 'InvalidCategory', $data); } - } else { - $error = '@category tag must contain a name'; - $this->currentFile->addError($error, $errorPos, 'EmptyCategory'); + + $error = 'Category name "%s" is not valid; consider "%s" instead'; + $validName = trim($newName, '_'); + $data = array( + $content, + $validName, + ); + $phpcsFile->addError($error, $tag, 'InvalidCategory', $data); } - } + }//end foreach }//end processCategory() @@ -554,38 +304,45 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ /** * Process the package tag. * - * @param int $errorPos The line number where the error occurs. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processPackage($errorPos) + protected function processPackage(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $package = $this->commentParser->getPackage(); - if ($package !== null) { - $content = $package->getContent(); - if ($content !== '') { - if (PHP_CodeSniffer::isUnderscoreName($content) !== true) { - $newContent = str_replace(' ', '_', $content); - $nameBits = explode('_', $newContent); - $firstBit = array_shift($nameBits); - $newName = strtoupper($firstBit{0}).substr($firstBit, 1).'_'; - foreach ($nameBits as $bit) { - $newName .= strtoupper($bit{0}).substr($bit, 1).'_'; - } + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } - $error = 'Package name "%s" is not valid; consider "%s" instead'; - $validName = trim($newName, '_'); - $data = array( - $content, - $validName, - ); - $this->currentFile->addError($error, $errorPos, 'InvalidPackage', $data); + $content = $tokens[($tag + 2)]['content']; + if (PHP_CodeSniffer::isUnderscoreName($content) === true) { + continue; + } + + $newContent = str_replace(' ', '_', $content); + $newContent = trim($newContent, '_'); + $newContent = preg_replace('/[^A-Za-z_]/', '', $newContent); + $nameBits = explode('_', $newContent); + $firstBit = array_shift($nameBits); + $newName = strtoupper($firstBit{0}).substr($firstBit, 1).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { + $newName .= strtoupper($bit{0}).substr($bit, 1).'_'; } - } else { - $error = '@package tag must contain a name'; - $this->currentFile->addError($error, $errorPos, 'EmptyPackage'); } - } + + $error = 'Package name "%s" is not valid; consider "%s" instead'; + $validName = trim($newName, '_'); + $data = array( + $content, + $validName, + ); + $phpcsFile->addError($error, $tag, 'InvalidPackage', $data); + }//end foreach }//end processPackage() @@ -593,38 +350,43 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ /** * Process the subpackage tag. * - * @param int $errorPos The line number where the error occurs. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processSubpackage($errorPos) + protected function processSubpackage(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $package = $this->commentParser->getSubpackage(); - if ($package !== null) { - $content = $package->getContent(); - if ($content !== '') { - if (PHP_CodeSniffer::isUnderscoreName($content) !== true) { - $newContent = str_replace(' ', '_', $content); - $nameBits = explode('_', $newContent); - $firstBit = array_shift($nameBits); - $newName = strtoupper($firstBit{0}).substr($firstBit, 1).'_'; - foreach ($nameBits as $bit) { - $newName .= strtoupper($bit{0}).substr($bit, 1).'_'; - } + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } - $error = 'Subpackage name "%s" is not valid; consider "%s" instead'; - $validName = trim($newName, '_'); - $data = array( - $content, - $validName, - ); - $this->currentFile->addError($error, $errorPos, 'InvalidSubpackage', $data); + $content = $tokens[($tag + 2)]['content']; + if (PHP_CodeSniffer::isUnderscoreName($content) === true) { + continue; + } + + $newContent = str_replace(' ', '_', $content); + $nameBits = explode('_', $newContent); + $firstBit = array_shift($nameBits); + $newName = strtoupper($firstBit{0}).substr($firstBit, 1).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { + $newName .= strtoupper($bit{0}).substr($bit, 1).'_'; } - } else { - $error = '@subpackage tag must contain a name'; - $this->currentFile->addError($error, $errorPos, 'EmptySubpackage'); } - } + + $error = 'Subpackage name "%s" is not valid; consider "%s" instead'; + $validName = trim($newName, '_'); + $data = array( + $content, + $validName, + ); + $phpcsFile->addError($error, $tag, 'InvalidSubpackage', $data); + }//end foreach }//end processSubpackage() @@ -632,102 +394,97 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ /** * Process the author tag(s) that this header comment has. * - * This function is different from other _process functions - * as $authors is an array of SingleElements, so we work out - * the errorPos for each element separately - * - * @param int $commentStart The position in the stack where - * the comment started. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processAuthors($commentStart) + protected function processAuthor(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $authors = $this->commentParser->getAuthors(); - // Report missing return. - if (empty($authors) === false) { - foreach ($authors as $author) { - $errorPos = ($commentStart + $author->getLine()); - $content = $author->getContent(); - if ($content !== '') { - $local = '\da-zA-Z-_+'; - // Dot character cannot be the first or last character - // in the local-part. - $localMiddle = $local.'.\w'; - if (preg_match('/^([^<]*)\s+<(['.$local.']['.$localMiddle.']*['.$local.']@[\da-zA-Z][-.\w]*[\da-zA-Z]\.[a-zA-Z]{2,7})>$/', $content) === 0) { - $error = 'Content of the @author tag must be in the form "Display Name "'; - $this->currentFile->addError($error, $errorPos, 'InvalidAuthors'); - } - } else { - $error = 'Content missing for @author tag in %s comment'; - $docBlock = (get_class($this) === 'PMAStandard_Sniffs_Commenting_FileCommentSniff') ? 'file' : 'class'; - $data = array($docBlock); - $this->currentFile->addError($error, $errorPos, 'EmptyAuthors', $data); - } + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + $local = '\da-zA-Z-_+'; + // Dot character cannot be the first or last character in the local-part. + $localMiddle = $local.'.\w'; + if (preg_match('/^([^<]*)\s+<(['.$local.'](['.$localMiddle.']*['.$local.'])*@[\da-zA-Z][-.\w]*[\da-zA-Z]\.[a-zA-Z]{2,7})>$/', $content) === 0) { + $error = 'Content of the @author tag must be in the form "Display Name "'; + $phpcsFile->addError($error, $tag, 'InvalidAuthors'); } } - }//end processAuthors() + }//end processAuthor() /** * Process the copyright tags. * - * @param int $commentStart The position in the stack where - * the comment started. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processCopyrights($commentStart) + protected function processCopyright(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $copyrights = $this->commentParser->getCopyrights(); - foreach ($copyrights as $copyright) { - $errorPos = ($commentStart + $copyright->getLine()); - $content = $copyright->getContent(); - if ($content !== '') { - $matches = array(); - if (preg_match('/^([0-9]{4})((.{1})([0-9]{4}))? (.+)$/', $content, $matches) !== 0) { - // Check earliest-latest year order. - if ($matches[3] !== '') { - if ($matches[3] !== '-') { - $error = 'A hyphen must be used between the earliest and latest year'; - $this->currentFile->addError($error, $errorPos, 'CopyrightHyphen'); - } - - if ($matches[4] !== '' && $matches[4] < $matches[1]) { - $error = "Invalid year span \"$matches[1]$matches[3]$matches[4]\" found; consider \"$matches[4]-$matches[1]\" instead"; - $this->currentFile->addWarning($error, $errorPos, 'InvalidCopyright'); - } + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + $matches = array(); + if (preg_match('/^([0-9]{4})((.{1})([0-9]{4}))? (.+)$/', $content, $matches) !== 0) { + // Check earliest-latest year order. + if ($matches[3] !== '') { + if ($matches[3] !== '-') { + $error = 'A hyphen must be used between the earliest and latest year'; + $phpcsFile->addError($error, $tag, 'CopyrightHyphen'); + } + + if ($matches[4] !== '' && $matches[4] < $matches[1]) { + $error = "Invalid year span \"$matches[1]$matches[3]$matches[4]\" found; consider \"$matches[4]-$matches[1]\" instead"; + $phpcsFile->addWarning($error, $tag, 'InvalidCopyright'); } - } else { - $error = '@copyright tag must contain a year and the name of the copyright holder'; - $this->currentFile->addError($error, $errorPos, 'EmptyCopyright'); } } else { $error = '@copyright tag must contain a year and the name of the copyright holder'; - $this->currentFile->addError($error, $errorPos, 'EmptyCopyright'); - }//end if - }//end if + $phpcsFile->addError($error, $tag, 'IncompleteCopyright'); + } + }//end foreach - }//end processCopyrights() + }//end processCopyright() /** * Process the license tag. * - * @param int $errorPos The line number where the error occurs. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processLicense($errorPos) + protected function processLicense(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $license = $this->commentParser->getLicense(); - if ($license !== null) { - $value = $license->getValue(); - $comment = $license->getComment(); - if ($value === '' || $comment === '') { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + $matches = array(); + preg_match('/^([^\s]+)\s+(.*)/', $content, $matches); + if (count($matches) !== 3) { $error = '@license tag must contain a URL and a license name'; - $this->currentFile->addError($error, $errorPos, 'EmptyLicense'); + $phpcsFile->addError($error, $tag, 'IncompleteLicense'); } } @@ -737,26 +494,29 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ /** * Process the version tag. * - * @param int $errorPos The line number where the error occurs. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. * * @return void */ - protected function processVersion($errorPos) + protected function processVersion(PHP_CodeSniffer_File $phpcsFile, array $tags) { - $version = $this->commentParser->getVersion(); - if ($version !== null) { - $content = $version->getContent(); - $matches = array(); - if (empty($content) === true) { - $error = 'Content missing for @version tag in file comment'; - $this->currentFile->addError($error, $errorPos, 'EmptyVersion'); - } else if (strstr($content, 'CVS:') === false + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if (strstr($content, 'CVS:') === false && strstr($content, 'SVN:') === false && strstr($content, 'GIT:') === false + && strstr($content, 'HG:') === false ) { - $error = 'Invalid version "%s" in file comment; consider "CVS: " or "SVN: " or "GIT: " instead'; + $error = 'Invalid version "%s" in file comment; consider "CVS: " or "SVN: " or "GIT: " or "HG: " instead'; $data = array($content); - $this->currentFile->addWarning($error, $errorPos, 'InvalidVersion', $data); + $phpcsFile->addWarning($error, $tag, 'InvalidVersion', $data); } } @@ -764,5 +524,3 @@ class PMAStandard_Sniffs_Commenting_FileCommentSniff implements PHP_CodeSniffer_ }//end class - -?> diff --git a/PMAStandard/Sniffs/Commenting/FunctionCommentSniff.php b/PMAStandard/Sniffs/Commenting/FunctionCommentSniff.php index 8852c7700b..0f215d3307 100644 --- a/PMAStandard/Sniffs/Commenting/FunctionCommentSniff.php +++ b/PMAStandard/Sniffs/Commenting/FunctionCommentSniff.php @@ -8,80 +8,26 @@ * @package PHP_CodeSniffer * @author Greg Sherwood * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ -if (class_exists('PHP_CodeSniffer_CommentParser_FunctionCommentParser', true) === false) { - throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_CommentParser_FunctionCommentParser not found'); -} - /** * Parses and verifies the doc comments for functions. * - * Verifies that : - *
    - *
  • A comment exists
  • - *
  • There is a blank newline after the short description.
  • - *
  • There is a blank newline between the long and short description.
  • - *
  • There is a blank newline between the long description and tags.
  • - *
  • Parameter names represent those in the method.
  • - *
  • Parameter comments are in the correct order
  • - *
  • Parameter comments are complete
  • - *
  • A space is present before the first and after the last parameter
  • - *
  • A return type exists
  • - *
  • There must be one blank line between body and headline comments.
  • - *
  • Any throw tag must have an exception class.
  • - *
- * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.3.3 + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: 2.2.0 * @link http://pear.php.net/package/PHP_CodeSniffer */ class PMAStandard_Sniffs_Commenting_FunctionCommentSniff implements PHP_CodeSniffer_Sniff { - /** - * The name of the method that we are currently processing. - * - * @var string - */ - private $_methodName = ''; - - /** - * The position in the stack where the fucntion token was found. - * - * @var int - */ - private $_functionToken = null; - - /** - * The position in the stack where the class token was found. - * - * @var int - */ - private $_classToken = null; - - /** - * The function comment parser for the current method. - * - * @var PHP_CodeSniffer_Comment_Parser_FunctionCommentParser - */ - protected $commentParser = null; - - /** - * The current PHP_CodeSniffer_File object we are processing. - * - * @var PHP_CodeSniffer_File - */ - protected $currentFile = null; - /** * Returns an array of tokens this test wants to listen for. @@ -106,385 +52,333 @@ class PMAStandard_Sniffs_Commenting_FunctionCommentSniff implements PHP_CodeSnif */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { - $find = array( - T_COMMENT, - T_DOC_COMMENT, - T_CLASS, - T_FUNCTION, - T_OPEN_TAG, - ); - - $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1)); - - if ($commentEnd === false) { - return; - } - - $this->currentFile = $phpcsFile; - $tokens = $phpcsFile->getTokens(); - - // If the token that we found was a class or a function, then this - // function has no doc comment. - $code = $tokens[$commentEnd]['code']; - - if ($code === T_COMMENT) { - $error = 'You must use "/**" style comments for a function comment'; - $phpcsFile->addError($error, $stackPtr, 'WrongStyle'); - return; - } else if ($code !== T_DOC_COMMENT) { - $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing'); - return; - } - - // If there is any code between the function keyword and the doc block - // then the doc block is not for us. - $ignore = PHP_CodeSniffer_Tokens::$scopeModifiers; - $ignore[] = T_STATIC; - $ignore[] = T_WHITESPACE; - $ignore[] = T_ABSTRACT; - $ignore[] = T_FINAL; - $prevToken = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true); - if ($prevToken !== $commentEnd) { - $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing'); - return; - } - - $this->_functionToken = $stackPtr; - - $this->_classToken = null; - foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condition) { - if ($condition === T_CLASS || $condition === T_INTERFACE) { - $this->_classToken = $condPtr; - break; - } - } - - // If the first T_OPEN_TAG is right before the comment, it is probably - // a file comment. - $commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1); - $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($commentStart - 1), null, true); - if ($tokens[$prevToken]['code'] === T_OPEN_TAG) { - // Is this the first open tag? - if ($stackPtr === 0 || $phpcsFile->findPrevious(T_OPEN_TAG, ($prevToken - 1)) === false) { - $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing'); - return; + $tokens = $phpcsFile->getTokens(); + $find = PHP_CodeSniffer_Tokens::$methodPrefixes; + $find[] = T_WHITESPACE; + + $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + // Inline comments might just be closing comments for + // control structures or functions instead of function comments + // using the wrong comment type. If there is other code on the line, + // assume they relate to that code. + $prev = $phpcsFile->findPrevious($find, ($commentEnd - 1), null, true); + if ($prev !== false && $tokens[$prev]['line'] === $tokens[$commentEnd]['line']) { + $commentEnd = $prev; } } - $comment = $phpcsFile->getTokensAsString($commentStart, ($commentEnd - $commentStart + 1)); - $this->_methodName = $phpcsFile->getDeclarationName($stackPtr); - - try { - $this->commentParser = new PHP_CodeSniffer_CommentParser_FunctionCommentParser($comment, $phpcsFile); - $this->commentParser->parse(); - } catch (PHP_CodeSniffer_CommentParser_ParserException $e) { - $line = ($e->getLineWithinComment() + $commentStart); - $phpcsFile->addError($e->getMessage(), $line, 'FailedParse'); + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG + && $tokens[$commentEnd]['code'] !== T_COMMENT + ) { + $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing'); + $phpcsFile->recordMetric($stackPtr, 'Function has doc comment', 'no'); return; + } else { + $phpcsFile->recordMetric($stackPtr, 'Function has doc comment', 'yes'); } - $comment = $this->commentParser->getComment(); - if (is_null($comment) === true) { - $error = 'Function doc comment is empty'; - $phpcsFile->addError($error, $commentStart, 'Empty'); + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a function comment', $stackPtr, 'WrongStyle'); return; } - $this->processParams($commentStart); - $this->processReturn($commentStart, $commentEnd); - $this->processThrows($commentStart); - - // No extra newline before short description. - $short = $comment->getShortComment(); - $newlineCount = 0; - $newlineSpan = strspn($short, $phpcsFile->eolChar); - if ($short !== '' && $newlineSpan > 0) { - $error = 'Extra newline(s) found before function comment short description'; - $phpcsFile->addError($error, ($commentStart + 1), 'SpacingBeforeShort'); + if ($tokens[$commentEnd]['line'] !== ($tokens[$stackPtr]['line'] - 1)) { + $error = 'There must be no blank lines after the function comment'; + $phpcsFile->addError($error, $commentEnd, 'SpacingAfter'); } - $newlineCount = (substr_count($short, $phpcsFile->eolChar) + 1); - - // Exactly one blank line between short and long description. - $long = $comment->getLongComment(); - if (empty($long) === false) { - $between = $comment->getWhiteSpaceBetween(); - $newlineBetween = substr_count($between, $phpcsFile->eolChar); - if ($newlineBetween !== 2) { - $error = 'There must be exactly one blank line between descriptions in function comment'; - $phpcsFile->addError($error, ($commentStart + $newlineCount + 1), 'SpacingAfterShort'); - } - - $newlineCount += $newlineBetween; - } - - // Exactly one blank line before tags. - $params = $this->commentParser->getTagOrders(); - if (count($params) > 1) { - $newlineSpan = $comment->getNewlineAfter(); - if ($newlineSpan !== 2) { - $error = 'There must be exactly one blank line before the tags in function comment'; - if ($long !== '') { - $newlineCount += (substr_count($long, $phpcsFile->eolChar) - $newlineSpan + 1); + $commentStart = $tokens[$commentEnd]['comment_opener']; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@see') { + // Make sure the tag isn't empty. + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) { + $error = 'Content missing for @see tag in function comment'; + $phpcsFile->addError($error, $tag, 'EmptySees'); } - - $phpcsFile->addError($error, ($commentStart + $newlineCount), 'SpacingBeforeTags'); - $short = rtrim($short, $phpcsFile->eolChar.' '); } } + $this->processReturn($phpcsFile, $stackPtr, $commentStart); + $this->processThrows($phpcsFile, $stackPtr, $commentStart); + $this->processParams($phpcsFile, $stackPtr, $commentStart); + }//end process() /** - * Process any throw tags that this function comment has. + * Process the return comment of this function comment. * - * @param int $commentStart The position in the stack where the - * comment started. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. * * @return void */ - protected function processThrows($commentStart) + protected function processReturn(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart) { - if (count($this->commentParser->getThrows()) === 0) { - return; - } - - foreach ($this->commentParser->getThrows() as $throw) { + $tokens = $phpcsFile->getTokens(); - $exception = $throw->getValue(); - $errorPos = ($commentStart + $throw->getLine()); + // Skip constructor and destructor. + $methodName = $phpcsFile->getDeclarationName($stackPtr); + $isSpecialMethod = ($methodName === '__construct' || $methodName === '__destruct'); + + $return = null; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@return') { + if ($return !== null) { + $error = 'Only 1 @return tag is allowed in a function comment'; + $phpcsFile->addError($error, $tag, 'DuplicateReturn'); + return; + } - if ($exception === '') { - $error = '@throws tag must contain the exception class name'; - $this->currentFile->addError($error, $errorPos, 'EmptyThrows'); + $return = $tag; } } - }//end processThrows() - - - /** - * Process the return comment of this function comment. - * - * @param int $commentStart The position in the stack where the comment started. - * @param int $commentEnd The position in the stack where the comment ended. - * - * @return void - */ - protected function processReturn($commentStart, $commentEnd) - { - // Skip constructor and destructor. - $className = ''; - if ($this->_classToken !== null) { - $className = $this->currentFile->getDeclarationName($this->_classToken); - $className = strtolower(ltrim($className, '_')); + if ($isSpecialMethod === true) { + return; } - $methodName = strtolower(ltrim($this->_methodName, '_')); - $isSpecialMethod = ($this->_methodName === '__construct' || $this->_methodName === '__destruct'); - - if ($isSpecialMethod === false && $methodName !== $className) { - // Report missing return tag. - if ($this->commentParser->getReturn() === null) { - $error = 'Missing @return tag in function comment'; - $this->currentFile->addError($error, $commentEnd, 'MissingReturn'); - } else if (trim($this->commentParser->getReturn()->getRawContent()) === '') { - $error = '@return tag is empty in function comment'; - $errorPos = ($commentStart + $this->commentParser->getReturn()->getLine()); - $this->currentFile->addError($error, $errorPos, 'EmptyReturn'); + if ($return !== null) { + $content = $tokens[($return + 2)]['content']; + if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) { + $error = 'Return type missing for @return tag in function comment'; + $phpcsFile->addError($error, $return, 'MissingReturnType'); } - } + } else { + $error = 'Missing @return tag in function comment'; + $phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn'); + }//end if }//end processReturn() /** - * Process the function parameter comments. + * Process any throw tags that this function comment has. * - * @param int $commentStart The position in the stack where - * the comment started. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. * * @return void */ - protected function processParams($commentStart) + protected function processThrows(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart) { - $realParams = $this->currentFile->getMethodParameters($this->_functionToken); + $tokens = $phpcsFile->getTokens(); - $params = $this->commentParser->getParams(); - $foundParams = array(); - - if (empty($params) === false) { - - $lastParm = (count($params) - 1); - if (substr_count($params[$lastParm]->getWhitespaceAfter(), $this->currentFile->eolChar) !== 2) { - $error = 'Last parameter comment requires a blank newline after it'; - $errorPos = ($params[$lastParm]->getLine() + $commentStart); - $this->currentFile->addError($error, $errorPos, 'SpacingAfterParams'); + $throws = array(); + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] !== '@throws') { + continue; } - // Parameters must appear immediately after the comment. - if ($params[0]->getOrder() !== 2) { - $error = 'Parameters must appear immediately after the comment'; - $errorPos = ($params[0]->getLine() + $commentStart); - $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParams'); + $exception = null; + $comment = null; + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $matches = array(); + preg_match('/([^\s]+)(?:\s+(.*))?/', $tokens[($tag + 2)]['content'], $matches); + $exception = $matches[1]; + if (isset($matches[2]) === true) { + $comment = $matches[2]; + } } - $previousParam = null; - $spaceBeforeVar = 10000; - $spaceBeforeComment = 10000; - $longestType = 0; - $longestVar = 0; - - foreach ($params as $param) { - - $paramComment = trim($param->getComment()); - $errorPos = ($param->getLine() + $commentStart); + if ($exception === null) { + $error = 'Exception type missing for @throws tag in function comment'; + $phpcsFile->addError($error, $tag, 'InvalidThrows'); + } + }//end foreach - // Make sure that there is only one space before the var type. - if ($param->getWhitespaceBeforeType() !== ' ') { - $error = 'Expected 1 space before variable type'; - $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParamType'); - } + }//end processThrows() - $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); - if ($spaceCount < $spaceBeforeVar) { - $spaceBeforeVar = $spaceCount; - $longestType = $errorPos; - } - $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); + /** + * Process the function parameter comments. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processParams(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + $params = array(); + $maxType = 0; + $maxVar = 0; + foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) { + if ($tokens[$tag]['content'] !== '@param') { + continue; + } - if ($spaceCount < $spaceBeforeComment && $paramComment !== '') { - $spaceBeforeComment = $spaceCount; - $longestVar = $errorPos; + $type = ''; + $typeSpace = 0; + $var = ''; + $varSpace = 0; + $comment = ''; + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $matches = array(); + preg_match('/([^$&]+)(?:((?:\$|&)[^\s]+)(?:(\s+)(.*))?)?/', $tokens[($tag + 2)]['content'], $matches); + $typeLen = strlen($matches[1]); + $type = trim($matches[1]); + $typeSpace = ($typeLen - strlen($type)); + $typeLen = strlen($type); + if ($typeLen > $maxType) { + $maxType = $typeLen; } - // Make sure they are in the correct order, - // and have the correct name. - $pos = $param->getPosition(); - - $paramName = ($param->getVarName() !== '') ? $param->getVarName() : '[ UNKNOWN ]'; - - if ($previousParam !== null) { - $previousName = ($previousParam->getVarName() !== '') ? $previousParam->getVarName() : 'UNKNOWN'; - - // Check to see if the parameters align properly. - if ($param->alignsVariableWith($previousParam) === false) { - $error = 'The variable names for parameters %s (%s) and %s (%s) do not align'; - $data = array( - $previousName, - ($pos - 1), - $paramName, - $pos, - ); - $this->currentFile->addError($error, $errorPos, 'ParameterNamesNotAligned', $data); + if (isset($matches[2]) === true) { + $var = $matches[2]; + $varLen = strlen($var); + if ($varLen > $maxVar) { + $maxVar = $varLen; } - if ($param->alignsCommentWith($previousParam) === false) { - $error = 'The comments for parameters %s (%s) and %s (%s) do not align'; - $data = array( - $previousName, - ($pos - 1), - $paramName, - $pos, - ); - $this->currentFile->addError($error, $errorPos, 'ParameterCommentsNotAligned', $data); - } - }//end if + if (isset($matches[4]) === true) { + $varSpace = strlen($matches[3]); + $comment = $matches[4]; - // Make sure the names of the parameter comment matches the - // actual parameter. - if (isset($realParams[($pos - 1)]) === true) { - $realName = $realParams[($pos - 1)]['name']; - $foundParams[] = $realName; - - // Append ampersand to name if passing by reference. - if ($realParams[($pos - 1)]['pass_by_reference'] === true) { - $realName = '&'.$realName; - } - - if ($realName !== $paramName) { - $code = 'ParamNameNoMatch'; - $data = array( - $paramName, - $realName, - $pos, - ); - - $error = 'Doc comment for var %s does not match '; - if (strtolower($paramName) === strtolower($realName)) { - $error .= 'case of '; - $code = 'ParamNameNoCaseMatch'; + // Any strings until the next tag belong to this comment. + if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) { + $end = $tokens[$commentStart]['comment_tags'][($pos + 1)]; + } else { + $end = $tokens[$commentStart]['comment_closer']; } - $error .= 'actual variable name %s at position %s'; - - $this->currentFile->addError($error, $errorPos, $code, $data); + for ($i = ($tag + 3); $i < $end; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) { + $comment .= ' '.$tokens[$i]['content']; + } + } + } else { + $error = 'Missing parameter comment'; + $phpcsFile->addError($error, $tag, 'MissingParamComment'); } } else { - // We must have an extra parameter comment. - $error = 'Superfluous doc comment at position '.$pos; - $this->currentFile->addError($error, $errorPos, 'ExtraParamComment'); - } - - if ($param->getVarName() === '') { - $error = 'Missing parameter name at position '.$pos; - $this->currentFile->addError($error, $errorPos, 'MissingParamName'); - } + $error = 'Missing parameter name'; + $phpcsFile->addError($error, $tag, 'MissingParamName'); + }//end if + } else { + $error = 'Missing parameter type'; + $phpcsFile->addError($error, $tag, 'MissingParamType'); + }//end if + + $params[] = array( + 'tag' => $tag, + 'type' => $type, + 'var' => $var, + 'comment' => $comment, + 'type_space' => $typeSpace, + 'var_space' => $varSpace, + ); + }//end foreach + + $realParams = $phpcsFile->getMethodParameters($stackPtr); + $foundParams = array(); + foreach ($params as $pos => $param) { + if ($param['var'] === '') { + continue; + } - if ($param->getType() === '') { - $error = 'Missing type at position '.$pos; - $this->currentFile->addError($error, $errorPos, 'MissingParamType'); + $foundParams[] = $param['var']; + + // Check number of spaces after the type. + $spaces = ($maxType - strlen($param['type']) + 1); + if ($param['type_space'] !== $spaces) { + $error = 'Expected %s spaces after parameter type; %s found'; + $data = array( + $spaces, + $param['type_space'], + ); + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data); + if ($fix === true) { + $content = $param['type']; + $content .= str_repeat(' ', $spaces); + $content .= $param['var']; + $content .= str_repeat(' ', $param['var_space']); + $content .= $param['comment']; + $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); } + } - if ($paramComment === '') { - $error = 'Missing comment for param "%s" at position %s'; - $data = array( - $paramName, - $pos, - ); - $this->currentFile->addError($error, $errorPos, 'MissingParamComment', $data); + // Make sure the param name is correct. + if (isset($realParams[$pos]) === true) { + // PMAStandard tweak for pass by reference variable: + // Variable should have '&' in doc comment + if ($realParams[$pos]['pass_by_reference'] === true) { + $realParams[$pos]['name'] = '&' . $realParams[$pos]['name']; } + $realName = $realParams[$pos]['name']; + if ($realName !== $param['var']) { + $code = 'ParamNameNoMatch'; + $data = array( + $param['var'], + $realName, + ); + + $error = 'Doc comment for parameter %s does not match '; + if (strtolower($param['var']) === strtolower($realName)) { + $error .= 'case of '; + $code = 'ParamNameNoCaseMatch'; + } - $previousParam = $param; - - }//end foreach + $error .= 'actual variable name %s'; - if ($spaceBeforeVar !== 1 && $spaceBeforeVar !== 10000 && $spaceBeforeComment !== 10000) { - $error = 'Expected 1 space after the longest type'; - $this->currentFile->addError($error, $longestType, 'SpacingAfterLongType'); + $phpcsFile->addError($error, $param['tag'], $code, $data); + } + } else if (substr($param['var'], -4) !== ',...') { + // We must have an extra parameter comment. + $error = 'Superfluous parameter comment'; + $phpcsFile->addError($error, $param['tag'], 'ExtraParamComment'); + }//end if + + if ($param['comment'] === '') { + continue; } - if ($spaceBeforeComment !== 1 && $spaceBeforeComment !== 10000) { - $error = 'Expected 1 space after the longest variable name'; - $this->currentFile->addError($error, $longestVar, 'SpacingAfterLongName'); + // Check number of spaces after the var name. + $spaces = ($maxVar - strlen($param['var']) + 1); + if ($param['var_space'] !== $spaces) { + $error = 'Expected %s spaces after parameter name; %s found'; + $data = array( + $spaces, + $param['var_space'], + ); + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamName', $data); + if ($fix === true) { + $content = $param['type']; + $content .= str_repeat(' ', $param['type_space']); + $content .= $param['var']; + $content .= str_repeat(' ', $spaces); + $content .= $param['comment']; + $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); + } } - - }//end if + }//end foreach $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } - // Report and missing comments. + // Report missing comments. $diff = array_diff($realNames, $foundParams); foreach ($diff as $neededParam) { - if (count($params) !== 0) { - $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart); - } else { - $errorPos = $commentStart; - } - - $error = 'Doc comment for "%s" missing'; + $error = 'Doc comment for parameter "%s" missing'; $data = array($neededParam); - $this->currentFile->addError($error, $errorPos, 'MissingParamTag', $data); + $phpcsFile->addError($error, $commentStart, 'MissingParamTag', $data); } }//end processParams() }//end class - -?> diff --git a/PMAStandard/Sniffs/Commenting/InlineCommentSniff.php b/PMAStandard/Sniffs/Commenting/InlineCommentSniff.php deleted file mode 100644 index 30ad0e0c15..0000000000 --- a/PMAStandard/Sniffs/Commenting/InlineCommentSniff.php +++ /dev/null @@ -1,70 +0,0 @@ - - * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer - */ - -/** - * PHP_CodeSniffer_Sniffs_PEAR_Commenting_InlineCommentSniff. - * - * Checks that no perl-style comments are used. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.3.3 - * @link http://pear.php.net/package/PHP_CodeSniffer - */ -class PMAStandard_Sniffs_Commenting_InlineCommentSniff implements PHP_CodeSniffer_Sniff -{ - - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return array(T_COMMENT); - - }//end register() - - - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - - if ($tokens[$stackPtr]['content']{0} === '#') { - $error = 'Perl-style comments are not allowed. Use "// Comment."'; - $error .= ' or "/* comment */" instead.'; - $phpcsFile->addError($error, $stackPtr, 'WrongStyle'); - } - - }//end process() - - -}//end class - -?> diff --git a/PMAStandard/Sniffs/Files/LineLengthSniff.php b/PMAStandard/Sniffs/Files/LineLengthSniff.php deleted file mode 100644 index ca0fee70ab..0000000000 --- a/PMAStandard/Sniffs/Files/LineLengthSniff.php +++ /dev/null @@ -1,169 +0,0 @@ - - * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer - */ - -/** - * PMAStandard_Sniffs_Files_LineLengthSniff. - * - * Checks all lines in the file, and throws warnings if they are over 80 - * characters in length and errors if they are over 100. Both these - * figures can be changed by extending this sniff in your own standard. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.3.3 - * @link http://pear.php.net/package/PHP_CodeSniffer - */ -class PMAStandard_Sniffs_Files_LineLengthSniff implements PHP_CodeSniffer_Sniff -{ - - /** - * The limit that the length of a line should not exceed. - * - * @var int - */ - public $lineLimit = 85; - - /** - * The limit that the length of a line must not exceed. - * - * Set to zero (0) to disable. - * - * @var int - */ - public $absoluteLineLimit = 0; - - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return array(T_OPEN_TAG); - - }//end register() - - - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token in - * the stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - - // Make sure this is the first open tag. - $previousOpenTag = $phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)); - if ($previousOpenTag !== false) { - return; - } - - $tokenCount = 0; - $currentLineContent = ''; - $currentLine = 1; - - $trim = (strlen($phpcsFile->eolChar) * -1); - for (; $tokenCount < $phpcsFile->numTokens; $tokenCount++) { - if ($tokens[$tokenCount]['line'] === $currentLine) { - $currentLineContent .= $tokens[$tokenCount]['content']; - } else { - $currentLineContent = substr($currentLineContent, 0, $trim); - $this->checkLineLength($phpcsFile, ($tokenCount - 1), $currentLineContent); - $currentLineContent = $tokens[$tokenCount]['content']; - $currentLine++; - } - } - - $currentLineContent = substr($currentLineContent, 0, $trim); - $this->checkLineLength($phpcsFile, ($tokenCount - 1), $currentLineContent); - - }//end process() - - - /** - * Checks if a line is too long. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The token at the end of the line. - * @param string $lineContent The content of the line. - * - * @return void - */ - protected function checkLineLength(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $lineContent) - { - // If the content is a CVS or SVN id in a version tag, or it is - // a license tag with a name and URL, there is nothing the - // developer can do to shorten the line, so don't throw errors. - if (preg_match('|@version[^\$]+\$Id|', $lineContent) !== 0) { - return; - } - - if (preg_match('|@license|', $lineContent) !== 0) { - return; - } - - if (preg_match('|__\("[^"]{40,999}"\)|', $lineContent) !== 0) { - return; - } - - if (preg_match("@__\('([^']|\\'){40,999}'\)@", $lineContent) !== 0) { - return; - } - - if (PHP_CODESNIFFER_ENCODING !== 'iso-8859-1') { - // Not using the detault encoding, so take a bit more care. - $lineLength = iconv_strlen($lineContent, PHP_CODESNIFFER_ENCODING); - if ($lineLength === false) { - // String contained invalid characters, so revert to default. - $lineLength = strlen($lineContent); - } - } else { - $lineLength = strlen($lineContent); - } - - if ($this->absoluteLineLimit > 0 - && $lineLength > $this->absoluteLineLimit - ) { - $data = array( - $this->absoluteLineLimit, - $lineLength, - ); - - $error = 'Line exceeds maximum limit of %s characters; contains %s characters'; - $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); - } else if ($lineLength > $this->lineLimit) { - $data = array( - $this->lineLimit, - $lineLength, - ); - - $warning = 'Line exceeds %s characters; contains %s characters'; - $phpcsFile->addWarning($warning, $stackPtr, 'TooLong', $data); - } - }//end checkLineLength() - - -}//end class - diff --git a/PMAStandard/ruleset.xml b/PMAStandard/ruleset.xml index 13f153ca67..a930c4fd77 100644 --- a/PMAStandard/ruleset.xml +++ b/PMAStandard/ruleset.xml @@ -7,8 +7,13 @@ - - + + + + + + + -- cgit v1.2.3