Skip to content

Commit

Permalink
fix with known offset
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Oct 14, 2023
1 parent 87963a4 commit 0edaf2d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Rector\Tests\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector\Fixture;

class KnownOffset
{
public const DEFAULT_GROUP = 'default';

/**
* @var array<string, list<self>>
*/
private static $groups = [];

public static function knownOffset(): array
{
$group = 'default';

self::$groups[$group] = ["foo"];

if (! empty(self::$groups[$group])) {
foreach (self::$groups[$group] as $group) {
echo "hello";
}
}

return [];
}
}

?>
-----
<?php

namespace Rector\Tests\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector\Fixture;

class KnownOffset
{
public const DEFAULT_GROUP = 'default';

/**
* @var array<string, list<self>>
*/
private static $groups = [];

public static function knownOffset(): array
{
$group = 'default';

self::$groups[$group] = ["foo"];

foreach (self::$groups[$group] as $group) {
echo "hello";
}

return [];
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,12 @@ private function isUselessBeforeForeachCheck(If_ $if, Scope $scope): bool
$foreach = $if->stmts[0];
$foreachExpr = $foreach->expr;

if ($foreachExpr instanceof Expr\ArrayDimFetch) {
return false;
if ($foreachExpr instanceof Expr\ArrayDimFetch && $foreachExpr->dim !== null) {
$exprType = $this->nodeTypeResolver->getNativeType($foreachExpr->var);
$dimType = $this->nodeTypeResolver->getNativeType($foreachExpr->dim);
if (!$exprType->hasOffsetValueType($dimType)->yes()) {
return false;
}
}

if ($foreachExpr instanceof Variable) {
Expand Down

0 comments on commit 0edaf2d

Please sign in to comment.