Skip to content

Commit

Permalink
[Php71] Skip typed array property on CountOnNullRector (#1049)
Browse files Browse the repository at this point in the history
Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>
Co-authored-by: Alexander Melihov <amelihovv@ya.ru>
Co-authored-by: GitHub Action <action@github.com>
  • Loading branch information
3 people committed Oct 23, 2021
1 parent fd5edff commit ec90557
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\Tests\Php71\Rector\FuncCall\CountOnNullRector\Fixture;

final class SkipTypedArrayProperty
{
private array $items;

public function __construct()
{
$this->items = [];
}

public function count(): int
{
return count($this->items);
}
}
28 changes: 28 additions & 0 deletions rules/Php71/NodeAnalyzer/CountableAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,15 @@
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\Php\PhpPropertyReflection;
use PHPStan\Reflection\PropertyReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\UnionType;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\NodeTypeResolver\NodeTypeResolver;

final class CountableAnalyzer
Expand Down Expand Up @@ -63,7 +68,30 @@ public function isCastableArrayType(Expr $expr): bool
return false;
}

$phpPropertyReflection = $this->resolveProperty($expr, $classReflection, $propertyName);
if (! $phpPropertyReflection instanceof PhpPropertyReflection) {
return false;
}

$nativeType = $phpPropertyReflection->getNativeType();
if ($nativeType->isIterable()->yes()) {
return false;
}

$propertyDefaultValue = $propertiesDefaults[$propertyName];
return $propertyDefaultValue === null;
}

private function resolveProperty(
PropertyFetch $propertyFetch,
ClassReflection $classReflection,
string $propertyName
): ?PropertyReflection {
$scope = $propertyFetch->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return null;
}

return $classReflection->getProperty($propertyName, $scope);
}
}

0 comments on commit ec90557

Please sign in to comment.