This is the first article of the series that shows the most important new features introduced by Symfony 7.1, which will be released at the end of May 2024.
The PropertyInfo component extracts information about the types of PHP class properties using metadata from PHP reflection, Doctrine, PHPDoc, PHPStan, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
readonly class Person
{
public function __construct(
public string $firstName,
) {
}
}
$types = $propertyInfo->getTypes(Person::class, 'firstName');
/*
$types = array(1) {
[0] =>
class Symfony\Component\PropertyInfo\Type (6) {
private $builtinType => string(6) "string"
private $nullable => bool(false)
private $class => NULL
private $collection => bool(false)
private $collectionKeyType => NULL
private $collectionValueType => NULL
}
}
*/
This component works well but it has two main limitations:
- It can't properly describe type unions, intersections or generics (this is
partially solved by returning an array of
Type
objects); - It can only get type information from properties and not from method arguments, return types, and raw strings.
That's why in Symfony 7.1 we're introducing a new TypeInfo component to solve these problems. The first problem is solved by defining a hierarchy of classes to describe the types (this will be expanded in the future with new classes when PHP adds new features related to types):
1 2 3 4 5 6 7 8 9
Symfony\Component\TypeInfo\Type
├─ BuiltinType
├─ UnionType
├─ IntersectionType
├─ GenericType
├─ Template
└─ ObjectType
└─ EnumType
└─ BackedEnumType
The second problem is solved with a series of type information extractors that
work not only on class properties (ReflectionReturnTypeResolver
to get return
types using PHP reflection; StringTypeResolver
to get type information using
PHPDoc annotations; etc.)
This component has been introduced as an experimental feature (meaning that
its API could change a bit before considering it stable) but it's already in use
inside the PropertyInfo component. In future Symfony versions we'll deprecate
the Type class from PropertyInfo and
all its related features in favor of the new Type
class from TypeInfo component.
Yeah!!! Congrats!!!
That's great! However, the linked PR seems to be the wrong one.
@Jacob, thanks for reporting this issue. We've just fixed the link to point to the right GitHub PR.
Very nice, more introspection! I guess there's a typo line 2 of the 2nd code block, "BultinType" -> "BuiltinType".
@Cédric good catch! It's fixed now. Thanks.
Guys check "Kotlin Reflection". That's the way how to do this.
I don't like to use plain strings for access to properties. It's not type safe, it's hard to refactor etc.
I would love to see these things from JVM ecosystem in PHP. They are well-made.