From 460120ec45fd014aeb9b0a9f40e92fd6fdfb8c5a Mon Sep 17 00:00:00 2001 From: Matthew Brown Date: Sat, 10 Aug 2019 09:12:02 -0400 Subject: [PATCH] Fix #1994 - make assert-if-true work for $this properties --- .../Statements/Expression/AssertionFinder.php | 18 ++++ tests/AssertTest.php | 92 +++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/AssertionFinder.php b/src/Psalm/Internal/Analyzer/Statements/Expression/AssertionFinder.php index ea26df7e2d2..da5693bcd0f 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/AssertionFinder.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/AssertionFinder.php @@ -1861,6 +1861,15 @@ protected static function processCustomAssertion( $if_types[$var_id] = [[$prefix . $assertion->rule[0][0]]]; } } + } elseif (is_string($assertion->var_id) + && strpos($assertion->var_id, '$this->') === 0 + && $expr instanceof PhpParser\Node\Expr\MethodCall + ) { + if ($prefix === $assertion->rule[0][0][0]) { + $if_types[$assertion->var_id] = [[substr($assertion->rule[0][0], 1)]]; + } else { + $if_types[$assertion->var_id] = [[$prefix . $assertion->rule[0][0]]]; + } } } } @@ -1901,6 +1910,15 @@ protected static function processCustomAssertion( $if_types[$var_id] = [[$negated_prefix . $assertion->rule[0][0]]]; } } + } elseif (is_string($assertion->var_id) + && strpos($assertion->var_id, '$this->') === 0 + && $expr instanceof PhpParser\Node\Expr\MethodCall + ) { + if ($prefix === $assertion->rule[0][0][0]) { + $if_types[$assertion->var_id] = [[substr($assertion->rule[0][0], 1)]]; + } else { + $if_types[$assertion->var_id] = [[$negated_prefix . $assertion->rule[0][0]]]; + } } } } diff --git a/tests/AssertTest.php b/tests/AssertTest.php index b0548969fc8..10555d608eb 100644 --- a/tests/AssertTest.php +++ b/tests/AssertTest.php @@ -574,6 +574,98 @@ function takesIntOrIterable($v) : int { return $v; }' ], + 'assertIfTrueOnProperty' => [ + 'assertProperty()) { + $this->a->foo(); + } + } + + /** + * @psalm-assert-if-true !null $this->a + */ + public function assertProperty() : bool { + return $this->a !== null; + } + }' + ], + 'assertIfFalseOnProperty' => [ + 'assertProperty()) { + $this->a->foo(); + } + } + + /** + * @psalm-assert-if-false null $this->a + */ + public function assertProperty() : bool { + return $this->a !== null; + } + }' + ], + 'assertIfTrueOnPropertyNegated' => [ + 'assertProperty()) { + $this->a->foo(); + } + } + + /** + * @psalm-assert-if-true null $this->a + */ + public function assertProperty() : bool { + return $this->a !== null; + } + }' + ], + 'assertIfFalseOnPropertyNegated' => [ + 'assertProperty()) { + $this->a->foo(); + } + } + + /** + * @psalm-assert-if-false !null $this->a + */ + public function assertProperty() : bool { + return $this->a !== null; + } + }' + ], ]; }