Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 20 | final class MethodCommentSniff implements PHP_CodeSniffer_Sniff |
||
| 21 | { |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @var string |
||
| 25 | */ |
||
| 26 | const NAME = 'ZenifyCodingStandard.Commenting.MethodComment'; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * @return int[] |
||
| 30 | */ |
||
| 31 | 1 | public function register() : array |
|
| 32 | { |
||
| 33 | 1 | return [T_FUNCTION]; |
|
| 34 | } |
||
| 35 | |||
| 36 | |||
| 37 | /** |
||
| 38 | * @param PHP_CodeSniffer_File $file |
||
| 39 | * @param int $position |
||
| 40 | */ |
||
| 41 | 1 | public function process(PHP_CodeSniffer_File $file, $position) |
|
| 42 | { |
||
| 43 | 1 | if ($this->hasMethodDocblock($file, $position)) { |
|
| 44 | 1 | return; |
|
| 45 | } |
||
| 46 | |||
| 47 | 1 | $parameters = $file->getMethodParameters($position); |
|
| 48 | 1 | $parameterCount = count($parameters); |
|
| 49 | |||
| 50 | // 1. method has no parameters |
||
| 51 | 1 | if ($parameterCount === 0) { |
|
| 52 | 1 | return; |
|
| 53 | } |
||
| 54 | |||
| 55 | // 2. all methods have typehints |
||
| 56 | 1 | if ($parameterCount === $this->countParametersWithTypehint($parameters)) { |
|
| 57 | 1 | return; |
|
| 58 | } |
||
| 59 | |||
| 60 | 1 | $file->addError('Method docblock is missing, due to some parameters without typehints.', $position); |
|
| 61 | 1 | } |
|
| 62 | |||
| 63 | |||
| 64 | 1 | View Code Duplication | private function hasMethodDocblock(PHP_CodeSniffer_File $file, int $position) : bool |
| 65 | { |
||
| 66 | 1 | $tokens = $file->getTokens(); |
|
| 67 | 1 | $currentToken = $tokens[$position]; |
|
| 68 | 1 | $docBlockClosePosition = $file->findPrevious(T_DOC_COMMENT_CLOSE_TAG, $position); |
|
| 69 | |||
| 70 | 1 | if ($docBlockClosePosition === FALSE) { |
|
| 71 | 1 | return FALSE; |
|
| 72 | } |
||
| 73 | |||
| 74 | 1 | $docBlockCloseToken = $tokens[$docBlockClosePosition]; |
|
| 75 | 1 | if ($docBlockCloseToken['line'] === ($currentToken['line'] - 1)) { |
|
| 76 | 1 | return TRUE; |
|
| 77 | } |
||
| 78 | |||
| 79 | return FALSE; |
||
| 80 | } |
||
| 81 | |||
| 82 | |||
| 83 | 1 | private function countParametersWithTypehint(array $parameters) : int |
|
| 93 | |||
| 94 | } |
||
| 95 |