Skip to content

[TypeInfo] Add ArrayShapeType class #59827

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

Merged
merged 1 commit into from
Mar 14, 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
1 change: 1 addition & 0 deletions src/Symfony/Component/TypeInfo/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ CHANGELOG
* Deprecate the third `$asList` argument of `TypeFactoryTrait::iterable()`, use `TypeFactoryTrait::list()` instead
* Add type alias support in `TypeContext` and `StringTypeResolver`
* Add `CollectionType::mergeCollectionValueTypes()` method
* Add `ArrayShapeType` to represent the exact shape of an array

7.2
---
Expand Down
98 changes: 98 additions & 0 deletions src/Symfony/Component/TypeInfo/Tests/Type/ArrayShapeTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\TypeInfo\Tests\Type;

use PHPUnit\Framework\TestCase;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\ArrayShapeType;

class ArrayShapeTypeTest extends TestCase
{
public function testGetCollectionKeyType()
{
$type = new ArrayShapeType([
1 => ['type' => Type::bool(), 'optional' => false],
]);
$this->assertEquals(Type::int(), $type->getCollectionKeyType());

$type = new ArrayShapeType([
'foo' => ['type' => Type::bool(), 'optional' => false],
]);
$this->assertEquals(Type::string(), $type->getCollectionKeyType());

$type = new ArrayShapeType([
1 => ['type' => Type::bool(), 'optional' => false],
'foo' => ['type' => Type::bool(), 'optional' => false],
]);
$this->assertEquals(Type::union(Type::int(), Type::string()), $type->getCollectionKeyType());
}

public function testGetCollectionValueType()
{
$type = new ArrayShapeType([
1 => ['type' => Type::bool(), 'optional' => false],
]);
$this->assertEquals(Type::bool(), $type->getCollectionValueType());

$type = new ArrayShapeType([
'foo' => ['type' => Type::bool(), 'optional' => false],
'bar' => ['type' => Type::int(), 'optional' => false],
]);
$this->assertEquals(Type::union(Type::int(), Type::bool()), $type->getCollectionValueType());

$type = new ArrayShapeType([
'foo' => ['type' => Type::bool(), 'optional' => false],
'bar' => ['type' => Type::nullable(Type::string()), 'optional' => false],
]);
$this->assertEquals(Type::nullable(Type::union(Type::bool(), Type::string())), $type->getCollectionValueType());

$type = new ArrayShapeType([
'foo' => ['type' => Type::true(), 'optional' => false],
'bar' => ['type' => Type::false(), 'optional' => false],
]);
$this->assertEquals(Type::bool(), $type->getCollectionValueType());
}

public function testAccepts()
{
$type = new ArrayShapeType([
'foo' => ['type' => Type::bool(), 'optional' => false],
'bar' => ['type' => Type::string(), 'optional' => true],
]);

$this->assertFalse($type->accepts('string'));
$this->assertFalse($type->accepts([]));
$this->assertFalse($type->accepts(['foo' => 'string']));
$this->assertFalse($type->accepts(['foo' => true, 'other' => 'string']));

$this->assertTrue($type->accepts(['foo' => true]));
$this->assertTrue($type->accepts(['foo' => true, 'bar' => 'string']));
}

public function testToString()
{
$type = new ArrayShapeType([1 => ['type' => Type::bool(), 'optional' => false]]);
$this->assertSame('array{1: bool}', (string) $type);

$type = new ArrayShapeType([
2 => ['type' => Type::int(), 'optional' => true],
1 => ['type' => Type::bool(), 'optional' => false],
]);
$this->assertSame('array{1: bool, 2?: int}', (string) $type);

$type = new ArrayShapeType([
'foo' => ['type' => Type::bool(), 'optional' => false],
'bar' => ['type' => Type::string(), 'optional' => true],
]);
$this->assertSame("array{'bar'?: string, 'foo': bool}", (string) $type);
}
}
7 changes: 7 additions & 0 deletions src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\TypeInfo\Tests\Fixtures\DummyBackedEnum;
use Symfony\Component\TypeInfo\Tests\Fixtures\DummyEnum;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\ArrayShapeType;
use Symfony\Component\TypeInfo\Type\BackedEnumType;
use Symfony\Component\TypeInfo\Type\BuiltinType;
use Symfony\Component\TypeInfo\Type\CollectionType;
Expand Down Expand Up @@ -205,6 +206,12 @@ public function testCreateNullable()
);
}

public function testCreateArrayShape()
{
$this->assertEquals(new ArrayShapeType(['foo' => ['type' => Type::bool(), 'optional' => true]]), Type::arrayShape(['foo' => ['type' => Type::bool(), 'optional' => true]]));
$this->assertEquals(new ArrayShapeType(['foo' => ['type' => Type::bool(), 'optional' => false]]), Type::arrayShape(['foo' => Type::bool()]));
}

/**
* @dataProvider createFromValueProvider
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ public static function resolveDataProvider(): iterable
yield [Type::list(Type::bool()), 'bool[]'];

// array shape
yield [Type::array(), 'array{0: true, 1: false}'];
yield [Type::arrayShape(['foo' => Type::true(), 1 => Type::false()]), 'array{foo: true, 1: false}'];
yield [Type::arrayShape(['foo' => ['type' => Type::bool(), 'optional' => true]]), 'array{foo?: bool}'];

// object shape
yield [Type::object(), 'object{foo: true, bar: false}'];
Expand Down
110 changes: 110 additions & 0 deletions src/Symfony/Component/TypeInfo/Type/ArrayShapeType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\TypeInfo\Type;

use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\TypeIdentifier;

/**
* Represents the exact shape of an array.
*
* @author Mathias Arlaud <mathias.arlaud@gmail.com>
*
* @extends CollectionType<GenericType<BuiltinType<TypeIdentifier::ARRAY>>>
*/
final class ArrayShapeType extends CollectionType
{
/**
* @var array<array{type: Type, optional: bool}>
*/
private readonly array $shape;

/**
* @param array<array{type: Type, optional: bool}> $shape
*/
public function __construct(array $shape)
{
$keyTypes = [];
$valueTypes = [];

foreach ($shape as $k => $v) {
$keyTypes[] = self::fromValue($k);
$valueTypes[] = $v['type'];
}

if ($keyTypes) {
$keyTypes = array_values(array_unique($keyTypes));
$keyType = \count($keyTypes) > 1 ? self::union(...$keyTypes) : $keyTypes[0];
} else {
$keyType = Type::union(Type::int(), Type::string());
}

$valueType = $valueTypes ? CollectionType::mergeCollectionValueTypes($valueTypes) : Type::mixed();

parent::__construct(self::generic(self::builtin(TypeIdentifier::ARRAY), $keyType, $valueType));

$sortedShape = $shape;
ksort($sortedShape);

$this->shape = $sortedShape;
}

/**
* @return array<array{type: Type, optional: bool}>
*/
public function getShape(): array
{
return $this->shape;
}

public function accepts(mixed $value): bool
{
if (!\is_array($value)) {
return false;
}

foreach ($this->shape as $key => $shapeValue) {
if (!($shapeValue['optional'] ?? false) && !\array_key_exists($key, $value)) {
return false;
}
}

foreach ($value as $key => $itemValue) {
$valueType = $this->shape[$key]['type'] ?? false;
if (!$valueType) {
return false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For extra keys, the behavior is different between PHPStan (allow) and psalm (restrict). You implemented the strict version: false is returned when an extra key is present. This is consistent with psalm and PHPStorm 👍🏻

There is a syntax using ... to allow extra keys (demo); but this is not supported by PHPStorm and PHP_CodeSniffer.

/** @param array{foo: string, ...} $a */
function fun(array $a): int

This feature can wait for a subsequent PR.

}

if (!$valueType->accepts($itemValue)) {
return false;
}
}

return true;
}

public function __toString(): string
{
$items = [];

foreach ($this->shape as $key => $value) {
$itemKey = \is_int($key) ? (string) $key : \sprintf("'%s'", $key);
if ($value['optional'] ?? false) {
$itemKey = \sprintf('%s?', $itemKey);
}

$items[] = \sprintf('%s: %s', $itemKey, $value['type']);
}

return \sprintf('array{%s}', implode(', ', $items));
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/TypeInfo/Type/CollectionType.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
*
* @implements WrappingTypeInterface<T>
*/
final class CollectionType extends Type implements WrappingTypeInterface
class CollectionType extends Type implements WrappingTypeInterface
{
/**
* @param T $type
Expand Down
13 changes: 13 additions & 0 deletions src/Symfony/Component/TypeInfo/TypeFactoryTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\TypeInfo;

use Symfony\Component\TypeInfo\Type\ArrayShapeType;
use Symfony\Component\TypeInfo\Type\BackedEnumType;
use Symfony\Component\TypeInfo\Type\BuiltinType;
use Symfony\Component\TypeInfo\Type\CollectionType;
Expand Down Expand Up @@ -194,6 +195,18 @@ public static function dict(?Type $value = null): CollectionType
return self::array($value, self::string());
}

/**
* @param array<array{type: Type, optional?: bool}|Type> $shape
*/
public static function arrayShape(array $shape): ArrayShapeType
{
return new ArrayShapeType(array_map(static function (array|Type $item): array {
return $item instanceof Type
? ['type' => $item, 'optional' => false]
: ['type' => $item['type'], 'optional' => $item['optional'] ?? false];
}, $shape));
}

/**
* @template T of class-string
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,15 @@ private function getTypeFromNode(TypeNode $node, ?TypeContext $typeContext): Typ
}

if ($node instanceof ArrayShapeNode) {
return Type::array();
$shape = [];
foreach ($node->items as $item) {
$shape[(string) $item->keyName] = [
'type' => $this->getTypeFromNode($item->valueType, $typeContext),
'optional' => $item->optional,
];
}

return Type::arrayShape($shape);
}

if ($node instanceof ObjectShapeNode) {
Expand Down
Loading