Skip to content

Commit cc2b385

Browse files
author
Lars Roettig
committed
#26: Add Sniff for Getters not change state
1 parent 230d2ad commit cc2b385

File tree

3 files changed

+34
-6
lines changed

3 files changed

+34
-6
lines changed

Magento/Sniffs/Functions/GetterStateSniff.php

+13-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,19 @@ public function process(File $phpcsFile, $stackPtr)
7474
}
7575

7676
if ($isObjectScope === true && array_key_exists($token['code'], Tokens::$assignmentTokens)) {
77-
$phpcsFile->addWarning($this->warningMessage, $i, $this->warningCode);
77+
78+
$isWrappedByIf = false;
79+
// Detect if the property warped by an if tag.
80+
$ifTag = $phpcsFile->findPrevious(T_IF, $i);
81+
if ($ifTag !== false) {
82+
$open = $tokens[$ifTag]['scope_opener'];
83+
$close = $tokens[$ifTag]['scope_closer'];
84+
$isWrappedByIf = $open <= $i && $close >= $i;
85+
}
86+
87+
if ($isWrappedByIf === false) {
88+
$phpcsFile->addWarning($this->warningMessage, $i, $this->warningCode);
89+
}
7890
}
7991
}
8092
}

Magento/Tests/Functions/GetterStateUnitTest.inc

+20-4
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
namespace Foo\Bar;
44

55

6-
abstract class Bar{
7-
8-
public static $foobar = 100;
6+
abstract class Bar
7+
{
8+
public static $foobar = 100;
99
}
1010

1111
class Foo extends Bar
@@ -36,11 +36,27 @@ class Foo extends Bar
3636
*/
3737
public function getProperty()
3838
{
39+
if (true) {
40+
41+
}
42+
3943
$this->property = 1223;
4044
return $this->property;
4145
}
4246

43-
public function TestigetFoo()
47+
/**
48+
* @return int
49+
*/
50+
public function getPropertyCached()
51+
{
52+
if ($this->property === null) {
53+
$this->property = 1223;
54+
}
55+
56+
return $this->property;
57+
}
58+
59+
public function testigetFoo()
4460
{
4561
$this->property = 1223;
4662
return $this->property;

Magento/Tests/Functions/GetterStateUnitTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ protected function getWarningList()
3030
28 => 1,
3131
29 => 1,
3232
30 => 1,
33-
39 => 1,
33+
43 => 1,
3434
];
3535
}
3636
}

0 commit comments

Comments
 (0)