[PHP 74] Fix ArraySpreadInsteadOfArrayMergeRector for non-constant string keys

This commit is contained in:
TomasVotruba 2020-02-08 13:55:30 +01:00
parent 03e1535d84
commit 5ad0771013
2 changed files with 43 additions and 8 deletions

View File

@ -11,8 +11,11 @@ use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Ternary; use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable; use PhpParser\Node\Expr\Variable;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType; use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantStringType; use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use Rector\Core\Rector\AbstractRector; use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample; use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition; use Rector\Core\RectorDefinition\RectorDefinition;
@ -127,16 +130,11 @@ PHP
} }
$arrayStaticType = $this->getStaticType($expr); $arrayStaticType = $this->getStaticType($expr);
if ($arrayStaticType instanceof ConstantArrayType) { if ($this->isConstantArrayTypeWithStringKeyType($arrayStaticType)) {
foreach ($arrayStaticType->getKeyTypes() as $keyType) { return true;
// key cannot be string
if ($keyType instanceof ConstantStringType) {
return true;
}
}
} }
return false; return $arrayStaticType instanceof ArrayType && $arrayStaticType->getKeyType() instanceof StringType;
} }
private function resolveValue(Expr $expr): Expr private function resolveValue(Expr $expr): Expr
@ -174,4 +172,20 @@ PHP
{ {
return $expr instanceof FuncCall && $this->isName($expr, 'iterator_to_array'); return $expr instanceof FuncCall && $this->isName($expr, 'iterator_to_array');
} }
private function isConstantArrayTypeWithStringKeyType(Type $type): bool
{
if (! $type instanceof ConstantArrayType) {
return false;
}
foreach ($type->getKeyTypes() as $keyType) {
// key cannot be string
if ($keyType instanceof ConstantStringType) {
return true;
}
}
return false;
}
} }

View File

@ -0,0 +1,21 @@
<?php
namespace Rector\Php74\Tests\Rector\FuncCall\ArraySpreadInsteadOfArrayMergeRector\Fixture;
class SkipParseUrl
{
public function run()
{
return array_merge($this->parseUrl($url), $this->parseUrl($redirectLocation));
}
/**
* @return array<string, string>
*/
private function parseUrl(string $url): array
{
$urlParts = parse_url($url);
return array_filter($urlParts);
}
}