| 1 |
TypeInfo Component |
| 2 |
================== |
| 3 |
|
| 4 |
The TypeInfo component extracts PHP types information. |
| 5 |
|
| 6 |
Getting Started |
| 7 |
--------------- |
| 8 |
|
| 9 |
```bash |
| 10 |
composer require symfony/type-info |
| 11 |
composer require phpstan/phpdoc-parser # to support raw string resolving |
| 12 |
``` |
| 13 |
|
| 14 |
```php |
| 15 |
<?php |
| 16 |
|
| 17 |
use Symfony\Component\TypeInfo\Type; |
| 18 |
use Symfony\Component\TypeInfo\TypeIdentifier; |
| 19 |
use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; |
| 20 |
|
| 21 |
// Instantiate a new resolver |
| 22 |
$typeResolver = TypeResolver::create(); |
| 23 |
|
| 24 |
// Then resolve types for any subject |
| 25 |
$typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'id')); // returns an "int" Type instance |
| 26 |
$typeResolver->resolve('bool'); // returns a "bool" Type instance |
| 27 |
|
| 28 |
// Types can be instantiated thanks to static factories |
| 29 |
$type = Type::list(Type::nullable(Type::bool())); |
| 30 |
|
| 31 |
// Type classes have their specific methods |
| 32 |
Type::object(FooClass::class)->getClassName(); |
| 33 |
Type::enum(FooEnum::class, Type::int())->getBackingType(); |
| 34 |
Type::list(Type::int())->isList(); |
| 35 |
|
| 36 |
// Every type can be cast to string |
| 37 |
(string) Type::generic(Type::object(Collection::class), Type::int()) // returns "Collection<int>" |
| 38 |
|
| 39 |
// You can check that a type (or one of its wrapped/composed parts) is identified by one of some identifiers. |
| 40 |
$type->isIdentifiedBy(Foo::class, Bar::class); |
| 41 |
$type->isIdentifiedBy(TypeIdentifier::OBJECT); |
| 42 |
$type->isIdentifiedBy('float'); |
| 43 |
|
| 44 |
// You can also check that a type satisfies specific conditions |
| 45 |
$type->isSatisfiedBy(fn (Type $type): bool => !$type->isNullable() && $type->isIdentifiedBy(TypeIdentifier::INT)); |
| 46 |
``` |
| 47 |
|
| 48 |
Resources |
| 49 |
--------- |
| 50 |
* [Documentation](https://symfony.com/doc/current/components/type_info.html) |
| 51 |
* [Contributing](https://symfony.com/doc/current/contributing/index.html) |
| 52 |
* [Report issues](https://github.com/symfony/symfony/issues) and |
| 53 |
[send Pull Requests](https://github.com/symfony/symfony/pulls) |
| 54 |
in the [main Symfony repository](https://github.com/symfony/symfony) |