Merge pull request #1583 from rectorphp/countnull

Fix CountOnNullRector for nullable and invalid property
This commit is contained in:
Tomáš Votruba 2019-06-09 00:10:53 +02:00 committed by GitHub
commit 94db26e2a5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 80 additions and 5 deletions

View File

@ -270,6 +270,13 @@ final class NodeTypeResolver
return true;
}
if ($node instanceof PropertyFetch) {
// PHPStan false positive, when variable has type[] docblock, but default array is missing
if ($this->isPropertyFetchWithArrayDefault($node) === false) {
return false;
}
}
if ($nodeStaticType instanceof MixedType) {
if ($nodeStaticType->isExplicitMixed()) {
return false;

View File

@ -71,7 +71,7 @@ CODE_SAMPLE
return null;
}
if ($this->isNullType($countedNode)) {
if ($this->isNullableType($countedNode) || $this->isNullType($countedNode)) {
$identicalNode = new Identical($countedNode, $this->createNull());
$ternaryNode = new Ternary($identicalNode, new LNumber(0), $node);
} else {

View File

@ -20,7 +20,11 @@ final class CountOnNullRectorTest extends AbstractRectorTestCase
__DIR__ . '/Fixture/preg_match_array.php.inc',
__DIR__ . '/Fixture/local_property.php.inc',
__DIR__ . '/Fixture/double_same_variable.php.inc',
__DIR__ . '/Fixture/array_merge.php.inc',
__DIR__ . '/Fixture/property_with_doc.php.inc',
__DIR__ . '/Fixture/nullable_array.php.inc',
// skip
__DIR__ . '/Fixture/skip_array_merge.php.inc',
]);
}

View File

@ -9,7 +9,7 @@ final class HeaderControl
/**
* @var mixed[]
*/
private $alsoTitles;
private $alsoTitles = [];
/**
* @var mixed
@ -42,7 +42,7 @@ final class HeaderControl
/**
* @var mixed[]
*/
private $alsoTitles;
private $alsoTitles = [];
/**
* @var mixed

View File

@ -0,0 +1,27 @@
<?php
namespace Rector\Php\Tests\Rector\FuncCall\CountOnNullRector\Fixture;
final class NullableArray
{
public function number(?array $items)
{
return count($items);
}
}
?>
-----
<?php
namespace Rector\Php\Tests\Rector\FuncCall\CountOnNullRector\Fixture;
final class NullableArray
{
public function number(?array $items)
{
return $items === null ? 0 : count($items);
}
}
?>

View File

@ -0,0 +1,37 @@
<?php
namespace Rector\Php\Tests\Rector\FuncCall\CountOnNullRector\Fixture;
class PropertyWithDoc
{
/**
* @var int[]
*/
private $fail;
public function run()
{
return count($this->fail);
}
}
?>
-----
<?php
namespace Rector\Php\Tests\Rector\FuncCall\CountOnNullRector\Fixture;
class PropertyWithDoc
{
/**
* @var int[]
*/
private $fail;
public function run()
{
return is_array($this->fail) || $this->fail instanceof \Countable ? count($this->fail) : 0;
}
}
?>

View File

@ -2,7 +2,7 @@
namespace Rector\Php\Tests\Rector\FuncCall\CountOnNullRector\Fixture;
class ArrayMerge
class SkipArrayMerge
{
public function run(string $string, array $regexes): ?array
{