/
NoSetterSniff.php
47 lines (39 loc) · 1.16 KB
/
NoSetterSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php declare(strict_types=1);
namespace ObjectCalisthenics\Sniffs\NamingConventions;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
final class NoSetterSniff implements Sniff
{
/**
* @var string
*/
private const ERROR_MESSAGE = 'Setters are not allowed. Use constructor injection and'
. ' behavior naming instead, e.g. changeName() instead of setName().';
/**
* @var string
*/
private const SETTER_REGEX = '/^set[A-Z0-9]/';
public function register(): array
{
return [T_FUNCTION];
}
/**
* @param File $file
* @param int $position
*/
public function process(File $file, $position): void
{
$declarationName = $file->getDeclarationName($position);
if ($declarationName === null) {
return;
}
if ($this->methodNameStartsWithSet($declarationName)) {
$file->addError(self::ERROR_MESSAGE, $position, self::class);
}
}
private function methodNameStartsWithSet(string $methodName): bool
{
return $methodName !== 'setUp'
&& preg_match(self::SETTER_REGEX, $methodName) === 1;
}
}