Skip to content

Commit df530b7

Browse files
authored
Allow Traits to use $this (#25)
* Tests: add trait test using $this * Tests: throw exception if fixture does not exist * Allow Traits to use `$this`
1 parent 4561aae commit df530b7

File tree

4 files changed

+25
-2
lines changed

4 files changed

+25
-2
lines changed

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -760,7 +760,7 @@ protected function checkForThisWithinClass(
760760
$token = $tokens[$stackPtr];
761761

762762
// Are we $this within a class?
763-
if (($varName != 'this') || empty($token['conditions'])) {
763+
if (($varName !== 'this') || empty($token['conditions'])) {
764764
return false;
765765
}
766766

@@ -770,7 +770,7 @@ protected function checkForThisWithinClass(
770770
if ($tokens[$scopePtr]['code'] === T_CLOSURE) {
771771
return true;
772772
}
773-
if ($scopeCode === T_CLASS) {
773+
if ($scopeCode === T_CLASS || $scopeCode === T_TRAIT) {
774774
return true;
775775
}
776776
}

VariableAnalysis/Tests/BaseTestCase.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ public function prepareLocalFileForSniffs($sniffFiles, string $fixtureFile): Loc
1515
}
1616
$ruleset->registerSniffs($sniffFiles, [], []);
1717
$ruleset->populateTokenListeners();
18+
if (! file_exists($fixtureFile)) {
19+
throw new \Exception('Fixture file does not exist: ' . $fixtureFile);
20+
}
1821
return new LocalFile($fixtureFile, $ruleset, $config);
1922
}
2023

VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,4 +373,16 @@ public function testCompactWarnings() {
373373
];
374374
$this->assertEquals($expectedWarnings, $lines);
375375
}
376+
377+
public function testTraitAllowsThis() {
378+
$fixtureFile = $this->getFixture('TraitFixture.php');
379+
$phpcsFile = $this->prepareLocalFileForSniffs($this->getSniffFiles(), $fixtureFile);
380+
$phpcsFile->process();
381+
$lines = $this->getWarningLineNumbersFromFile($phpcsFile);
382+
$expectedWarnings = [];
383+
$this->assertEquals($expectedWarnings, $lines);
384+
$lines = $this->getErrorLineNumbersFromFile($phpcsFile);
385+
$expectedErrors = [];
386+
$this->assertEquals($expectedErrors, $lines);
387+
}
376388
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
trait Hello {
4+
public function sayHelloWorld() {
5+
echo 'Hello'.$this->getWorld();
6+
}
7+
abstract public function getWorld();
8+
}

0 commit comments

Comments
 (0)