/** * Process a list of unknown tags. * * @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 processUnknownTags($commentStart, $commentEnd) { $unknownTags = $this->commentParser->getUnknown(); foreach ($unknownTags as $errorTag) { $error = '@%s tag is not allowed in function comment'; $data = array($errorTag['tag']); $this->currentFile->addWarning($error, $commentStart + $errorTag['line'], 'TagNotAllowed', $data); } }
/** * Process the return comment of this function comment. * * @return void */ protected function getValueOfReturnTag() { $returnContent = $tmpContent = null; $pairElement = $this->commentParser->getReturn(); if ($pairElement instanceof PHP_CodeSniffer_CommentParser_AbstractDocElement) { $tmpContent = trim($this->commentParser->getReturn()->getRawContent()); } if ($tmpContent !== null) { $returnContent = $tmpContent; } return $returnContent; }
/** * Process any throw tags that this function comment has. * * @param int $commentStart The position in the stack where the * comment started. * * @return void */ protected function processThrows($commentStart) { if (count($this->commentParser->getThrows()) === 0) { return; } foreach ($this->commentParser->getThrows() as $throw) { $exception = $throw->getValue(); $errorPos = $commentStart + $throw->getLine(); if ($exception === '') { $error = '@throws tag must contain the exception class name'; $this->currentFile->addError($error, $errorPos, 'EmptyThrows'); } } }
/** * Process any throw tags that this function comment has. * * @param int $commentStart The position in the stack where the comment started. * * @return void */ protected function processThrows($commentStart) { if (count($this->commentParser->getThrows()) === 0) { return; } $tagOrder = $this->commentParser->getTagOrders(); $index = array_keys($this->commentParser->getTagOrders(), 'throws'); foreach ($this->commentParser->getThrows() as $i => $throw) { $exception = $throw->getValue(); $content = trim($throw->getComment()); $errorPos = $commentStart + $throw->getLine(); if (empty($exception) === true) { $error = 'Exception type and comment missing for @throws tag in function comment'; $this->currentFile->addError($error, $errorPos, 'InvalidThrows'); } else { if (empty($content) === true) { $error = 'Comment missing for @throws tag in function comment'; $this->currentFile->addError($error, $errorPos, 'EmptyThrows'); } else { // Starts with a capital letter and ends with a fullstop. $firstChar = $content[0]; if (strtoupper($firstChar) !== $firstChar) { $error = '@throws tag comment must start with a capital letter'; $this->currentFile->addError($error, $errorPos, 'ThrowsNotCapital'); } $lastChar = $content[strlen($content) - 1]; if ($lastChar !== '.') { $error = '@throws tag comment must end with a full stop'; $this->currentFile->addError($error, $errorPos, 'ThrowsNoFullStop'); } } } $since = array_keys($tagOrder, 'since'); if (count($since) === 1 && $this->_tagIndex !== 0) { $this->_tagIndex++; if ($index[$i] !== $this->_tagIndex) { $error = 'The @throws tag is in the wrong order; the tag follows @return'; $this->currentFile->addError($error, $errorPos, 'ThrowsOrder'); } } } //end foreach }
/** * Process the function parameter comments. * * @param int $commentStart The position in the stack where * the comment started. * * @return void */ protected function processParams($commentStart) { $realParams = $this->currentFile->getMethodParameters($this->_functionToken); $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'); } // 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'); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; // 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'); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment && $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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 ($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 // 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; 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'; } $error .= 'actual variable name %s at position %s'; $this->currentFile->addError($error, $errorPos, $code, $data); } } 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'); } if ($param->getType() === '') { $error = 'Missing type at position ' . $pos; $this->currentFile->addError($error, $errorPos, 'MissingParamType'); } if ($paramComment === '') { $error = 'Missing comment for param "%s" at position %s'; $data = array($paramName, $pos); $this->currentFile->addError($error, $errorPos, 'MissingParamComment', $data); } $previousParam = $param; } //end foreach if ($spaceBeforeVar !== 1 && $spaceBeforeVar !== 10000 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest type'; $this->currentFile->addError($error, $longestType, 'SpacingAfterLongType'); } if ($spaceBeforeComment !== 1 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest variable name'; $this->currentFile->addError($error, $longestVar, 'SpacingAfterLongName'); } } //end if $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // Report and 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'; $data = array($neededParam); $this->currentFile->addError($error, $errorPos, 'MissingParamTag', $data); } }
/** * 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) { $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 (isset($tokens[$stackPtr]['nested_parenthesis'])) { return; } if (!isset($tokens[$stackPtr]['conditions'])) { return; } end($tokens[$stackPtr]['conditions']); $ckey = key($tokens[$stackPtr]['conditions']); if (!isset($tokens[$ckey]) || $tokens[$ckey]['code'] !== T_CLASS && $tokens[$ckey]['code'] !== T_INTERFACE) { return; } // 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 variable comment'; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.6.4') . $error, $stackPtr); return; } else { if ($code !== T_DOC_COMMENT) { $error = 'Missing variable doc comment'; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.6.1') . $error, $stackPtr); 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($this->getReqPrefix('REQ.PHP.4.6.1') . 'Missing function doc comment', $stackPtr); return; } // 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($this->getReqPrefix('REQ.PHP.4.6.1') . 'Missing function doc comment', $stackPtr); return; } } $comment = $phpcsFile->getTokensAsString($commentStart, $commentEnd - $commentStart + 1); try { $this->commentParser = new PHP_CodeSniffer_CommentParser_MemberCommentParser($comment, $phpcsFile); $this->commentParser->parse(); } catch (PHP_CodeSniffer_CommentParser_ParserException $e) { $line = $e->getLineWithinComment() + $commentStart; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.1') . $e->getMessage(), $line); return; } $comment = $this->commentParser->getComment(); if (is_null($comment) === true) { $error = 'Variable doc comment is empty'; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.6.2') . $error, $commentStart); return; } $this->processTags($commentStart, $commentEnd); // No extra newline before short description. $short = $comment->getShortComment(); $newlineCount = 0; $newlineSpan = strspn($short, $phpcsFile->eolChar); if ($short !== '' && $newlineSpan > 0) { $line = $newlineSpan > 1 ? 'newlines' : 'newline'; $error = "Extra {$line} found before variable comment short description"; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.7') . $error, $commentStart + 1); } $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 variable comment'; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.19') . $error, $commentStart + $newlineCount + 1); } $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; } $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.18') . $error, $commentStart + $newlineCount); $short = rtrim($short, $phpcsFile->eolChar . ' '); } } }
/** * Process the function parameter comments * * @param integer $commentStart The position in the stack where the comment started * @param integer $commentEnd The position in the stack where the comment ended * @return void */ protected function _processParams($commentStart, $commentEnd) { $realParams = $this->_currentFile->getMethodParameters($this->_functionToken); $params = $this->_commentParser->getParams(); $foundParams = array(); if (empty($params) === false) { $isSpecialMethod = ($this->_methodName === '__construct' or $this->_methodName === '__destruct'); if (substr_count($params[count($params) - 1]->getWhitespaceAfter(), $this->_currentFile->eolChar) !== 1 and $isSpecialMethod === false) { $error = 'No empty line after last parameter comment allowed'; $errorPos = $params[count($params) - 1]->getLine() + $commentStart; $this->_currentFile->addError($error, $errorPos + 1); } // 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); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; if (count($this->_commentParser->getThrows()) !== 0) { $isSpecialMethod = false; } foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; // Make sure that there is only one or two space before the var type if ($isSpecialMethod === false and $param->getWhitespaceBeforeType() !== ' ') { $error = 'Expected 2 spaces before variable type'; $this->_currentFile->addError($error, $errorPos); } if ($isSpecialMethod === true and $param->getWhitespaceBeforeType() !== ' ') { $error = 'Expected 1 space before variable type'; $this->_currentFile->addError($error, $errorPos); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment and $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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 ' . $previousName . ' (' . ($pos - 1) . ') and ' . $paramName . ' (' . $pos . ') do not align'; $this->_currentFile->addError($error, $errorPos); } if ($param->alignsCommentWith($previousParam) === false) { $error = 'The comments for parameters ' . $previousName . ' (' . ($pos - 1) . ') and ' . $paramName . ' (' . $pos . ') do not align'; $this->_currentFile->addError($error, $errorPos); } } // Variable must be one of the supported standard type $typeNames = explode('|', $param->getType()); foreach ($typeNames as $typeName) { $suggestedName = PHP_CodeSniffer::suggestType($typeName); if ($typeName !== $suggestedName) { $error = "Expected \"{$suggestedName}\"; found \"{$typeName}\" for {$paramName} at position {$pos}"; $this->_currentFile->addError($error, $errorPos); continue; } if (count($typeNames) !== 1) { continue; } // Check type hint for array and custom type $suggestedTypeHint = ''; if (strpos($suggestedName, 'array') !== false) { $suggestedTypeHint = 'array'; } else { if (in_array($typeName, PHP_CodeSniffer::$allowedTypes) === false) { $suggestedTypeHint = $suggestedName; } } if ($suggestedTypeHint !== '' and isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint === '') { $error = "Type hint \"{$suggestedTypeHint}\" missing for {$paramName} at position {$pos}"; $this->_currentFile->addError($error, $commentEnd + 2); } else { if ($typeHint !== $suggestedTypeHint) { $error = "Expected type hint \"{$suggestedTypeHint}\"; found \"{$typeHint}\"" . " for {$paramName} at position {$pos}"; $this->_currentFile->addError($error, $commentEnd + 2); } } } else { if ($suggestedTypeHint === '' and isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint !== '') { $error = "Unknown type hint \"{$typeHint}\" found for {$paramName} at position {$pos}"; $this->_currentFile->addError($error, $commentEnd + 2); } } } } // 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 !== $param->getVarName()) { $error = 'Doc comment var "' . $paramName; $error .= '" does not match actual variable name "' . $realName; $error .= '" at position ' . $pos; $this->_currentFile->addError($error, $errorPos); } } else { // We must have an extra parameter comment $error = 'Superfluous doc comment at position ' . $pos; $this->_currentFile->addError($error, $errorPos); } if ($param->getVarName() === '') { $error = 'Missing parameter name at position ' . $pos; $this->_currentFile->addError($error, $errorPos); } if ($param->getType() === '') { $error = 'Missing type at position ' . $pos; $this->_currentFile->addError($error, $errorPos); } if ($paramComment === '') { $error = 'Missing comment for param "' . $paramName . '" at position ' . $pos; $this->_currentFile->addError($error, $errorPos); } else { // Param comments must start with a capital letter $firstChar = $paramComment[0]; if (preg_match('|[A-Z]|', $firstChar) === 0 and $firstChar !== '(') { $error = 'Param comment must start with a capital letter'; $this->_currentFile->addError($error, $errorPos); } // Check if optional params include (Optional) within their description $functionBegin = $this->_currentFile->findNext(array(T_FUNCTION), $commentStart); $functionName = $this->_currentFile->findNext(array(T_STRING), $functionBegin); $openBracket = $this->_tokens[$functionBegin]['parenthesis_opener']; $closeBracket = $this->_tokens[$functionBegin]['parenthesis_closer']; $nextParam = $this->_currentFile->findNext(T_VARIABLE, $openBracket + 1, $closeBracket); while ($nextParam !== false) { $nextToken = $this->_currentFile->findNext(T_WHITESPACE, $nextParam + 1, $closeBracket + 1, true); if ($nextToken === false and $this->_tokens[$nextParam + 1]['code'] === T_CLOSE_PARENTHESIS) { break; } $nextCode = $this->_tokens[$nextToken]['code']; $arg = $this->_tokens[$nextParam]['content']; if ($nextCode === T_EQUAL and $paramName === $arg) { if (substr($paramComment, 0, 11) !== '(Optional) ') { $error = "Optional param comment for '{$paramName}' must start with '(Optional)'"; $this->_currentFile->addError($error, $errorPos); } else { if (preg_match('|[A-Z]|', $paramComment[11]) === 0) { $error = 'Param comment must start with a capital letter'; $this->_currentFile->addError($error, $errorPos); } } } $nextParam = $this->_currentFile->findNext(T_VARIABLE, $nextParam + 1, $closeBracket); } } $previousParam = $param; } if ($spaceBeforeVar !== 1 and $spaceBeforeVar !== 10000 and $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest type'; $this->_currentFile->addError($error, $longestType); } if ($spaceBeforeComment !== 1 and $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest variable name'; $this->_currentFile->addError($error, $longestVar); } } $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // 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 "' . $neededParam . '" missing'; $this->_currentFile->addError($error, $errorPos); } }
/** * Process the function parameter comments. * * @param int $commentStart The position in the stack where * the comment started. * * @return void */ protected function processParams($commentStart) { $realParams = $this->currentFile->getMethodParameters($this->_functionToken); $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); } // 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); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; // 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); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment && $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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 ' . $previousName . ' (' . ($pos - 1) . ') and ' . $paramName . ' (' . $pos . ') do not align'; $this->currentFile->addError($error, $errorPos); } if ($param->alignsCommentWith($previousParam) === false) { $error = 'The comments for parameters ' . $previousName . ' (' . ($pos - 1) . ') and ' . $paramName . ' (' . $pos . ') do not align'; $this->currentFile->addError($error, $errorPos); } } //end if // 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 !== $param->getVarName()) { $error = 'Doc comment var "' . $paramName; $error .= '" does not match actual variable name "' . $realName; $error .= '" at position ' . $pos; $this->currentFile->addError($error, $errorPos); } } else { // We must have an extra parameter comment. $error = 'Superfluous doc comment at position ' . $pos; $this->currentFile->addError($error, $errorPos); } if ($param->getVarName() === '') { $error = 'Missing parameter name at position ' . $pos; $this->currentFile->addError($error, $errorPos); } if ($param->getType() === '') { $error = 'Missing type at position ' . $pos; $this->currentFile->addError($error, $errorPos); } if ($paramComment === '') { $error = 'Missing comment for param "' . $paramName . '" at position ' . $pos; $this->currentFile->addError($error, $errorPos); } $previousParam = $param; } //end foreach if ($spaceBeforeVar !== 1 && $spaceBeforeVar !== 10000 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest type'; $this->currentFile->addError($error, $longestType); } if ($spaceBeforeComment !== 1 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest variable name'; $this->currentFile->addError($error, $longestVar); } } //end if $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // Report and 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 "' . $neededParam . '" missing'; $this->currentFile->addError($error, $errorPos); } }
/** * Process the function parameter comments. * * @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 processParams($commentStart, $commentEnd) { $realParams = $this->currentFile->getMethodParameters($this->_functionToken); $params = $this->commentParser->getParams(); $foundParams = array(); if (empty($params) === false) { if (substr_count($params[count($params) - 1]->getWhitespaceAfter(), $this->currentFile->eolChar) !== 2) { $error = 'Last parameter comment requires a blank newline after it'; $errorPos = $params[count($params) - 1]->getLine() + $commentStart; $this->currentFile->addError($error, $errorPos); } // 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); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; // 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); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment && $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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 ' . $previousName . ' (' . ($pos - 1) . ') and ' . $paramName . ' (' . $pos . ') do not align'; $this->currentFile->addError($error, $errorPos); } if ($param->alignsCommentWith($previousParam) === false) { $error = 'The comments for parameters ' . $previousName . ' (' . ($pos - 1) . ') and ' . $paramName . ' (' . $pos . ') do not align'; $this->currentFile->addError($error, $errorPos); } } // Variable must be one of the supported standard type. $typeNames = explode('|', $param->getType()); foreach ($typeNames as $typeName) { $suggestedName = PHP_CodeSniffer::suggestType($typeName); if ($typeName !== $suggestedName) { $error = "Expected \"{$suggestedName}\"; found \"{$typeName}\" for {$paramName} at position {$pos}"; $this->currentFile->addError($error, $errorPos); } else { if (count($typeNames) === 1) { // Check type hint for array and custom type. $suggestedTypeHint = ''; if (strpos($suggestedName, 'array') !== false) { $suggestedTypeHint = 'array'; } else { if (in_array($typeName, PHP_CodeSniffer::$allowedTypes) === false) { $suggestedTypeHint = $suggestedName; } } if ($suggestedTypeHint !== '' && isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint === '') { $error = "Type hint \"{$suggestedTypeHint}\" missing for {$paramName} at position {$pos}"; $this->currentFile->addError($error, $commentEnd + 2); } else { if ($typeHint !== $suggestedTypeHint) { $error = "Expected type hint \"{$suggestedTypeHint}\"; found \"{$typeHint}\" for {$paramName} at position {$pos}"; $this->currentFile->addError($error, $commentEnd + 2); } } } else { if ($suggestedTypeHint === '' && isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint !== '') { $error = "Unknown type hint \"{$typeHint}\" found for {$paramName} at position {$pos}"; $this->currentFile->addError($error, $commentEnd + 2); } } } } } //end if } //end foreach // 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) { $error = 'Doc comment for var ' . $paramName; $error .= ' does not match '; if (strtolower($paramName) === strtolower($realName)) { $error .= 'case of '; } $error .= 'actual variable name ' . $realName; $error .= ' at position ' . $pos; $this->currentFile->addError($error, $errorPos); } } else { // We must have an extra parameter comment. $error = 'Superfluous doc comment at position ' . $pos; $this->currentFile->addError($error, $errorPos); } if ($param->getVarName() === '') { $error = 'Missing parameter name at position ' . $pos; $this->currentFile->addError($error, $errorPos); } if ($param->getType() === '') { $error = 'Missing type at position ' . $pos; $this->currentFile->addError($error, $errorPos); } if ($paramComment === '') { $error = 'Missing comment for param "' . $paramName . '" at position ' . $pos; $this->currentFile->addError($error, $errorPos); } else { // Param comments must start with a capital letter and // end with the full stop. $firstChar = $paramComment[0]; if (preg_match('|[A-Z]|', $firstChar) === 0) { $error = 'Param comment must start with a capital letter'; $this->currentFile->addError($error, $errorPos); } $lastChar = $paramComment[strlen($paramComment) - 1]; if ($lastChar !== '.') { $error = 'Param comment must end with a full stop'; $this->currentFile->addError($error, $errorPos); } } $previousParam = $param; } //end foreach if ($spaceBeforeVar !== 1 && $spaceBeforeVar !== 10000 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest type'; $this->currentFile->addError($error, $longestType); } if ($spaceBeforeComment !== 1 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest variable name'; $this->currentFile->addError($error, $longestVar); } } //end if $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // 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 "' . $neededParam . '" missing'; $this->currentFile->addError($error, $errorPos); } }
/** * Process the function parameter comments. * * @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 processParams($commentStart, $commentEnd) { $realParams = $this->currentFile->getMethodParameters($this->_functionToken); $params = $this->commentParser->getParams(); $foundParams = array(); if (empty($params) === false) { // if (substr_count($params[(count($params) - 1)]->getWhitespaceAfter(), $this->currentFile->eolChar) !== 2) { // $error = 'Last parameter comment requires a blank newline after it'; // $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart); // $this->currentFile->addError($error, $errorPos, 'SpacingAfterParams'); // } // 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'); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; // 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'); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment && $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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 ($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); //// } // } // // Variable must be one of the supported standard type. // $typeNames = explode('|', $param->getType()); // foreach ($typeNames as $typeName) { // $suggestedName = PHP_CodeSniffer::suggestType($typeName); // if ($typeName !== $suggestedName) { // $error = 'Expected "%s"; found "%s" for %s at position %s'; // $data = array( // $suggestedName, // $typeName, // $paramName, // $pos, // ); // $this->currentFile->addError($error, $errorPos, 'IncorrectParamVarName', $data); // } else if (count($typeNames) === 1) { // // Check type hint for array and custom type. // $suggestedTypeHint = ''; // if (strpos($suggestedName, 'array') !== false) { // $suggestedTypeHint = 'array'; // } else if (strpos($suggestedName, 'callable') !== false) { // $suggestedTypeHint = 'callable'; // } else if (in_array($typeName, PHP_CodeSniffer::$allowedTypes) === false) { // $suggestedTypeHint = $suggestedName; // } // // if ($suggestedTypeHint !== '' && isset($realParams[($pos - 1)]) === true) { // $typeHint = $realParams[($pos - 1)]['type_hint']; // if ($typeHint === '') { // $error = 'Type hint "%s" missing for %s at position %s'; // $data = array( // $suggestedTypeHint, // $paramName, // $pos, // ); // $this->currentFile->addError($error, ($commentEnd + 2), 'TypeHintMissing', $data); // } else if ($typeHint !== $suggestedTypeHint) { // $error = 'Expected type hint "%s"; found "%s" for %s at position %s'; // $data = array( // $suggestedTypeHint, // $typeHint, // $paramName, // $pos, // ); // $this->currentFile->addError($error, ($commentEnd + 2), 'IncorrectTypeHint', $data); // } // } else if ($suggestedTypeHint === '' && isset($realParams[($pos - 1)]) === true) { // $typeHint = $realParams[($pos - 1)]['type_hint']; // if ($typeHint !== '') { // $error = 'Unknown type hint "%s" found for %s at position %s'; // $data = array( // $typeHint, // $paramName, // $pos, // ); // $this->currentFile->addError($error, ($commentEnd + 2), 'InvalidTypeHint', $data); // } // } // }//end if // }//end foreach // 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'; } $error .= 'actual variable name %s at position %s'; $this->currentFile->addError($error, $errorPos, $code, $data); } } else { if (substr($paramName, -4) !== ',...') { // 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'); } if ($param->getType() === '') { $error = 'Missing type at position ' . $pos; $this->currentFile->addError($error, $errorPos, 'MissingParamType'); } if ($paramComment === '') { $error = 'Missing comment for param "%s" at position %s'; $data = array($paramName, $pos); $this->currentFile->addError($error, $errorPos, 'MissingParamComment', $data); } else { // Param comments must start with a capital letter and // end with the full stop. $firstChar = $paramComment[0]; if (preg_match('|\\p{Lu}|u', $firstChar) === 0) { $error = 'Param comment must start with a capital letter'; $this->currentFile->addError($error, $errorPos, 'ParamCommentNotCapital'); } $lastChar = $paramComment[strlen($paramComment) - 1]; if (!in_array($lastChar, ['.', '?', '!'])) { $error = 'Param comment must end with punctuation'; $this->currentFile->addError($error, $errorPos, 'ParamCommentPunctuation'); } } $previousParam = $param; } //end foreach if ($spaceBeforeVar !== 1 && $spaceBeforeVar !== 10000 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest type'; $this->currentFile->addError($error, $longestType, 'SpacingAfterLongType'); } if ($spaceBeforeComment !== 1 && $spaceBeforeComment !== 10000) { $error = 'Expected 1 space after the longest variable name'; $this->currentFile->addError($error, $longestVar, 'SpacingAfterLongName'); } } //end if $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // 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'; $data = array($neededParam); $this->currentFile->addError($error, $errorPos, 'MissingParamTag', $data); } }
/** * 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) { $find = array(T_COMMENT, T_DOC_COMMENT, T_CLASS, T_FUNCTION, T_OPEN_TAG); $commentEnd = $phpcsFile->findPrevious($find, $stackPtr - 1); if ($commentEnd === false) { return; } $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) { return; } elseif ($code !== T_DOC_COMMENT) { 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) { return; } // 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) { return; } } $comment = $phpcsFile->getTokensAsString($commentStart, $commentEnd - $commentStart + 1); try { $this->commentParser = new PHP_CodeSniffer_CommentParser_FunctionCommentParser($comment, $phpcsFile); $this->commentParser->parse(); } catch (PHP_CodeSniffer_CommentParser_ParserException $e) { return; } // Function doc comment is empty $comment = $this->commentParser->getComment(); if (is_null($comment) === true) { return; } /** * Here we go. * Now we have a doc comment. Parse the annotations for @author-Tags! */ $error = '@author tag should not be used in function or method phpDoc comment blocks - only at class level'; $unknownTags = $this->commentParser->getUnknown(); foreach ($unknownTags as $tagInfo) { if ($tagInfo['tag'] !== 'author') { continue; } $phpcsFile->addError($error, $tagInfo['line'] + $commentStart, 'NoAuthorAnnotationInFunctionDocComment'); } return null; }
/** * Process the function parameter comments. * * @param int $commentStart The position in the stack where * the comment started. * * @return void */ protected function processParams($commentStart) { $realParams = $this->currentFile->getMethodParameters($this->_functionToken); $params = $this->commentParser->getParams(); $foundParams = array(); if (empty($params) === false) { $lastParm = count($params) - 1; if (substr_count($params[$lastParm]->getWhitespaceAfter(), $this->currentFile->eolChar) !== 1) { $error = 'Last parameter comment must not a blank newline after it'; $errorPos = $params[$lastParm]->getLine() + $commentStart; $this->currentFile->addError($error, $errorPos, 'SpacingAfterParams'); } // 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'); } $previousParam = null; foreach ($params as $param) { $errorPos = $param->getLine() + $commentStart; // Make sure they are in the correct order, // and have the correct name. $pos = $param->getPosition(); $paramName = $param->getVarName() !== '' ? $param->getVarName() : '[ UNKNOWN ]'; // Make sure the names of the parameter comment matches the // actual parameter. if (isset($realParams[$pos - 1]) === true) { // Make sure that there are only tabs used to intend the var type. if ($this->isTabUsedToIntend($param->getWhitespaceBeforeType())) { $error = 'Spaces must be used to indent the variable type; tabs are not allowed'; $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParamType'); } // Make sure that there are only tabs used to intend the var comment. if ($this->isTabUsedToIntend($param->getWhiteSpaceBeforeComment())) { $error = 'Spaces must be used to indent the variable comment; tabs are not allowed'; $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParamComment'); } // Make sure that there are only tabs used to intend the var name. if ($param->getVarName() && $this->isTabUsedToIntend($param->getWhiteSpaceBeforeVarName())) { $error = 'Spaces must be used to indent the variable name; tabs are not allowed'; $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParamName'); } $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'; } $error .= 'actual variable name %s at position %s'; $this->currentFile->addError($error, $errorPos, $code, $data); } } else { // Throw an error if we found a parameter in comment but not in the parameter list of the function $error = 'The paramter "' . $paramName . '" at position ' . $pos . ' is superfluous, because this parameter was not found in parameter list.'; $this->currentFile->addError($error, $errorPos, 'SuperFluous.ParamComment'); } if ($param->getVarName() === '') { $error = 'Missing parameter name at position ' . $pos; $this->currentFile->addError($error, $errorPos, 'MissingParamName'); } if ($param->getType() === '') { $error = 'Missing type at position ' . $pos; $this->currentFile->addError($error, $errorPos, 'MissingParamType'); } } } $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // Report and 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'; $data = array($neededParam); $this->currentFile->addError($error, $errorPos, 'MissingParamTag', $data); } }
/** * Process the function parameter comments * * @param integer $commentStart The position in the stack where the comment started * @param integer $commentEnd The position in the stack where the comment ended * @return void */ protected function _processParams($commentStart, $commentEnd) { $realParams = $this->_currentFile->getMethodParameters($this->_functionToken); $params = $this->_commentParser->getParams(); $foundParams = array(); if (empty($params) === false) { $isSpecialMethod = ($this->_methodName === '__construct' or $this->_methodName === '__destruct'); if (substr_count($params[count($params) - 1]->getWhitespaceAfter(), $this->_currentFile->eolChar) !== 1 and $isSpecialMethod === false) { $errorPos = $params[count($params) - 1]->getLine() + $commentStart; $this->_currentFile->addEvent('EMPTY_LINE_LAST_PARAMETER_FUNCTION_COMMENT', array(), $errorPos + 1); } // Parameters must appear immediately after the comment if ($params[0]->getOrder() !== 2) { $errorPos = $params[0]->getLine() + $commentStart; $this->_currentFile->addEvent('PARAMETER_AFTER_COMMENT_FUNCTION_COMMENT', array(), $errorPos); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; if (count($this->_commentParser->getThrows()) !== 0) { $isSpecialMethod = false; } foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; if ($isSpecialMethod === true and $param->getWhitespaceBeforeType() !== ' ') { $this->_currentFile->addEvent('ONE_SPACE_VARIABLE_FUNCTION_COMMENT', array(), $errorPos); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment and $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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) { $this->_currentFile->addEvent('VARIABLES_NAMES_NOT_ALIGN_FUNCTION_COMMENT', array('previousname' => $previousName, 'previousnamepos' => $pos - 1, 'paramname' => $paramName, 'paramnamepos' => $pos), $errorPos); } if ($param->alignsCommentWith($previousParam) === false) { $this->_currentFile->addEvent('COMMENTS_NOT_ALIGN_FUNCTION_COMMENT', array('previousname' => $previousName, 'previousnamepos' => $pos - 1, 'paramname' => $paramName, 'paramnamepos' => $pos), $errorPos); } } // Variable must be one of the supported standard type $typeNames = explode('|', $param->getType()); foreach ($typeNames as $typeName) { $suggestedName = PHP_CodeSniffer::suggestType($typeName); if ($typeName !== $suggestedName) { $this->_currentFile->addEvent('EXPECTED_FOUND_FUNCTION_COMMENT', array('suggestedname' => $suggestedName, 'paramname' => $paramName, 'typename' => $paramName, 'paramnamepos' => $pos), $errorPos); continue; } if (count($typeNames) !== 1) { continue; } // Check type hint for array and custom type $suggestedTypeHint = ''; if (strpos($suggestedName, 'array') !== false) { $suggestedTypeHint = 'array'; } else { if (in_array($typeName, PHP_CodeSniffer::$allowedTypes) === false) { $suggestedTypeHint = $suggestedName; } } if ($suggestedTypeHint !== '' and isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint === '') { $this->_currentFile->addEvent('TYPEHINT_MISSING_FUNCTION_COMMENT', array('suggestedtypehint' => $suggestedTypeHint, 'paramname' => $paramName, 'paramnamepos' => $pos), $commentEnd + 2); } else { if ($typeHint !== $suggestedTypeHint) { $this->_currentFile->addEvent('EXPECTED_TYPEHINT_FOUND_FUNCTION_COMMENT', array('suggestedtypehint' => $suggestedTypeHint, 'typehint' => $typeHint, 'paramname' => $paramName, 'paramnamepos' => $pos), $commentEnd + 2); } } } else { if ($suggestedTypeHint === '' and isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint !== '') { $this->_currentFile->addEvent('UNKNOW_TYPEHINT_FOUND_FUNCTION_COMMENT', array('typehint' => $typeHint, 'paramname' => $paramName, 'paramnamepos' => $pos), $commentEnd + 2); } } } } // 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 !== $param->getVarName()) { $this->_currentFile->addEvent('DOCCOMMENT_NOT_MATCH_FUNCTION_COMMENT', array('paramname' => $paramName, 'realname' => $realName, 'paramnamepos' => $pos), $errorPos); } } else { // We must have an extra parameter comment $this->_currentFile->addEvent('SUPERFLUOUS_DOCCOMMENT_FUNCTION_COMMENT', array('doccommentpos' => $pos), $errorPos); } if ($param->getVarName() === '') { $this->_currentFile->addEvent('MISSING_PARAMETER_FUNCTION_COMMENT', array('parameterpos' => $pos), $errorPos); } if ($param->getType() === '') { $this->_currentFile->addEvent('MISSING_TYPE_FUNCTION_COMMENT', array('typepos' => $pos), $errorPos); } if ($paramComment === '') { $this->_currentFile->addEvent('MISSING_COMMENT_PARAM_FUNCTION_COMMENT', array('paramname' => $paramName, 'paramnamepos' => $pos), $errorPos); } else { // Check if optional params include (Optional) within their description $functionBegin = $this->_currentFile->findNext(array(T_FUNCTION), $commentStart); $functionName = $this->_currentFile->findNext(array(T_STRING), $functionBegin); $openBracket = $this->_tokens[$functionBegin]['parenthesis_opener']; $closeBracket = $this->_tokens[$functionBegin]['parenthesis_closer']; $nextParam = $this->_currentFile->findNext(T_VARIABLE, $openBracket + 1, $closeBracket); while ($nextParam !== false) { $nextToken = $this->_currentFile->findNext(T_WHITESPACE, $nextParam + 1, $closeBracket + 1, true); if ($nextToken === false and $this->_tokens[$nextParam + 1]['code'] === T_CLOSE_PARENTHESIS) { break; } $nextCode = $this->_tokens[$nextToken]['code']; $arg = $this->_tokens[$nextParam]['content']; if ($nextCode === T_EQUAL and $paramName === $arg) { if (substr($paramComment, 0, 11) !== '(Optional) ') { $this->_currentFile->addEvent('OPTIONAL_PARAM_START_FUNCTION_COMMENT', array('paramname' => $paramName), $errorPos); } } $nextParam = $this->_currentFile->findNext(T_VARIABLE, $nextParam + 1, $closeBracket); } } $previousParam = $param; } if ($spaceBeforeVar !== 1 and $spaceBeforeVar !== 10000 and $spaceBeforeComment !== 10000) { $this->_currentFile->addEvent('ONE_SPACE_LONGEST_TYPE_FUNCTION_COMMENT', array(), $longestType); } if ($spaceBeforeComment !== 1 and $spaceBeforeComment !== 10000) { $this->_currentFile->addEvent('ONE_SPACE_LONGEST_VARIABLE_FUNCTION_COMMENT', array(), $longestVar); } } $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // 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; } $this->_currentFile->addEvent('DOCCOMMENT_MISSING_FUNCTION_COMMENT', array('param' => $neededParam), $errorPos); } }
/** * Process the function parameter comments * * @param integer $commentStart The position in the stack where the comment started * @param integer $commentEnd The position in the stack where the comment ended * @return void */ protected function _processParams($commentStart, $commentEnd) { $realParams = $this->_currentFile->getMethodParameters($this->_functionToken); $params = $this->_commentParser->getParams(); $foundParams = array(); if (empty($params) === false) { $isSpecialMethod = ($this->_methodName === '__construct' or $this->_methodName === '__destruct'); if (substr_count($params[count($params) - 1]->getWhitespaceAfter(), $this->_currentFile->eolChar) !== 1 and $isSpecialMethod === false) { $errorPos = $params[count($params) - 1]->getLine() + $commentStart; $this->_currentFile->addError("No empty line after last parameter comment allowed", $errorPos + 1, 'EmptyLineLastParameterFunctionComment'); } // Parameters must appear immediately after the comment if ($params[0]->getOrder() !== 2) { $errorPos = $params[0]->getLine() + $commentStart; $this->_currentFile->addError("Parameters must appear immediately after the comment", $errorPos, 'ParameterAfterCommentFunctionComment'); } $previousParam = null; $spaceBeforeVar = 10000; $spaceBeforeComment = 10000; $longestType = 0; $longestVar = 0; if (count($this->_commentParser->getThrows()) !== 0) { $isSpecialMethod = false; } foreach ($params as $param) { $paramComment = trim($param->getComment()); $errorPos = $param->getLine() + $commentStart; if ($isSpecialMethod === true and $param->getWhitespaceBeforeType() !== ' ') { $this->_currentFile->addError("Expected 1 space before variable type", $errorPos, 'OneSpaceVariableFunctionComment'); } $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' '); if ($spaceCount < $spaceBeforeVar) { $spaceBeforeVar = $spaceCount; $longestType = $errorPos; } $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' '); if ($spaceCount < $spaceBeforeComment and $paramComment !== '') { $spaceBeforeComment = $spaceCount; $longestVar = $errorPos; } // 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) { $this->_currentFile->addError("The variable names for parameters {$previousName} (" . ($pos - 1) . ") and {$paramName} ({$pos}) do not align", $errorPos, 'VariablesNamesNotAlignFunctionComment'); } if ($param->alignsCommentWith($previousParam) === false) { $this->_currentFile->addError("The comments for parameters {$previousName} (" . ($pos - 1) . ") and {$paramName} ({$pos}) do not align", $errorPos, 'CommentsNotAlignFunctionComment'); } } // Variable must be one of the supported standard type $typeNames = explode('|', $param->getType()); foreach ($typeNames as $typeName) { $suggestedName = PHP_CodeSniffer::suggestType($typeName); if ($typeName !== $suggestedName) { $this->_currentFile->addError("Expected {$suggestedName} found {$typeName} for {$paramName} at position {$pos}", $errorPos, 'ExpectedFoundFunctionComment'); continue; } if (count($typeNames) !== 1) { continue; } // Check type hint for array and custom type $suggestedTypeHint = ''; if (strpos($suggestedName, 'array') !== false) { $suggestedTypeHint = 'array'; } else { if (in_array($typeName, PHP_CodeSniffer::$allowedTypes) === false) { $suggestedTypeHint = $suggestedName; } } if ($suggestedTypeHint !== '' and isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint === '') { $this->_currentFile->addError("Type hint {$suggestedTypeHint} missing for {$paramName} at position {$pos}", $commentEnd + 2, 'TypehintMissingFunctionComment'); } else { if ($typeHint !== $suggestedTypeHint) { $this->_currentFile->addError("Expected type hint {$suggestedTypeHint} found {$typeHint} for {$paramName} at position {$pos}", $commentEnd + 2, 'ExpectedTypehintFoundFunctionComment'); } } } else { if ($suggestedTypeHint === '' and isset($realParams[$pos - 1]) === true) { $typeHint = $realParams[$pos - 1]['type_hint']; if ($typeHint !== '') { $this->_currentFile->addError("Unknown type hint {$typeHint} found for {$paramName} at position {$pos}", $commentEnd + 2, 'UnknowTypehintFoundFunctionComment'); } } } } // 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 !== $param->getVarName()) { $this->_currentFile->addError("Doc comment var {$paramName} does not match actual variable name {$realName} at position {$pos}", $errorPos, 'DoccommentNotMatchFunctionComment'); } } else { // We must have an extra parameter comment $this->_currentFile->addError("Superfluous doc comment at position {$pos}", $errorPos, 'SuperfluousDoccommentFunctionComment'); } if ($param->getVarName() === '') { $this->_currentFile->addError("Missing parameter name at position {$pos}", $errorPos, 'MissingParameterFunctionComment'); } if ($param->getType() === '') { $this->_currentFile->addError("Missing type at position {$pos}", $errorPos, 'MissingTypeFunctionComment'); } if ($paramComment === '') { $this->_currentFile->addError("Missing comment for param {$paramName} at position {$pos}", $errorPos, 'MissingCommentParamFunctionComment'); } else { // Check if optional params include (Optional) within their description $functionBegin = $this->_currentFile->findNext(array(T_FUNCTION), $commentStart); $functionName = $this->_currentFile->findNext(array(T_STRING), $functionBegin); $openBracket = $this->_tokens[$functionBegin]['parenthesis_opener']; $closeBracket = $this->_tokens[$functionBegin]['parenthesis_closer']; $nextParam = $this->_currentFile->findNext(T_VARIABLE, $openBracket + 1, $closeBracket); while ($nextParam !== false) { $nextToken = $this->_currentFile->findNext(T_WHITESPACE, $nextParam + 1, $closeBracket + 1, true); if ($nextToken === false and $this->_tokens[$nextParam + 1]['code'] === T_CLOSE_PARENTHESIS) { break; } $nextCode = $this->_tokens[$nextToken]['code']; $arg = $this->_tokens[$nextParam]['content']; if ($nextCode === T_EQUAL and $paramName === $arg) { if (substr($paramComment, 0, 11) !== '(Optional) ') { $this->_currentFile->addError("Le commentaire pour le parametre {$paramName} doit commencer avec \"(Optional)\"", $errorPos, 'OptionalParamStartFunctionComment'); } } $nextParam = $this->_currentFile->findNext(T_VARIABLE, $nextParam + 1, $closeBracket); } } $previousParam = $param; } if ($spaceBeforeVar !== 1 and $spaceBeforeVar !== 10000 and $spaceBeforeComment !== 10000) { $this->_currentFile->addError("1 espace attendu après la définition du type pour les paramètres", $longestType, 'OneSpaceLongestTypeFunctionComment'); } if ($spaceBeforeComment !== 1 and $spaceBeforeComment !== 10000) { $this->_currentFile->addError("1 espace attendu après le nom de la variable pour les paramètres", $longestVar, 'OneSpaceLongestTypeFunctionComment'); } } $realNames = array(); foreach ($realParams as $realParam) { $realNames[] = $realParam['name']; } // 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; } $this->_currentFile->addError("Commentaire de fonction manquant ({$neededParam})", $errorPos, 'DoccommentMissingFunctionComment'); } }
/** * 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(); $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr + 1, null, true); if ($tokens[$next]['code'] !== T_STRING) { return; } $throwExists = isset($tokens[$stackPtr]['scope_closer']) ? $phpcsFile->findNext(T_THROW, $stackPtr + 1, $tokens[$stackPtr]['scope_closer'] - 1) : false; if (false === $throwExists) { if (isset($this->tags['throws'])) { unset($this->tags['throws']); } } else { $tags = $this->tags; $this->tags = array_slice($tags, 0, 2); $this->tags['throws'] = array('required' => true, 'allow_multiple' => true, 'order_text' => 'follows @return'); $this->tags += array_slice($tags, 2); } $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; // 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($this->getReqPrefix('REQ.PHP.4.5.6') . $error, $stackPtr); return; } else { if ($code !== T_DOC_COMMENT) { $error = 'Missing function doc comment'; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.5.1') . $error, $stackPtr); 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($this->getReqPrefix('REQ.PHP.4.5.1') . 'Missing function doc comment', $stackPtr); 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($this->getReqPrefix('REQ.PHP.4.5.1') . 'Missing function doc comment', $stackPtr); return; } } $comment = $phpcsFile->getTokensAsString($commentStart, $commentEnd - $commentStart + 1); $this->_methodName = $phpcsFile->getDeclarationName($stackPtr); try { $this->commentParser = new XLite_FunctionCommentParser($comment, $phpcsFile); $this->commentParser->parse(); } catch (PHP_CodeSniffer_CommentParser_ParserException $e) { $line = $e->getLineWithinComment() + $commentStart; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.1') . $e->getMessage(), $line); return; } $comment = $this->commentParser->getComment(); if (is_null($comment) === true) { $error = 'Function doc comment is empty'; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.5.2') . $error, $commentStart); return; } $this->checkAccess($stackPtr, $commentStart, $commentEnd); $this->processTags($commentStart, $commentEnd); // No extra newline before short description. $short = $comment->getShortComment(); $newlineCount = 0; $newlineSpan = strspn($short, $phpcsFile->eolChar); if ($short !== '' && $newlineSpan > 0) { $line = $newlineSpan > 1 ? 'newlines' : 'newline'; $error = "Extra {$line} found before function comment short description"; $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.7') . $error, $commentStart + 1); } $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($this->getReqPrefix('REQ.PHP.4.1.19') . $error, $commentStart + $newlineCount + 1); } $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; } $phpcsFile->addError($this->getReqPrefix('REQ.PHP.4.1.18') . $error, $commentStart + $newlineCount); $short = rtrim($short, $phpcsFile->eolChar . ' '); } } }