phpstan-rules
phpstan-rules copied to clipboard
[suggestion] No shadow variable
Hello,
I'm working on a PHP project right now and found this bug:
public function get(string $id): ?Model
{
if ($this->models === null) {
$this->models = [];
$modelsData = $this->resolver->getList($this->operator->getId(), ids: array_keys($this->buffer));
foreach (array_keys($this->buffer) as $bufferedId) {
$this->models[$bufferedId] = null;
}
// function argument $id is overridden here
foreach ($modelsData as $id => $modelDatum) {
$this->models[$id] = $modelDatum;
}
}
// so now the $id is not function's $id the the last $id of the above foreach
return $this->models[$id] ?? null;
}
I feel like it would make sense to have a rule that prevents this, but it's been a while I haven't done any serious PHP so I'm not sure how is the state of static analysis in PHP
Some time ago I implemented generic variable overwriting rule, but was not satisfied with the results (too many ignores of valid cases). But maybe some specific cases like the suggested one (foreach introduced variables) might make sense.
Variable overwrite in a loop is now checked by phpstan/phpstan-strict-rules
$i = 1;
$foo = [1,2,3];
foreach ($foo as $i) {
echo $i;
}
Right, so closing. Thx