Completed
Pull Request — master (#39)
by Björn
03:41 queued 40s
created

FluentSetterSniff   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 232
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 8
dl 0
loc 232
ccs 68
cts 68
cp 1
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A checkAndRegisterEmptyReturnErrors() 0 17 4
A checkForFluentSetterErrors() 0 28 3
A getSniffName() 0 14 2
A processTokenWithinScope() 0 15 3
A checkIfSetterFunction() 0 18 2
A fixNoReturnFound() 0 13 1
A fixMustReturnThis() 0 15 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BestIt\Sniffs\Functions;
6
7
use BestIt\CodeSniffer\File as FileDecorator;
8
use BestIt\CodeSniffer\Helper\PropertyHelper;
9
use function in_array;
10
use PHP_CodeSniffer\Files\File;
11
use PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MethodScopeSniff;
12
use PHP_CodeSniffer\Util\Tokens;
13
use SlevomatCodingStandard\Helpers\SuppressHelper;
14
use SlevomatCodingStandard\Helpers\TokenHelper;
15
use function substr;
16
17
/**
18
 * Checks if a fluent setter is used per default.
19
 *
20
 * @package BestIt\Sniffs\Functions
21
 *
22
 * @author Nick Lubisch <[email protected]>
23
 * @author Björn Lange <[email protected]>
24
 */
25
class FluentSetterSniff extends MethodScopeSniff
26
{
27
    /**
28
     * Code when the method does not return $this.
29
     *
30
     * @var string
31
     */
32
    public const CODE_MUST_RETURN_THIS = 'MustReturnThis';
33
34
    /**
35
     * Code when no return statement is found.
36
     *
37
     * @var string
38
     */
39
    public const CODE_NO_RETURN_FOUND = 'NoReturnFound';
40
41
    /**
42
     * Error message when the method does not return $this.
43
     *
44
     * @var string
45
     */
46
    private const ERROR_MUST_RETURN_THIS = 'The method "%s" must return $this';
47
48
    /**
49
     * Error message when no return statement is found.
50
     *
51
     * @var string
52
     */
53
    private const ERROR_NO_RETURN_FOUND = 'Method "%s" has no return statement';
54
55
    /**
56
     * Specifies how an identation looks like.
57
     *
58
     * @var string
59
     */
60
    public $identation = '    ';
61
62
    /**
63
     * FluentSetterSniff constructor.
64
     */
65
    public function __construct()
66
    {
67
        parent::__construct(Tokens::$ooScopeTokens, [T_FUNCTION], false);
0 ignored issues
show
Unused Code introduced by
The call to MethodScopeSniff::__construct() has too many arguments starting with \PHP_CodeSniffer\Util\Tokens::$ooScopeTokens.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
68
    }
69
70
    /**
71 4
     * Registers an error if an empty return (return null; or return;) is given.
72
     *
73 4
     * @param File $file The sniffed file.
74 4
     * @param int $functionPos The position of the function.
75
     * @param int $returnPos The position of the return call.
76
     * @param string $methodIdent The ident for the method to given in an error.
77
     *
78
     * @return void
79
     */
80
    private function checkAndRegisterEmptyReturnErrors(File $file, int $functionPos, $returnPos, string $methodIdent): void
81
    {
82
        $nextToken = $file->getTokens()[TokenHelper::findNextEffective($file, $returnPos + 1)];
83
84
        if (!$nextToken || (in_array($nextToken['content'], ['null', ';']))) {
85 4
            $fixMustReturnThis = $file->addFixableError(
86
                self::ERROR_MUST_RETURN_THIS,
87
                $functionPos,
88
                self::CODE_MUST_RETURN_THIS,
89
                $methodIdent
0 ignored issues
show
Documentation introduced by
$methodIdent is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
90 4
            );
91 4
92
            if ($fixMustReturnThis) {
93 4
                $this->fixMustReturnThis($file, $returnPos);
94 1
            }
95
        }
96
    }
97 4
98 4
    /**
99
     * Checks if there are fluent setter errors and registers errors if needed.
100 4
     *
101 4
     * @param File $phpcsFile The file for this sniff.
102 4
     * @param int $functionPos The position of the used token.
103
     * @param int $classPos The position of the class.
104 4
     *
105
     * @return void
106 4
     */
107 1
    private function checkForFluentSetterErrors(File $phpcsFile, int $functionPos, int $classPos): void
108 1
    {
109 1
        $tokens = $phpcsFile->getTokens();
110 1
        $errorData = $phpcsFile->getDeclarationName($classPos) . '::' . $phpcsFile->getDeclarationName($functionPos);
111 1
112
        $functionToken = $tokens[$functionPos];
113
        $openBracePtr = $functionToken['scope_opener'];
114 1
        $closeBracePtr = $functionToken['scope_closer'];
115 1
116
        $returnPtr = $phpcsFile->findNext(T_RETURN, $openBracePtr, $closeBracePtr);
117
118 1
        if ($returnPtr === false) {
119
            $fixNoReturnFound = $phpcsFile->addFixableError(
120
                self::ERROR_NO_RETURN_FOUND,
121 4
                $functionPos,
122 4
                self::CODE_NO_RETURN_FOUND,
123 4
                $errorData
0 ignored issues
show
Documentation introduced by
$errorData is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
124 4
            );
125
126
            if ($fixNoReturnFound) {
127 4
                $this->fixNoReturnFound($phpcsFile, $closeBracePtr);
128 1
            }
129 1
130 1
            return;
131 1
        }
132 1
133
        $this->checkAndRegisterEmptyReturnErrors($phpcsFile, $functionPos, $returnPtr, $errorData);
134 1
    }
135
136
    /**
137 3
     * Get the sniff name.
138
     *
139 3
     * @param string $sniffName If there is an optional sniff name.
140 1
     *
141 1
     * @return string Returns the special sniff name in the code sniffer context.
142 1
     */
143 1
    private function getSniffName(string $sniffName = ''): string
144 1
    {
145
        $sniffFQCN = preg_replace(
146
            '/Sniff$/',
147 1
            '',
148 1
            str_replace(['\\', '.Sniffs'], ['.', ''], static::class)
149
        );
150
151 1
        if ($sniffName) {
152
            $sniffFQCN .= '.' . $sniffName;
153 3
        }
154
155
        return $sniffFQCN;
156
    }
157
158
    /**
159
     * Processes the tokens that this test is listening for.
160
     *
161
     * @param File $file The file where this token was found.
162
     * @param int $functionPos The position in the stack where this token was found.
163
     * @param int $classPos The position in the tokens array that opened the scope that this test is listening for.
164
     *
165
     * @return void
166 4
     */
167
    protected function processTokenWithinScope(
168 4
        File $file,
169
        $functionPos,
170 4
        $classPos
171
    ): void {
172
        $isSuppressed = SuppressHelper::isSniffSuppressed(
173
            $file,
174
            $functionPos,
175
            $this->getSniffName(static::CODE_NO_RETURN_FOUND)
176
        );
177
178
        if (!$isSuppressed && $this->checkIfSetterFunction($classPos, $file, $functionPos)) {
179
            $this->checkForFluentSetterErrors($file, $functionPos, $classPos);
180
        }
181 1
    }
182
183 1
    /**
184 1
     * Checks if the given method name relates to a setter function of a property.
185
     *
186 1
     * @param int $classPosition The position of the class token.
187
     * @param File $file The file of the sniff.
188 1
     * @param int $methodPosition The position of the method token.
189 1
     *
190 1
     * @return bool Indicator if the given method is a setter function
191 1
     */
192 1
    private function checkIfSetterFunction(int $classPosition, File $file, int $methodPosition): bool
193 1
    {
194
        $isSetter = false;
195
        $methodName = $file->getDeclarationName($methodPosition);
196
197
        if (substr($methodName, 0, 3) === 'set') {
198
            // We define in our styleguide, that there is only one class per file!
199
            $properties = (new PropertyHelper(new FileDecorator($file)))->getProperties(
200
                $file->getTokens()[$classPosition]
201
            );
202
203 1
            // We require camelCase for methods and properties,
204
            // so there should be an "lcfirst-Method" without set-prefix.
205 1
            $isSetter = in_array(lcfirst(substr($methodName, 3)), $properties, true);
206
        }
207 1
208 1
        return $isSetter;
209
    }
210
211 1
    /**
212 1
     * Fixes if no return statement is found.
213 1
     *
214 1
     * @param File $phpcsFile The php cs file
215
     * @param int $closingBracePtr Pointer to the closing curly brace of the function
216 1
     *
217 1
     * @return void
218
     */
219
    private function fixNoReturnFound(File $phpcsFile, int $closingBracePtr)
220
    {
221
        $tokens = $phpcsFile->getTokens();
222
        $closingBraceToken = $tokens[$closingBracePtr];
223
224
        $expectedReturnSpaces = str_repeat($this->identation, $closingBraceToken['level'] + 1);
225
226
        $phpcsFile->fixer->beginChangeset();
227
        $phpcsFile->fixer->addNewlineBefore($closingBracePtr - 1);
228
        $phpcsFile->fixer->addContentBefore($closingBracePtr - 1, $expectedReturnSpaces . 'return $this;');
229
        $phpcsFile->fixer->addNewlineBefore($closingBracePtr - 1);
230
        $phpcsFile->fixer->endChangeset();
231
    }
232
233
    /**
234
     * Fixes the return value of a function to $this.
235
     *
236
     * @param File $phpcsFile The php cs file
237
     * @param int $returnPtr Pointer to the return token
238
     *
239
     * @return void
240
     */
241
    private function fixMustReturnThis(File $phpcsFile, $returnPtr)
242
    {
243
        $returnSemicolonPtr = $phpcsFile->findEndOfStatement($returnPtr);
244
245
        for ($i = $returnPtr + 1; $i < $returnSemicolonPtr; $i++) {
246
            $phpcsFile->fixer->replaceToken($i, '');
247
        }
248
249
        $phpcsFile->fixer->beginChangeset();
250
        $phpcsFile->fixer->addContentBefore(
251
            $returnSemicolonPtr,
252
            ' $this'
253
        );
254
        $phpcsFile->fixer->endChangeset();
255
    }
256
}
257