diff --git a/components/type_info.rst b/components/type_info.rst index 817c7f1d61a..fce6b1788f4 100644 --- a/components/type_info.rst +++ b/components/type_info.rst @@ -74,6 +74,8 @@ that need a simple way to describe a class or anything with a type:: // Then resolve types for any subject $typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'id')); // returns an "int" Type instance $typeResolver->resolve('bool'); // returns a "bool" Type instance + $typeResolver->resolve('array{id: int, name?: string}'); // returns an "ArrayShapeType" Type instance with 'id' is required, 'name' is optional + // Types can be instantiated thanks to static factories $type = Type::list(Type::nullable(Type::bool())); @@ -92,6 +94,54 @@ Each of these calls will return you a ``Type`` instance that corresponds to the static method used. You can also resolve types from a string (as shown in the ``bool`` parameter of the previous example) + +The TypeInfo component provides a new Type "ArrayShapeType" to define exact array structures with specific key-value type relationships. + +.. versionadded:: 7.3 + + The ``ArrayShapeType`` method was introduced in Symfony 7.3. + +Array shape types support: + +* Required and optional keys +* Nested array shapes +* Union types for values +* Exact key ordering validation + +The ArrayShapeType support Associative Array definition:: + + use Symfony\Component\TypeInfo\Type; + + // Simple array shape + $type = Type::arrayShape([ + 'name' => Type::string(), + 'age' => Type::int() + ]); + + // With optional keys (denoted by "?" suffix) + $type = Type::arrayShape([ + 'required_id' => Type::int(), + 'optional_name?' => Type::string() + ]); + +But also, ``StringTypeResolver`` now supports parsing array shape notation:: + + use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; + + $resolver = new TypeResolver(); + + // Parse array shape definition + $type = $resolver->resolve('array{name: string, age: int}'); + + // Equivalent to: + Type::arrayShape([ + 'name' => Type::string(), + 'age' => Type::int() + ]); + + $type->is(typeof(['name' => 'Alice', 'age' => 30, ])); // true + $type->is(typeof(['name' => 'Alice', 'age' => '30', ])); // false (wrong age type) + PHPDoc Parsing ~~~~~~~~~~~~~~