|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +namespace Magento2\Sniffs\Commenting; |
| 7 | + |
| 8 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 9 | +use PHP_CodeSniffer\Files\File; |
| 10 | + |
| 11 | +/** |
| 12 | + * Detects PHPDoc formatting for constants. |
| 13 | + */ |
| 14 | +class ConstantsPHPDocFormattingSniff implements Sniff |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @inheritDoc |
| 18 | + */ |
| 19 | + public function register() |
| 20 | + { |
| 21 | + return [ |
| 22 | + T_CONST, |
| 23 | + T_STRING |
| 24 | + ]; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * @inheritDoc |
| 29 | + */ |
| 30 | + public function process(File $phpcsFile, $stackPtr) |
| 31 | + { |
| 32 | + $tokens = $phpcsFile->getTokens(); |
| 33 | + |
| 34 | + if ($tokens[$stackPtr]['code'] != T_CONST |
| 35 | + && !($tokens[$stackPtr]['content'] == 'define' && $tokens[$stackPtr+1]['code'] == T_OPEN_PARENTHESIS) |
| 36 | + ) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + $constNamePtr = $phpcsFile->findNext( |
| 41 | + ($tokens[$stackPtr]['code'] === T_CONST) ? T_STRING : T_CONSTANT_ENCAPSED_STRING, |
| 42 | + $stackPtr + 1, |
| 43 | + null, |
| 44 | + false, |
| 45 | + null, |
| 46 | + true |
| 47 | + ); |
| 48 | + $constName = strtolower(trim($tokens[$constNamePtr]['content'], " '\"")); |
| 49 | + |
| 50 | + $commentStartPtr = $phpcsFile->findPrevious(T_DOC_COMMENT_OPEN_TAG, $stackPtr - 1, null, false, null, true); |
| 51 | + if ($commentStartPtr === false) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + $commentCloserPtr = $tokens[$commentStartPtr]['comment_closer']; |
| 56 | + for ($i = $commentStartPtr; $i <= $commentCloserPtr; $i++) { |
| 57 | + $token = $tokens[$i]; |
| 58 | + |
| 59 | + // Not an interesting string |
| 60 | + if ($token['code'] !== T_DOC_COMMENT_STRING) { |
| 61 | + continue; |
| 62 | + } |
| 63 | + |
| 64 | + // Comment is the same as constant name |
| 65 | + $docComment = trim(strtolower($token['content']), ',.'); |
| 66 | + if ($docComment === $constName) { |
| 67 | + continue; |
| 68 | + } |
| 69 | + |
| 70 | + // Comment is exactly the same as constant name |
| 71 | + $docComment = str_replace(' ', '_', $docComment); |
| 72 | + if ($docComment === $constName) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + // We have found at lease one meaningful line in comment description |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + $phpcsFile->addWarning( |
| 81 | + 'Constants must have short description if they add information beyond what the constant name supplies.', |
| 82 | + $stackPtr, |
| 83 | + 'MissingConstantPHPDoc' |
| 84 | + ); |
| 85 | + } |
| 86 | +} |
0 commit comments