PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/PEAR/Sniffs/Commenting/FunctionCommentSniff.php

https://gitlab.com/yousafsyed/easternglamor
PHP | 490 lines | 283 code | 82 blank | 125 comment | 53 complexity | 928221bb77c7ef3a80ada51e34a5b3dd MD5 | raw file
  1. <?php
  2. /**
  3. * Parses and verifies the doc comments for functions.
  4. *
  5. * PHP version 5
  6. *
  7. * @category PHP
  8. * @package PHP_CodeSniffer
  9. * @author Greg Sherwood <gsherwood@squiz.net>
  10. * @author Marc McIntyre <mmcintyre@squiz.net>
  11. * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
  12. * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
  13. * @link http://pear.php.net/package/PHP_CodeSniffer
  14. */
  15. if (class_exists('PHP_CodeSniffer_CommentParser_FunctionCommentParser', true) === false) {
  16. throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_CommentParser_FunctionCommentParser not found');
  17. }
  18. /**
  19. * Parses and verifies the doc comments for functions.
  20. *
  21. * Verifies that :
  22. * <ul>
  23. * <li>A comment exists</li>
  24. * <li>There is a blank newline after the short description.</li>
  25. * <li>There is a blank newline between the long and short description.</li>
  26. * <li>There is a blank newline between the long description and tags.</li>
  27. * <li>Parameter names represent those in the method.</li>
  28. * <li>Parameter comments are in the correct order</li>
  29. * <li>Parameter comments are complete</li>
  30. * <li>A space is present before the first and after the last parameter</li>
  31. * <li>A return type exists</li>
  32. * <li>There must be one blank line between body and headline comments.</li>
  33. * <li>Any throw tag must have an exception class.</li>
  34. * </ul>
  35. *
  36. * @category PHP
  37. * @package PHP_CodeSniffer
  38. * @author Greg Sherwood <gsherwood@squiz.net>
  39. * @author Marc McIntyre <mmcintyre@squiz.net>
  40. * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
  41. * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
  42. * @version Release: @package_version@
  43. * @link http://pear.php.net/package/PHP_CodeSniffer
  44. */
  45. class PEAR_Sniffs_Commenting_FunctionCommentSniff implements PHP_CodeSniffer_Sniff
  46. {
  47. /**
  48. * The name of the method that we are currently processing.
  49. *
  50. * @var string
  51. */
  52. private $_methodName = '';
  53. /**
  54. * The position in the stack where the function token was found.
  55. *
  56. * @var int
  57. */
  58. private $_functionToken = null;
  59. /**
  60. * The position in the stack where the class token was found.
  61. *
  62. * @var int
  63. */
  64. private $_classToken = null;
  65. /**
  66. * The function comment parser for the current method.
  67. *
  68. * @var PHP_CodeSniffer_Comment_Parser_FunctionCommentParser
  69. */
  70. protected $commentParser = null;
  71. /**
  72. * The current PHP_CodeSniffer_File object we are processing.
  73. *
  74. * @var PHP_CodeSniffer_File
  75. */
  76. protected $currentFile = null;
  77. /**
  78. * Returns an array of tokens this test wants to listen for.
  79. *
  80. * @return array
  81. */
  82. public function register()
  83. {
  84. return array(T_FUNCTION);
  85. }//end register()
  86. /**
  87. * Processes this test, when one of its tokens is encountered.
  88. *
  89. * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  90. * @param int $stackPtr The position of the current token
  91. * in the stack passed in $tokens.
  92. *
  93. * @return void
  94. */
  95. public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
  96. {
  97. $find = array(
  98. T_COMMENT,
  99. T_DOC_COMMENT,
  100. T_CLASS,
  101. T_FUNCTION,
  102. T_OPEN_TAG,
  103. );
  104. $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1));
  105. if ($commentEnd === false) {
  106. return;
  107. }
  108. $this->currentFile = $phpcsFile;
  109. $tokens = $phpcsFile->getTokens();
  110. // If the token that we found was a class or a function, then this
  111. // function has no doc comment.
  112. $code = $tokens[$commentEnd]['code'];
  113. if ($code === T_COMMENT) {
  114. $error = 'You must use "/**" style comments for a function comment';
  115. $phpcsFile->addError($error, $stackPtr, 'WrongStyle');
  116. return;
  117. } else if ($code !== T_DOC_COMMENT) {
  118. $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing');
  119. return;
  120. }
  121. // If there is any code between the function keyword and the doc block
  122. // then the doc block is not for us.
  123. $ignore = PHP_CodeSniffer_Tokens::$scopeModifiers;
  124. $ignore[] = T_STATIC;
  125. $ignore[] = T_WHITESPACE;
  126. $ignore[] = T_ABSTRACT;
  127. $ignore[] = T_FINAL;
  128. $prevToken = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true);
  129. if ($prevToken !== $commentEnd) {
  130. $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing');
  131. return;
  132. }
  133. $this->_functionToken = $stackPtr;
  134. $this->_classToken = null;
  135. foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condition) {
  136. if ($condition === T_CLASS || $condition === T_INTERFACE) {
  137. $this->_classToken = $condPtr;
  138. break;
  139. }
  140. }
  141. // If the first T_OPEN_TAG is right before the comment, it is probably
  142. // a file comment.
  143. $commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1);
  144. $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($commentStart - 1), null, true);
  145. if ($tokens[$prevToken]['code'] === T_OPEN_TAG) {
  146. // Is this the first open tag?
  147. if ($stackPtr === 0 || $phpcsFile->findPrevious(T_OPEN_TAG, ($prevToken - 1)) === false) {
  148. $phpcsFile->addError('Missing function doc comment', $stackPtr, 'Missing');
  149. return;
  150. }
  151. }
  152. $comment = $phpcsFile->getTokensAsString($commentStart, ($commentEnd - $commentStart + 1));
  153. $this->_methodName = $phpcsFile->getDeclarationName($stackPtr);
  154. try {
  155. $this->commentParser = new PHP_CodeSniffer_CommentParser_FunctionCommentParser($comment, $phpcsFile);
  156. $this->commentParser->parse();
  157. } catch (PHP_CodeSniffer_CommentParser_ParserException $e) {
  158. $line = ($e->getLineWithinComment() + $commentStart);
  159. $phpcsFile->addError($e->getMessage(), $line, 'FailedParse');
  160. return;
  161. }
  162. $comment = $this->commentParser->getComment();
  163. if (is_null($comment) === true) {
  164. $error = 'Function doc comment is empty';
  165. $phpcsFile->addError($error, $commentStart, 'Empty');
  166. return;
  167. }
  168. $this->processParams($commentStart);
  169. $this->processReturn($commentStart, $commentEnd);
  170. $this->processThrows($commentStart);
  171. // No extra newline before short description.
  172. $short = $comment->getShortComment();
  173. $newlineCount = 0;
  174. $newlineSpan = strspn($short, $phpcsFile->eolChar);
  175. if ($short !== '' && $newlineSpan > 0) {
  176. $error = 'Extra newline(s) found before function comment short description';
  177. $phpcsFile->addError($error, ($commentStart + 1), 'SpacingBeforeShort');
  178. }
  179. $newlineCount = (substr_count($short, $phpcsFile->eolChar) + 1);
  180. // Exactly one blank line between short and long description.
  181. $long = $comment->getLongComment();
  182. if (empty($long) === false) {
  183. $between = $comment->getWhiteSpaceBetween();
  184. $newlineBetween = substr_count($between, $phpcsFile->eolChar);
  185. if ($newlineBetween !== 2) {
  186. $error = 'There must be exactly one blank line between descriptions in function comment';
  187. $phpcsFile->addError($error, ($commentStart + $newlineCount + 1), 'SpacingAfterShort');
  188. }
  189. $newlineCount += $newlineBetween;
  190. }
  191. // Exactly one blank line before tags.
  192. $params = $this->commentParser->getTagOrders();
  193. if (count($params) > 1) {
  194. $newlineSpan = $comment->getNewlineAfter();
  195. if ($newlineSpan !== 2) {
  196. $error = 'There must be exactly one blank line before the tags in function comment';
  197. if ($long !== '') {
  198. $newlineCount += (substr_count($long, $phpcsFile->eolChar) - $newlineSpan + 1);
  199. }
  200. $phpcsFile->addError($error, ($commentStart + $newlineCount), 'SpacingBeforeTags');
  201. $short = rtrim($short, $phpcsFile->eolChar.' ');
  202. }
  203. }
  204. }//end process()
  205. /**
  206. * Process any throw tags that this function comment has.
  207. *
  208. * @param int $commentStart The position in the stack where the
  209. * comment started.
  210. *
  211. * @return void
  212. */
  213. protected function processThrows($commentStart)
  214. {
  215. if (count($this->commentParser->getThrows()) === 0) {
  216. return;
  217. }
  218. foreach ($this->commentParser->getThrows() as $throw) {
  219. $exception = $throw->getValue();
  220. $errorPos = ($commentStart + $throw->getLine());
  221. if ($exception === '') {
  222. $error = '@throws tag must contain the exception class name';
  223. $this->currentFile->addError($error, $errorPos, 'EmptyThrows');
  224. }
  225. }
  226. }//end processThrows()
  227. /**
  228. * Process the return comment of this function comment.
  229. *
  230. * @param int $commentStart The position in the stack where the comment started.
  231. * @param int $commentEnd The position in the stack where the comment ended.
  232. *
  233. * @return void
  234. */
  235. protected function processReturn($commentStart, $commentEnd)
  236. {
  237. // Skip constructor and destructor.
  238. $className = '';
  239. if ($this->_classToken !== null) {
  240. $className = $this->currentFile->getDeclarationName($this->_classToken);
  241. $className = strtolower(ltrim($className, '_'));
  242. }
  243. $methodName = strtolower(ltrim($this->_methodName, '_'));
  244. $isSpecialMethod = ($this->_methodName === '__construct' || $this->_methodName === '__destruct');
  245. if ($isSpecialMethod === false && $methodName !== $className) {
  246. // Report missing return tag.
  247. if ($this->commentParser->getReturn() === null) {
  248. $error = 'Missing @return tag in function comment';
  249. $this->currentFile->addError($error, $commentEnd, 'MissingReturn');
  250. } else if (trim($this->commentParser->getReturn()->getRawContent()) === '') {
  251. $error = '@return tag is empty in function comment';
  252. $errorPos = ($commentStart + $this->commentParser->getReturn()->getLine());
  253. $this->currentFile->addError($error, $errorPos, 'EmptyReturn');
  254. }
  255. }
  256. }//end processReturn()
  257. /**
  258. * Process the function parameter comments.
  259. *
  260. * @param int $commentStart The position in the stack where
  261. * the comment started.
  262. *
  263. * @return void
  264. */
  265. protected function processParams($commentStart)
  266. {
  267. $realParams = $this->currentFile->getMethodParameters($this->_functionToken);
  268. $params = $this->commentParser->getParams();
  269. $foundParams = array();
  270. if (empty($params) === false) {
  271. $lastParm = (count($params) - 1);
  272. if (substr_count($params[$lastParm]->getWhitespaceAfter(), $this->currentFile->eolChar) !== 2) {
  273. $error = 'Last parameter comment requires a blank newline after it';
  274. $errorPos = ($params[$lastParm]->getLine() + $commentStart);
  275. $this->currentFile->addError($error, $errorPos, 'SpacingAfterParams');
  276. }
  277. // Parameters must appear immediately after the comment.
  278. if ($params[0]->getOrder() !== 2) {
  279. $error = 'Parameters must appear immediately after the comment';
  280. $errorPos = ($params[0]->getLine() + $commentStart);
  281. $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParams');
  282. }
  283. $previousParam = null;
  284. $spaceBeforeVar = 10000;
  285. $spaceBeforeComment = 10000;
  286. $longestType = 0;
  287. $longestVar = 0;
  288. foreach ($params as $param) {
  289. $paramComment = trim($param->getComment());
  290. $errorPos = ($param->getLine() + $commentStart);
  291. // Make sure that there is only one space before the var type.
  292. if ($param->getWhitespaceBeforeType() !== ' ') {
  293. $error = 'Expected 1 space before variable type';
  294. $this->currentFile->addError($error, $errorPos, 'SpacingBeforeParamType');
  295. }
  296. $spaceCount = substr_count($param->getWhitespaceBeforeVarName(), ' ');
  297. if ($spaceCount < $spaceBeforeVar) {
  298. $spaceBeforeVar = $spaceCount;
  299. $longestType = $errorPos;
  300. }
  301. $spaceCount = substr_count($param->getWhitespaceBeforeComment(), ' ');
  302. if ($spaceCount < $spaceBeforeComment && $paramComment !== '') {
  303. $spaceBeforeComment = $spaceCount;
  304. $longestVar = $errorPos;
  305. }
  306. // Make sure they are in the correct order,
  307. // and have the correct name.
  308. $pos = $param->getPosition();
  309. $paramName = ($param->getVarName() !== '') ? $param->getVarName() : '[ UNKNOWN ]';
  310. if ($previousParam !== null) {
  311. $previousName = ($previousParam->getVarName() !== '') ? $previousParam->getVarName() : 'UNKNOWN';
  312. // Check to see if the parameters align properly.
  313. if ($param->alignsVariableWith($previousParam) === false) {
  314. $error = 'The variable names for parameters %s (%s) and %s (%s) do not align';
  315. $data = array(
  316. $previousName,
  317. ($pos - 1),
  318. $paramName,
  319. $pos,
  320. );
  321. $this->currentFile->addError($error, $errorPos, 'ParameterNamesNotAligned', $data);
  322. }
  323. if ($param->alignsCommentWith($previousParam) === false) {
  324. $error = 'The comments for parameters %s (%s) and %s (%s) do not align';
  325. $data = array(
  326. $previousName,
  327. ($pos - 1),
  328. $paramName,
  329. $pos,
  330. );
  331. $this->currentFile->addError($error, $errorPos, 'ParameterCommentsNotAligned', $data);
  332. }
  333. }//end if
  334. // Make sure the names of the parameter comment matches the
  335. // actual parameter.
  336. if (isset($realParams[($pos - 1)]) === true) {
  337. $realName = $realParams[($pos - 1)]['name'];
  338. $foundParams[] = $realName;
  339. // Append ampersand to name if passing by reference.
  340. if ($realParams[($pos - 1)]['pass_by_reference'] === true) {
  341. $realName = '&'.$realName;
  342. }
  343. if ($realName !== $paramName) {
  344. $code = 'ParamNameNoMatch';
  345. $data = array(
  346. $paramName,
  347. $realName,
  348. $pos,
  349. );
  350. $error = 'Doc comment for var %s does not match ';
  351. if (strtolower($paramName) === strtolower($realName)) {
  352. $error .= 'case of ';
  353. $code = 'ParamNameNoCaseMatch';
  354. }
  355. $error .= 'actual variable name %s at position %s';
  356. $this->currentFile->addError($error, $errorPos, $code, $data);
  357. }
  358. } else {
  359. // We must have an extra parameter comment.
  360. $error = 'Superfluous doc comment at position '.$pos;
  361. $this->currentFile->addError($error, $errorPos, 'ExtraParamComment');
  362. }
  363. if ($param->getVarName() === '') {
  364. $error = 'Missing parameter name at position '.$pos;
  365. $this->currentFile->addError($error, $errorPos, 'MissingParamName');
  366. }
  367. if ($param->getType() === '') {
  368. $error = 'Missing type at position '.$pos;
  369. $this->currentFile->addError($error, $errorPos, 'MissingParamType');
  370. }
  371. if ($paramComment === '') {
  372. $error = 'Missing comment for param "%s" at position %s';
  373. $data = array(
  374. $paramName,
  375. $pos,
  376. );
  377. $this->currentFile->addError($error, $errorPos, 'MissingParamComment', $data);
  378. }
  379. $previousParam = $param;
  380. }//end foreach
  381. if ($spaceBeforeVar !== 1 && $spaceBeforeVar !== 10000 && $spaceBeforeComment !== 10000) {
  382. $error = 'Expected 1 space after the longest type';
  383. $this->currentFile->addError($error, $longestType, 'SpacingAfterLongType');
  384. }
  385. if ($spaceBeforeComment !== 1 && $spaceBeforeComment !== 10000) {
  386. $error = 'Expected 1 space after the longest variable name';
  387. $this->currentFile->addError($error, $longestVar, 'SpacingAfterLongName');
  388. }
  389. }//end if
  390. $realNames = array();
  391. foreach ($realParams as $realParam) {
  392. $realNames[] = $realParam['name'];
  393. }
  394. // Report and missing comments.
  395. $diff = array_diff($realNames, $foundParams);
  396. foreach ($diff as $neededParam) {
  397. if (count($params) !== 0) {
  398. $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart);
  399. } else {
  400. $errorPos = $commentStart;
  401. }
  402. $error = 'Doc comment for "%s" missing';
  403. $data = array($neededParam);
  404. $this->currentFile->addError($error, $errorPos, 'MissingParamTag', $data);
  405. }
  406. }//end processParams()
  407. }//end class
  408. ?>