Skip to content

Commit 8ff2790

Browse files
loilosirbrillig
authored andcommitted
Correctly mark pass-by-reference variables in use() constructs (#54)
* Test: add test for pass-by-reference in anonymous functions' use construct * checkForFunctionPrototype: Mark relevant variables in use() constructs as pass-by-reference
1 parent d3bbba3 commit 8ff2790

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,14 @@ protected function checkForFunctionPrototype(File $phpcsFile, $stackPtr, $varNam
274274
// TODO: typeHints in use?
275275
$this->markVariableDeclaration($varName, 'bound', null, $stackPtr, $functionPtr);
276276
$this->markVariableAssignment($varName, $stackPtr, $functionPtr);
277+
278+
// Are we pass-by-reference?
279+
$referencePtr = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true, null, true);
280+
if (($referencePtr !== false) && ($tokens[$referencePtr]['code'] === T_BITWISE_AND)) {
281+
$varInfo = $this->getOrCreateVariableInfo($varName, $functionPtr);
282+
$varInfo->passByReference = true;
283+
}
284+
277285
return true;
278286
}
279287
}

VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ public function testFunctionWithoutParamsWarnings() {
3737
$this->assertEquals($expectedWarnings, $lines);
3838
}
3939

40+
public function testFunctionWithUseReferenceWarnings() {
41+
$fixtureFile = $this->getFixture('FunctionWithUseReferenceFixture.php');
42+
$phpcsFile = $this->prepareLocalFileForSniffs($this->getSniffFiles(), $fixtureFile);
43+
$phpcsFile->process();
44+
$lines = $this->getWarningLineNumbersFromFile($phpcsFile);
45+
$expectedErrors = [];
46+
$this->assertEquals($expectedErrors, $lines);
47+
}
48+
4049
public function testFunctionWithDefaultParamErrors() {
4150
$fixtureFile = $this->getFixture('FunctionWithDefaultParamFixture.php');
4251
$phpcsFile = $this->prepareLocalFileForSniffs($this->getSniffFiles(), $fixtureFile);
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
$ref = 0;
4+
5+
$function_with_use_reference = function () use (&$ref) {
6+
$ref = 1;
7+
};

0 commit comments

Comments
 (0)