1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 04:45:20 +01:00

Fix #1915 - allow @psalm-assert-if-true to operate on $this

This commit is contained in:
Matthew Brown 2019-07-07 15:06:03 -04:00
parent 820eba1151
commit 5c4ac97546
2 changed files with 53 additions and 0 deletions

View File

@ -1847,6 +1847,20 @@ class AssertionFinder
$if_types[$var_name] = [[$prefix . $assertion->rule[0][0]]]; $if_types[$var_name] = [[$prefix . $assertion->rule[0][0]]];
} }
} }
} elseif ($assertion->var_id === '$this' && $expr instanceof PhpParser\Node\Expr\MethodCall) {
$var_id = ExpressionAnalyzer::getArrayVarId(
$expr->var,
$this_class_name,
$source
);
if ($var_id) {
if ($prefix === $assertion->rule[0][0][0]) {
$if_types[$var_id] = [[substr($assertion->rule[0][0], 1)]];
} else {
$if_types[$var_id] = [[$prefix . $assertion->rule[0][0]]];
}
}
} }
} }
} }
@ -1873,6 +1887,20 @@ class AssertionFinder
$if_types[$var_name] = [[$negated_prefix . $assertion->rule[0][0]]]; $if_types[$var_name] = [[$negated_prefix . $assertion->rule[0][0]]];
} }
} }
} elseif ($assertion->var_id === '$this' && $expr instanceof PhpParser\Node\Expr\MethodCall) {
$var_id = ExpressionAnalyzer::getArrayVarId(
$expr->var,
$this_class_name,
$source
);
if ($var_id) {
if ($negated_prefix === $assertion->rule[0][0][0]) {
$if_types[$var_id] = [[substr($assertion->rule[0][0], 1)]];
} else {
$if_types[$var_id] = [[$negated_prefix . $assertion->rule[0][0]]];
}
}
} }
} }
} }

View File

@ -956,6 +956,31 @@ class AssertTest extends TestCase
return $value; return $value;
}' }'
], ],
'assertThisTypeIfTrue' => [
'<?php
class Type {
/**
* @psalm-assert-if-true FooType $this
*/
public function isFoo() : bool {
return $this instanceof FooType;
}
}
class FooType extends Type {
public function bar(): void {}
}
function takesType(Type $t) : void {
if ($t->isFoo()) {
$t->bar();
}
switch (true) {
case $t->isFoo():
$t->bar();
}
}'
],
]; ];
} }