Skip to content
Permalink
Browse files

Fix #1994 - make assert-if-true work for $this properties

  • Loading branch information...
muglug committed Aug 10, 2019
1 parent 5254b75 commit 460120ec45fd014aeb9b0a9f40e92fd6fdfb8c5a
Showing with 110 additions and 0 deletions.
  1. +18 −0 src/Psalm/Internal/Analyzer/Statements/Expression/AssertionFinder.php
  2. +92 −0 tests/AssertTest.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]]];
}
}
}
}
@@ -574,6 +574,98 @@ function takesIntOrIterable($v) : int {
return $v;
}'
],
'assertIfTrueOnProperty' => [
'<?php
class A {
public function foo() : void {}
}
class B {
private ?A $a = null;
public function bar() : void {
if ($this->assertProperty()) {
$this->a->foo();
}
}
/**
* @psalm-assert-if-true !null $this->a
*/
public function assertProperty() : bool {
return $this->a !== null;
}
}'
],
'assertIfFalseOnProperty' => [
'<?php
class A {
public function foo() : void {}
}
class B {
private ?A $a = null;
public function bar() : void {
if ($this->assertProperty()) {
$this->a->foo();
}
}
/**
* @psalm-assert-if-false null $this->a
*/
public function assertProperty() : bool {
return $this->a !== null;
}
}'
],
'assertIfTrueOnPropertyNegated' => [
'<?php
class A {
public function foo() : void {}
}
class B {
private ?A $a = null;
public function bar() : void {
if (!$this->assertProperty()) {
$this->a->foo();
}
}
/**
* @psalm-assert-if-true null $this->a
*/
public function assertProperty() : bool {
return $this->a !== null;
}
}'
],
'assertIfFalseOnPropertyNegated' => [
'<?php
class A {
public function foo() : void {}
}
class B {
private ?A $a = null;
public function bar() : void {
if (!$this->assertProperty()) {
$this->a->foo();
}
}
/**
* @psalm-assert-if-false !null $this->a
*/
public function assertProperty() : bool {
return $this->a !== null;
}
}'
],
];
}

0 comments on commit 460120e

Please sign in to comment.
You can’t perform that action at this time.