Skip to content

Commit

Permalink
Improvements for null assertions.
Browse files Browse the repository at this point in the history
- isset($a->b->c) now asserts that $a is not null, $a->b is not null, and $a->b->c is not null
- Consistent with php, !is_null($a->b->c) asserts the same, but does report null dereferences in the parameter before it asserts.
- To avoid errors use !is_null($a?->b?->c) or isset($a->b->c).
- Don't assert when "$this instanceof" is used.  Ie. $this instanceOf Foo from inside of Bar does not change $this to be a Foo.
  • Loading branch information
jongardiner committed May 10, 2024
1 parent 1bd8592 commit 7f34b8e
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
13 changes: 13 additions & 0 deletions tests/units/Checks/TestData/TestComplexTypes.5.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

class TestClass {

private string|array $testArray = "foo";

function method(): array {
if (!is_array($this->testArray)) {
$this->testArray = explode(',', $this->testArray);
}
return $this->testArray;
}
}
14 changes: 14 additions & 0 deletions tests/units/Checks/TestData/TestComplexTypes.6.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

class TestClass {

private $testArray;

function method(): array {
$this->testArray->foo = true ? 'bar' : [];
if (!is_array($this->testArray->foo)) {
$this->testArray->foo = explode(',', $this->testArray->foo);
}
return $this->testArray;
}
}
12 changes: 12 additions & 0 deletions tests/units/Checks/TestData/TestNullablePropertiesCheck.4.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

function nullError(?int $a):int {
if (is_null($a)) {
return 0;
}
return $a;
}

nullError(null);
14 changes: 14 additions & 0 deletions tests/units/Checks/TestData/TestNullablePropertiesCheck.5.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

class NullDefault {
public ?int $a;

function init():int {
if (is_null($this->a)) {
$this->a = 0;
}
return $this->a;
}
}

0 comments on commit 7f34b8e

Please sign in to comment.