Completed
Pull Request — master (#39)
by Björn
05:06 queued 01:58
created

FluentSetterSniff::checkForFluentSetterErrors()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 16
cts 16
cp 1
rs 9.472
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 3
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(
81
        File $file,
82
        int $functionPos,
83
        int $returnPos,
84
        string $methodIdent
85 4
    ): void {
86
        $nextToken = $file->getTokens()[TokenHelper::findNextEffective($file, $returnPos + 1)];
87
88
        if (!$nextToken || (in_array($nextToken['content'], ['null', ';']))) {
89
            $fixMustReturnThis = $file->addFixableError(
90 4
                self::ERROR_MUST_RETURN_THIS,
91 4
                $functionPos,
92
                self::CODE_MUST_RETURN_THIS,
93 4
                $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...
94 1
            );
95
96
            if ($fixMustReturnThis) {
97 4
                $this->fixMustReturnThis($file, $returnPos);
98 4
            }
99
        }
100 4
    }
101 4
102 4
    /**
103
     * Checks if there are fluent setter errors and registers errors if needed.
104 4
     *
105
     * @param File $phpcsFile The file for this sniff.
106 4
     * @param int $functionPos The position of the used token.
107 1
     * @param int $classPos The position of the class.
108 1
     *
109 1
     * @return void
110 1
     */
111 1
    private function checkForFluentSetterErrors(File $phpcsFile, int $functionPos, int $classPos): void
112
    {
113
        $tokens = $phpcsFile->getTokens();
114 1
        $errorData = $phpcsFile->getDeclarationName($classPos) . '::' . $phpcsFile->getDeclarationName($functionPos);
115 1
116
        $functionToken = $tokens[$functionPos];
117
        $openBracePtr = $functionToken['scope_opener'];
118 1
        $closeBracePtr = $functionToken['scope_closer'];
119
120
        $returnPtr = $phpcsFile->findNext(T_RETURN, $openBracePtr, $closeBracePtr);
121 4
122 4
        if ($returnPtr === false) {
123 4
            $fixNoReturnFound = $phpcsFile->addFixableError(
124 4
                self::ERROR_NO_RETURN_FOUND,
125
                $functionPos,
126
                self::CODE_NO_RETURN_FOUND,
127 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...
128 1
            );
129 1
130 1
            if ($fixNoReturnFound) {
131 1
                $this->fixNoReturnFound($phpcsFile, $closeBracePtr);
132 1
            }
133
134 1
            return;
135
        }
136
137 3
        $this->checkAndRegisterEmptyReturnErrors($phpcsFile, $functionPos, $returnPtr, $errorData);
138
    }
139 3
140 1
    /**
141 1
     * Get the sniff name.
142 1
     *
143 1
     * @param string $sniffName If there is an optional sniff name.
144 1
     *
145
     * @return string Returns the special sniff name in the code sniffer context.
146
     */
147 1
    private function getSniffName(string $sniffName = ''): string
148 1
    {
149
        $sniffFQCN = preg_replace(
150
            '/Sniff$/',
151 1
            '',
152
            str_replace(['\\', '.Sniffs'], ['.', ''], static::class)
153 3
        );
154
155
        if ($sniffName) {
156
            $sniffFQCN .= '.' . $sniffName;
157
        }
158
159
        return $sniffFQCN;
160
    }
161
162
    /**
163
     * Processes the tokens that this test is listening for.
164
     *
165
     * @param File $file The file where this token was found.
166 4
     * @param int $functionPos The position in the stack where this token was found.
167
     * @param int $classPos The position in the tokens array that opened the scope that this test is listening for.
168 4
     *
169
     * @return void
170 4
     */
171
    protected function processTokenWithinScope(
172
        File $file,
173
        $functionPos,
174
        $classPos
175
    ): void {
176
        $isSuppressed = SuppressHelper::isSniffSuppressed(
177
            $file,
178
            $functionPos,
179
            $this->getSniffName(static::CODE_NO_RETURN_FOUND)
180
        );
181 1
182
        if (!$isSuppressed && $this->checkIfSetterFunction($classPos, $file, $functionPos)) {
183 1
            $this->checkForFluentSetterErrors($file, $functionPos, $classPos);
184 1
        }
185
    }
186 1
187
    /**
188 1
     * Checks if the given method name relates to a setter function of a property.
189 1
     *
190 1
     * @param int $classPosition The position of the class token.
191 1
     * @param File $file The file of the sniff.
192 1
     * @param int $methodPosition The position of the method token.
193 1
     *
194
     * @return bool Indicator if the given method is a setter function
195
     */
196
    private function checkIfSetterFunction(int $classPosition, File $file, int $methodPosition): bool
197
    {
198
        $isSetter = false;
199
        $methodName = $file->getDeclarationName($methodPosition);
200
201
        if (substr($methodName, 0, 3) === 'set') {
202
            // We define in our styleguide, that there is only one class per file!
203 1
            $properties = (new PropertyHelper(new FileDecorator($file)))->getProperties(
204
                $file->getTokens()[$classPosition]
205 1
            );
206
207 1
            // We require camelCase for methods and properties,
208 1
            // so there should be an "lcfirst-Method" without set-prefix.
209
            $isSetter = in_array(lcfirst(substr($methodName, 3)), $properties, true);
210
        }
211 1
212 1
        return $isSetter;
213 1
    }
214 1
215
    /**
216 1
     * Fixes if no return statement is found.
217 1
     *
218
     * @param File $phpcsFile The php cs file
219
     * @param int $closingBracePtr Pointer to the closing curly brace of the function
220
     *
221
     * @return void
222
     */
223
    private function fixNoReturnFound(File $phpcsFile, int $closingBracePtr)
224
    {
225
        $tokens = $phpcsFile->getTokens();
226
        $closingBraceToken = $tokens[$closingBracePtr];
227
228
        $expectedReturnSpaces = str_repeat($this->identation, $closingBraceToken['level'] + 1);
229
230
        $phpcsFile->fixer->beginChangeset();
231
        $phpcsFile->fixer->addNewlineBefore($closingBracePtr - 1);
232
        $phpcsFile->fixer->addContentBefore($closingBracePtr - 1, $expectedReturnSpaces . 'return $this;');
233
        $phpcsFile->fixer->addNewlineBefore($closingBracePtr - 1);
234
        $phpcsFile->fixer->endChangeset();
235
    }
236
237
    /**
238
     * Fixes the return value of a function to $this.
239
     *
240
     * @param File $phpcsFile The php cs file
241
     * @param int $returnPtr Pointer to the return token
242
     *
243
     * @return void
244
     */
245
    private function fixMustReturnThis(File $phpcsFile, $returnPtr)
246
    {
247
        $returnSemicolonPtr = $phpcsFile->findEndOfStatement($returnPtr);
248
249
        for ($i = $returnPtr + 1; $i < $returnSemicolonPtr; $i++) {
250
            $phpcsFile->fixer->replaceToken($i, '');
251
        }
252
253
        $phpcsFile->fixer->beginChangeset();
254
        $phpcsFile->fixer->addContentBefore(
255
            $returnSemicolonPtr,
256
            ' $this'
257
        );
258
        $phpcsFile->fixer->endChangeset();
259
    }
260
}
261