Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support tagged unions in array_merge #3770

Merged
merged 1 commit into from
Jan 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -1312,11 +1312,6 @@ parameters:
count: 1
path: src/Type/Php/ArrayKeyExistsFunctionTypeSpecifyingExtension.php

-
message: "#^Doing instanceof PHPStan\\\\Type\\\\Constant\\\\ConstantArrayType is error\\-prone and deprecated\\. Use Type\\:\\:getConstantArrays\\(\\) instead\\.$#"
count: 4
path: src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php

-
message: "#^Doing instanceof PHPStan\\\\Type\\\\ConstantScalarType is error\\-prone and deprecated\\. Use Type\\:\\:isConstantScalarValue\\(\\) or Type\\:\\:getConstantScalarTypes\\(\\) or Type\\:\\:getConstantScalarValues\\(\\) instead\\.$#"
count: 16
Expand Down
54 changes: 25 additions & 29 deletions src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\IntegerType;
use PHPStan\Type\NeverType;
Expand Down Expand Up @@ -39,58 +40,53 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,

$argTypes = [];
$optionalArgTypes = [];
$allConstant = true;
foreach ($args as $arg) {
$argType = $scope->getType($arg->value);

if ($arg->unpack) {
if ($argType instanceof ConstantArrayType) {
$argTypesFound = $argType->getValueTypes();
} else {
$argTypesFound = [$argType->getIterableValueType()];
}

foreach ($argTypesFound as $argTypeFound) {
$argTypes[] = $argTypeFound;
if ($argTypeFound instanceof ConstantArrayType) {
continue;
if ($argType->isConstantArray()->yes()) {
foreach ($argType->getConstantArrays() as $constantArray) {
foreach ($constantArray->getValueTypes() as $valueType) {
$argTypes[] = $valueType;
}
}
herndlm marked this conversation as resolved.
Show resolved Hide resolved
$allConstant = false;
} else {
$argTypes[] = $argType->getIterableValueType();
}

if (!$argType->isIterableAtLeastOnce()->yes()) {
// unpacked params can be empty, making them optional
$optionalArgTypesOffset = count($argTypes) - 1;
foreach (array_keys($argTypesFound) as $key) {
foreach (array_keys($argTypes) as $key) {
$optionalArgTypes[] = $optionalArgTypesOffset + $key;
}
}
} else {
$argTypes[] = $argType;
if (!$argType instanceof ConstantArrayType) {
$allConstant = false;
}
}
}

if ($allConstant) {
$allConstant = TrinaryLogic::createYes()->lazyAnd(
$argTypes,
static fn (Type $argType) => $argType->isConstantArray(),
);

if ($allConstant->yes()) {
$newArrayBuilder = ConstantArrayTypeBuilder::createEmpty();
foreach ($argTypes as $argType) {
if (!$argType instanceof ConstantArrayType) {
throw new ShouldNotHappenException();
/** @var array<int|string, ConstantIntegerType|ConstantStringType> $keyTypes */
$keyTypes = [];
foreach ($argType->getConstantArrays() as $constantArray) {
foreach ($constantArray->getKeyTypes() as $keyType) {
$keyTypes[$keyType->getValue()] = $keyType;
}
}

$keyTypes = $argType->getKeyTypes();
$valueTypes = $argType->getValueTypes();
$optionalKeys = $argType->getOptionalKeys();

foreach ($keyTypes as $k => $keyType) {
$isOptional = in_array($k, $optionalKeys, true);

foreach ($keyTypes as $keyType) {
$newArrayBuilder->setOffsetValueType(
$keyType instanceof ConstantIntegerType ? null : $keyType,
$valueTypes[$k],
$isOptional,
$argType->getOffsetValueType($keyType),
!$argType->hasOffsetValueType($keyType)->yes(),
);
}
}
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Analyser/nsrt/array-merge2.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public function arrayMergeArrayShapes($array1, $array2): void
assertType("array{foo: '1', bar: '2', lall2: '3', 0: '4', 1: '6', lall: '3', 2: '2', 3: '3'}", array_merge($array2, $array1));
assertType("array{foo: 3, bar: '2', lall2: '3', 0: '4', 1: '6', lall: '3', 2: '2', 3: '3'}", array_merge($array2, $array1, ['foo' => 3]));
assertType("array{foo: 3, bar: '2', lall2: '3', 0: '4', 1: '6', lall: '3', 2: '2', 3: '3'}", array_merge($array2, $array1, ...[['foo' => 3]]));
assertType("array{foo: '1', bar: '2'|'4', lall?: '3', 0: '2'|'4', 1: '3'|'6', lall2?: '3'}", array_merge(rand(0, 1) ? $array1 : $array2, []));
assertType("array{foo?: 3, bar?: 3}", array_merge([], ...[rand(0, 1) ? ['foo' => 3] : ['bar' => 3]]));
assertType("array{foo: '1', bar: '2'|'4', lall?: '3', 0: '2'|'4', 1: '3'|'6', lall2?: '3'}", array_merge([], ...[rand(0, 1) ? $array1 : $array2]));
assertType("array{foo: 1, bar: 2, 0: 2, 1: 3}", array_merge(['foo' => 4, 'bar' => 5], ...[['foo' => 1, 'bar' => 2], [2, 3]]));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1598,6 +1598,15 @@ public function testBug9399(): void
$this->analyse([__DIR__ . '/data/bug-9399.php'], []);
}

public function testBug9559(): void
{
if (PHP_VERSION_ID < 80000) {
$this->markTestSkipped('Test requires PHP 8.0');
}

$this->analyse([__DIR__ . '/data/bug-9559.php'], []);
}

public function testBug9923(): void
{
if (PHP_VERSION_ID < 80000) {
Expand Down
12 changes: 12 additions & 0 deletions tests/PHPStan/Rules/Functions/data/bug-9559.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php declare(strict_types = 1);

namespace Bug9559;

class ZZ {};
function foo(?ZZ $z = null, ?int $a = 0, ?string $b = "x"): string { return "bah"; }

function doit(int $x): void {
$call = [];
if ($x) $call['a'] = 45;
foo(...array_merge($call, [ "b" => "3" ]));
}
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,16 @@ public function testBug8573(): void
$this->analyse([__DIR__ . '/data/bug-8573.php'], []);
}

public function testBug8632(): void
{
$this->analyse([__DIR__ . '/data/bug-8632.php'], []);
}

public function testBug7857(): void
{
$this->analyse([__DIR__ . '/data/bug-7857.php'], []);
}

public function testBug8879(): void
{
$this->analyse([__DIR__ . '/data/bug-8879.php'], []);
Expand Down
17 changes: 17 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-7857.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types = 1);

namespace Bug7857;

class Paginator
{
/**
* @return array{page: int, perPage?: int}
*/
public function toArray(int $page, ?int $perPage): array
{
return array_merge(
['page' => $page],
$perPage !== null ? ['perPage' => $perPage] : []
);
}
}
26 changes: 26 additions & 0 deletions tests/PHPStan/Rules/Methods/data/bug-8632.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php declare(strict_types = 1);

namespace Bug8632;

class HelloWorld
{
/**
* @return array{
* id?: int,
* categories?: string[],
* }
*/
public function test(bool $foo): array
{
if ($foo) {
$arr = [
'id' => 1,
'categories' => ['news'],
];
} else {
$arr = [];
}

return array_merge($arr, []);
}
}
Loading