The PropertyInfo Component

The PropertyInfo component allows you to get informationabout class properties by using different sources of metadata.

While the PropertyAccess componentallows you to read and write values to/from objects and arrays, the PropertyInfocomponent works solely with class definitions to provide information about thedata type and visibility - including via getter or setter methods - of the propertieswithin that class.

Installation

  1. $ composer require symfony/property-info

Note

If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Additional dependencies may be required for some of theextractors provided with this component.

Usage

To use this component, create a newPropertyInfoExtractor instance andprovide it with a set of information extractors:

  1. use Example\Namespace\YourAwesomeCoolClass;
  2. use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
  3. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  4. use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
  5.  
  6. // a full list of extractors is shown further below
  7. $phpDocExtractor = new PhpDocExtractor();
  8. $reflectionExtractor = new ReflectionExtractor();
  9.  
  10. // list of PropertyListExtractorInterface (any iterable)
  11. $listExtractors = [$reflectionExtractor];
  12.  
  13. // list of PropertyTypeExtractorInterface (any iterable)
  14. $typeExtractors = [$phpDocExtractor, $reflectionExtractor];
  15.  
  16. // list of PropertyDescriptionExtractorInterface (any iterable)
  17. $descriptionExtractors = [$phpDocExtractor];
  18.  
  19. // list of PropertyAccessExtractorInterface (any iterable)
  20. $accessExtractors = [$reflectionExtractor];
  21.  
  22. // list of PropertyInitializableExtractorInterface (any iterable)
  23. $propertyInitializableExtractors = [$reflectionExtractor];
  24.  
  25. $propertyInfo = new PropertyInfoExtractor(
  26. $listExtractors,
  27. $typeExtractors,
  28. $descriptionExtractors,
  29. $accessExtractors,
  30. $propertyInitializableExtractors
  31. );
  32.  
  33. // see below for more examples
  34. $class = YourAwesomeCoolClass::class;
  35. $properties = $propertyInfo->getProperties($class);

Extractor Ordering

The order of extractor instances within an array matters: the first non-nullresult will be returned. That is why you must provide each category of extractorsas a separate array, even if an extractor provides information for more thanone category.

For example, while the ReflectionExtractorand DoctrineExtractorboth provide list and type information it is probably better that:

  • The ReflectionExtractorhas priority for list information so that all properties in a class (notjust mapped properties) are returned.

  • The DoctrineExtractorhas priority for type information so that entity metadata is used insteadof type-hinting to provide more accurate type information:

  1. use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
  2. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  3. use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
  4.  
  5. $reflectionExtractor = new ReflectionExtractor();
  6. $doctrineExtractor = new DoctrineExtractor(/* ... */);
  7.  
  8. $propertyInfo = new PropertyInfoExtractor(
  9. // List extractors
  10. [
  11. $reflectionExtractor,
  12. $doctrineExtractor
  13. ],
  14. // Type extractors
  15. [
  16. $doctrineExtractor,
  17. $reflectionExtractor
  18. ]
  19. );

Extractable Information

The PropertyInfoExtractorclass exposes public methods to extract several types of information:

Note

Be sure to pass a class name, not an object to the extractor methods:

  1. // bad! It may work, but not with all extractors
  2. $propertyInfo->getProperties($awesomeObject);
  3.  
  4. // Good!
  5. $propertyInfo->getProperties(get_class($awesomeObject));
  6. $propertyInfo->getProperties('Example\Namespace\YourAwesomeClass');
  7. $propertyInfo->getProperties(YourAwesomeClass::class);

List Information

Extractors that implement PropertyListExtractorInterfaceprovide the list of properties that are available on a class as an arraycontaining each property name as a string:

  1. $properties = $propertyInfo->getProperties($class);
  2. /*
  3. Example Result
  4. --------------
  5. array(3) {
  6. [0] => string(8) "username"
  7. [1] => string(8) "password"
  8. [2] => string(6) "active"
  9. }
  10. */

Type Information

Extractors that implement PropertyTypeExtractorInterfaceprovide extensive data type informationfor a property:

  1. $types = $propertyInfo->getTypes($class, $property);
  2. /*
  3. Example Result
  4. --------------
  5. array(1) {
  6. [0] =>
  7. class Symfony\Component\PropertyInfo\Type (6) {
  8. private $builtinType => string(6) "string"
  9. private $nullable => bool(false)
  10. private $class => NULL
  11. private $collection => bool(false)
  12. private $collectionKeyType => NULL
  13. private $collectionValueType => NULL
  14. }
  15. }
  16. */

See Type Objects for info about the Type class.

Description Information

Extractors that implement PropertyDescriptionExtractorInterfaceprovide long and short descriptions from a properties annotations asstrings:

  1. $title = $propertyInfo->getShortDescription($class, $property);
  2. /*
  3. Example Result
  4. --------------
  5. string(41) "This is the first line of the DocComment."
  6. */
  7.  
  8. $paragraph = $propertyInfo->getLongDescription($class, $property);
  9. /*
  10. Example Result
  11. --------------
  12. string(79):
  13. These is the subsequent paragraph in the DocComment.
  14. It can span multiple lines.
  15. */

Access Information

Extractors that implement PropertyAccessExtractorInterfaceprovide whether properties are readable or writable as booleans:

  1. $propertyInfo->isReadable($class, $property);
  2. // Example Result: bool(true)
  3.  
  4. $propertyInfo->isWritable($class, $property);
  5. // Example Result: bool(false)

The ReflectionExtractor looksfor getter/isser/setter/hasser method in addition to whether or not a property is publicto determine if it's accessible. This based on how the PropertyAccessworks.

Property Initializable Information

Extractors that implement PropertyInitializableExtractorInterfaceprovide whether properties are initializable through the class's constructor as booleans:

  1. $propertyInfo->isInitializable($class, $property);
  2. // Example Result: bool(true)

isInitializable()returns true if a constructor's parameter of the given class matches thegiven property name.

Tip

The main PropertyInfoExtractorclass implements all interfaces, delegating the extraction of propertyinformation to the extractors that have been registered with it.

This means that any method available on each of the extractors is alsoavailable on the main PropertyInfoExtractorclass.

Type Objects

Compared to the other extractors, type information extractors provide muchmore information than can be represented as simple scalar values. Becauseof this, type extractors return an array of Typeobjects for each type that the property supports.

For example, if a property supports both integer and string (viathe @return int|string annotation),PropertyInfoExtractor::getTypes()will return an array containing two instances of the Typeclass.

Note

Most extractors will return only one Typeinstance. The PhpDocExtractoris currently the only extractor that returns multiple instances in the array.

Each object will provide 6 attributes, available in the 6 methods:

Type::getBuiltInType()

The Type::getBuiltinType()method returns the built-in PHP data type, which can be one of thesestring values: array, bool, callable, float, int,iterable, null, object, resource or string.

Constants inside the Typeclass, in the form Type::BUILTINTYPE*, are provided for convenience.

Type::isNullable()

The Type::isNullable()method will return a boolean value indicating whether the property parametercan be set to null.

Type::getClassName()

If the built-in PHP data typeis object, the Type::getClassName()method will return the fully-qualified class or interface name accepted.

Type::isCollection()

The Type::isCollection()method will return a boolean value indicating if the property parameter isa collection - a non-scalar value capable of containing other values. Currentlythis returns true if:

  • The built-in PHP data typeis array;
  • The mutator method the property is derived from has a prefix of addor remove (which are defined as the list of array mutator prefixes);
  • The phpDocumentor annotation is of type "collection" (e.g.@var SomeClass<DateTime>, @var SomeClass<integer,string>,@var Doctrine\Common\Collections\Collection<App\Entity\SomeEntity>, etc.)

New in version 4.2: The support of phpDocumentor collection types was introduced in Symfony 4.2.

Type::getCollectionKeyType() & Type::getCollectionValueType()

If the property is a collection, additional type objects may be returnedfor both the key and value types of the collection (if the information isavailable), via the Type::getCollectionKeyType()and Type::getCollectionValueType()methods.

Extractors

The extraction of property information is performed by extractor classes.An extraction class can provide one or more types of property informationby implementing the correct interface(s).

The PropertyInfoExtractor williterate over the relevant extractor classes in the order they were set, callthe appropriate method and return the first result that is not null.

While you can create your own extractors, the following are already availableto cover most use-cases:

ReflectionExtractor

Using PHP reflection, the ReflectionExtractorprovides list, type and access information from setter and accessor methods.It can also give the type of a property (even extracting it from the constructorarguments), and if it is initializable through the constructor. It supportsreturn and scalar types for PHP 7:

  1. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  2.  
  3. $reflectionExtractor = new ReflectionExtractor();
  4.  
  5. // List information.
  6. $reflectionExtractor->getProperties($class);
  7.  
  8. // Type information.
  9. $reflectionExtractor->getTypes($class, $property);
  10.  
  11. // Access information.
  12. $reflectionExtractor->isReadable($class, $property);
  13. $reflectionExtractor->isWritable($class, $property);
  14.  
  15. // Initializable information
  16. $reflectionExtractor->isInitializable($class, $property);

New in version 4.1: The feature to extract the property types from constructor arguments wasintroduced in Symfony 4.1.

Note

When using the Symfony framework, this service is automatically registeredwhen the property_info feature is enabled:

  1. # config/packages/framework.yaml
  2. framework:
  3. property_info:
  4. enabled: true

PhpDocExtractor

Note

This extractor depends on the phpdocumentor/reflection-docblock library.

Using phpDocumentor Reflection to parse property and method annotations,the PhpDocExtractorprovides type and description information. This extractor is automaticallyregistered with the propertyinfo in the Symfony Framework _if the dependentlibrary is present:

  1. use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
  2.  
  3. $phpDocExtractor = new PhpDocExtractor();
  4.  
  5. // Type information.
  6. $phpDocExtractor->getTypes($class, $property);
  7. // Description information.
  8. $phpDocExtractor->getShortDescription($class, $property);
  9. $phpDocExtractor->getLongDescription($class, $property);

SerializerExtractor

Note

This extractor depends on the symfony/serializer library.

Using groups metadatafrom the Serializer component,the SerializerExtractorprovides list information. This extractor is not registered automaticallywith the property_info service in the Symfony Framework:

  1. use Doctrine\Common\Annotations\AnnotationReader;
  2. use Symfony\Component\PropertyInfo\Extractor\SerializerExtractor;
  3. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
  4. use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
  5.  
  6. $serializerClassMetadataFactory = new ClassMetadataFactory(
  7. new AnnotationLoader(new AnnotationReader)
  8. );
  9. $serializerExtractor = new SerializerExtractor($serializerClassMetadataFactory);
  10.  
  11. // List information.
  12. $serializerExtractor->getProperties($class);

DoctrineExtractor

Note

This extractor depends on the symfony/doctrine-bridge and doctrine/ormlibraries.

Using entity mapping data from Doctrine ORM, theDoctrineExtractorprovides list and type information. This extractor is not registered automaticallywith the property_info service in the Symfony Framework:

  1. use Doctrine\ORM\EntityManager;
  2. use Doctrine\ORM\Tools\Setup;
  3. use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
  4.  
  5. $config = Setup::createAnnotationMetadataConfiguration([__DIR__], true);
  6. $entityManager = EntityManager::create([
  7. 'driver' => 'pdo_sqlite',
  8. // ...
  9. ], $config);
  10. $doctrineExtractor = new DoctrineExtractor($entityManager);
  11.  
  12. // List information.
  13. $doctrineExtractor->getProperties($class);
  14. // Type information.
  15. $doctrineExtractor->getTypes($class, $property);

Creating Your Own Extractors

You can create your own property information extractors by creating aclass that implements one or more of the following interfaces:PropertyAccessExtractorInterface,PropertyDescriptionExtractorInterface,PropertyListExtractorInterface,PropertyTypeExtractorInterface andPropertyInitializableExtractorInterface.

If you have enabled the PropertyInfo component with the FrameworkBundle,you can automatically register your extractor class with the propertyinfoservice by defining it as a service with one or more of the following[_tags](https://symfony.com/doc/current/service_container/tags.html):

  • property_info.list_extractor if it provides list information.
  • property_info.type_extractor if it provides type information.
  • property_info.description_extractor if it provides description information.
  • property_info.access_extractor if it provides access information.