Skip to content

Commit

Permalink
fix getArrays
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Dec 26, 2022
1 parent 727ccd6 commit 29273e7
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Type/Constant/ConstantArrayType.php
Expand Up @@ -145,6 +145,11 @@ public function getOptionalKeys(): array
return $this->optionalKeys;
}

public function getArrays(): array
{
return $this->getAllArrays();
}

/**
* @return self[]
*/
Expand Down
4 changes: 4 additions & 0 deletions src/Type/IntersectionType.php
Expand Up @@ -109,6 +109,10 @@ public function getArrays(): array
{
$arrays = [];
foreach ($this->types as $type) {
if (!$type instanceof ArrayType) {
continue;
}

foreach ($type->getArrays() as $array) {
$arrays[] = $array;
}
Expand Down
4 changes: 4 additions & 0 deletions src/Type/UnionType.php
Expand Up @@ -116,6 +116,10 @@ public function getArrays(): array
{
$arrays = [];
foreach ($this->types as $type) {
if (!$type instanceof ArrayType) {
return [];
}

foreach ($type->getArrays() as $array) {
$arrays[] = $array;
}
Expand Down
73 changes: 73 additions & 0 deletions tests/PHPStan/Type/UnionTypeTest.php
Expand Up @@ -1347,4 +1347,77 @@ public function dataGetConstantStrings(): iterable
];
}

/**
* @dataProvider dataGetArrays
* @param list<string> $expectedDescriptions
*/
public function testGetArrays(
Type $unionType,
array $expectedDescriptions,
): void
{
$arrays = $unionType->getArrays();

$actualDescriptions = [];
foreach ($arrays as $arrayType) {
$actualDescriptions[] = $arrayType->describe(VerbosityLevel::precise());
}

$this->assertSame($expectedDescriptions, $actualDescriptions);
}

public function dataGetArrays(): iterable
{
yield from [
[
TypeCombinator::union(
new ConstantStringType('hello'),
new ConstantStringType('world'),
),
[],
],
[
TypeCombinator::union(
TypeCombinator::intersect(
new ConstantArrayType(
[new ConstantIntegerType(1), new ConstantIntegerType(2)],
[new IntegerType(), new StringType()],
2,
[0, 1],
),
new NonEmptyArrayType(),
),
new ConstantArrayType(
[new ConstantIntegerType(0), new ConstantIntegerType(1)],
[new ObjectType(Foo::class), new ObjectType(stdClass::class)],
2,
),
),
[
'array{1?: int, 2?: string}',
'array{RecursionCallable\Foo, stdClass}',
],
],
[
TypeCombinator::union(
new ArrayType(new IntegerType(), new StringType()),
new ConstantArrayType(
[new ConstantIntegerType(1), new ConstantIntegerType(2)],
[new IntegerType(), new StringType()],
2,
[0, 1],
),
new ConstantArrayType(
[new ConstantIntegerType(0), new ConstantIntegerType(1)],
[new ObjectType(Foo::class), new ObjectType(stdClass::class)],
2,
),
),
[
'array<int, int|RecursionCallable\Foo|stdClass|string>',
],
],
];
}

}

0 comments on commit 29273e7

Please sign in to comment.