Skip to content

Commit

Permalink
Fix #1994 - make assert-if-true work for $this properties
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Aug 10, 2019
1 parent 5254b75 commit 460120e
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
Expand Up @@ -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]]];
}
}
}
}
Expand Down Expand Up @@ -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]]];
}
}
}
}
Expand Down
92 changes: 92 additions & 0 deletions tests/AssertTest.php
Expand Up @@ -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;
}
}'
],
];
}

Expand Down

0 comments on commit 460120e

Please sign in to comment.