|
| 1 | +The TypeInfo Component |
| 2 | +====================== |
| 3 | + |
| 4 | + The TypeInfo component extracts PHP types information. It aims to: |
| 5 | + |
| 6 | + - Have a powerful Type definition that can handle union, intersections, and generics (and could be even more extended) |
| 7 | + |
| 8 | + - Being able to get types from anything, such as properties, method arguments, return types, and raw strings (and can also be extended). |
| 9 | + |
| 10 | + |
| 11 | +Installation |
| 12 | +------------ |
| 13 | + |
| 14 | +.. code-block:: terminal |
| 15 | +
|
| 16 | + $ composer require symfony/type-info |
| 17 | +
|
| 18 | +.. include:: /components/require_autoload.rst.inc |
| 19 | + |
| 20 | +Usage |
| 21 | +----- |
| 22 | + |
| 23 | +There is two ways to use this component. First one is to create a manually thanks |
| 24 | +to :class:`Symfony\\Component\\TypeInfo\\Type` static methods as following:: |
| 25 | + |
| 26 | + use Symfony\Component\TypeInfo\Type; |
| 27 | + |
| 28 | + Type::int(); |
| 29 | + Type::nullable(Type::string()); |
| 30 | + Type::generic(Type::object(Collection::class), Type::int()); |
| 31 | + Type::list(Type::bool()); |
| 32 | + Type::intersection(Type::object(\Stringable::class), Type::object(\Iterator::class)); |
| 33 | + |
| 34 | + // Many others are available and can be |
| 35 | + // found in Symfony\Component\TypeInfo\TypeFactoryTrait |
| 36 | + |
| 37 | +Second way to use TypeInfo is to resolve a type based on reflection or a simple string:: |
| 38 | + |
| 39 | + use Symfony\Component\TypeInfo\Type; |
| 40 | + use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; |
| 41 | + |
| 42 | + // Instantiate a new resolver |
| 43 | + $typeResolver = TypeResolver::create(); |
| 44 | + |
| 45 | + // Then resolve types for any subject |
| 46 | + $typeResolver->resolve(new \ReflectionProperty(Dummy::class, 'id')); // returns an "int" Type instance |
| 47 | + $typeResolver->resolve('bool'); // returns a "bool" Type instance |
| 48 | + |
| 49 | + // Types can be instantiated thanks to static factories |
| 50 | + $type = Type::list(Type::nullable(Type::bool())); |
| 51 | + |
| 52 | + // Type instances have several helper methods |
| 53 | + $type->getBaseType() // returns an "array" Type instance |
| 54 | + $type->getCollectionKeyType(); // returns an "int" Type instance |
| 55 | + $type->getCollectionValueType()->isNullable(); // returns true |
| 56 | + |
| 57 | +.. note:: |
| 58 | + |
| 59 | + To support raw string resolving, you need to install ``phpstan/phpdoc-parser`` package. |
0 commit comments