Skip to content

Commit d74cb03

Browse files
committed
Rename NoSetterSniff to NoAccessorsSniff
and warn for getters as well.
1 parent ee9bd86 commit d74cb03

File tree

2 files changed

+80
-66
lines changed

2 files changed

+80
-66
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<?php declare(strict_types=1); # -*- coding: utf-8 -*-
2+
/*
3+
* This file is part of the php-coding-standards package.
4+
*
5+
* (c) Inpsyde GmbH
6+
*
7+
* For the full copyright and license information, please view the LICENSE
8+
* file that was distributed with this source code.
9+
*
10+
* This file contains code from "phpcs-calisthenics-rules" repository
11+
* found at https://github.com/object-calisthenics
12+
* Copyright (c) 2014 Doctrine Project
13+
* released under MIT license.
14+
*/
15+
16+
namespace Inpsyde\InpsydeCodingStandard\Sniffs\CodeQuality;
17+
18+
use Inpsyde\InpsydeCodingStandard\Helpers;
19+
use PHP_CodeSniffer\Files\File;
20+
use PHP_CodeSniffer\Sniffs\Sniff;
21+
22+
/**
23+
* @package php-coding-standards
24+
* @license http://opensource.org/licenses/MIT MIT
25+
*/
26+
final class NoAccessorsSniff implements Sniff
27+
{
28+
public $allowSetUp = true;
29+
30+
public $skipForFunctions = true;
31+
32+
/**
33+
* @return int[]
34+
*/
35+
public function register()
36+
{
37+
return [T_FUNCTION];
38+
}
39+
40+
/**
41+
* @param File $file
42+
* @param int $position
43+
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException
44+
*/
45+
public function process(File $file, $position)
46+
{
47+
if ($this->skipForFunctions && !Helpers::functionIsMethod($file, $position)) {
48+
return;
49+
}
50+
51+
$functionName = $file->getDeclarationName($position);
52+
53+
if (!$functionName || ($functionName === 'setUp' && $this->allowSetUp)) {
54+
return;
55+
}
56+
57+
preg_match('/^(set|get)[a-zA-Z0-9_\x7f-\xff]+/', $functionName, $matches);
58+
if (!$matches) {
59+
return;
60+
}
61+
62+
if ($matches[1] === 'set') {
63+
$file->addWarning(
64+
'Setters are discouraged. Try to use immutable objects, constructor injection '
65+
. 'and for objects that really needs changing state try behavior naming instead, '
66+
. 'e.g. changeName() instead of setName().',
67+
$position,
68+
'NoSetter'
69+
);
70+
}
71+
72+
$file->addWarning(
73+
'Getters are discouraged. "Tell Don\'t Ask" principle should be applied if possible, '
74+
. 'and if getters are really needed consider naming methods after properties, '
75+
. 'e.g. name() instead of getName().',
76+
$position,
77+
'NoGetter'
78+
);
79+
}
80+
}

Inpsyde/Sniffs/CodeQuality/NoSetterSniff.php

Lines changed: 0 additions & 66 deletions
This file was deleted.

0 commit comments

Comments
 (0)