The PropertyInfo Component

The PropertyInfo Component

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

While the PropertyAccess component allows you to read and write values to/from objects and arrays, the PropertyInfo component works solely with class definitions to provide information about the data type and visibility - including via getter or setter methods - of the properties within that class.

Installation

  1. $ composer require symfony/property-info

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

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

Usage

To use this component, create a new Symfony\Component\PropertyInfo\PropertyInfoExtractor instance and provide 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. // a full list of extractors is shown further below
  6. $phpDocExtractor = new PhpDocExtractor();
  7. $reflectionExtractor = new ReflectionExtractor();
  8. // list of PropertyListExtractorInterface (any iterable)
  9. $listExtractors = [$reflectionExtractor];
  10. // list of PropertyTypeExtractorInterface (any iterable)
  11. $typeExtractors = [$phpDocExtractor, $reflectionExtractor];
  12. // list of PropertyDescriptionExtractorInterface (any iterable)
  13. $descriptionExtractors = [$phpDocExtractor];
  14. // list of PropertyAccessExtractorInterface (any iterable)
  15. $accessExtractors = [$reflectionExtractor];
  16. // list of PropertyInitializableExtractorInterface (any iterable)
  17. $propertyInitializableExtractors = [$reflectionExtractor];
  18. $propertyInfo = new PropertyInfoExtractor(
  19. $listExtractors,
  20. $typeExtractors,
  21. $descriptionExtractors,
  22. $accessExtractors,
  23. $propertyInitializableExtractors
  24. );
  25. // see below for more examples
  26. $class = YourAwesomeCoolClass::class;
  27. $properties = $propertyInfo->getProperties($class);

Extractor Ordering

The order of extractor instances within an array matters: the first non-null result will be returned. That is why you must provide each category of extractors as a separate array, even if an extractor provides information for more than one category.

For example, while the Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor and Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor both provide list and type information it is probably better that:

  • The Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor has priority for list information so that all properties in a class (not just mapped properties) are returned.

  • The Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor has priority for type information so that entity metadata is used instead of 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. $reflectionExtractor = new ReflectionExtractor();
    5. $doctrineExtractor = new DoctrineExtractor(/* ... */);
    6. $propertyInfo = new PropertyInfoExtractor(
    7. // List extractors
    8. [
    9. $reflectionExtractor,
    10. $doctrineExtractor
    11. ],
    12. // Type extractors
    13. [
    14. $doctrineExtractor,
    15. $reflectionExtractor
    16. ]
    17. );

Extractable Information

The Symfony\Component\PropertyInfo\PropertyInfoExtractor class 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. // Good!
  4. $propertyInfo->getProperties(get_class($awesomeObject));
  5. $propertyInfo->getProperties('Example\Namespace\YourAwesomeClass');
  6. $propertyInfo->getProperties(YourAwesomeClass::class);

List Information

Extractors that implement Symfony\Component\PropertyInfo\PropertyListExtractorInterface provide the list of properties that are available on a class as an array containing 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 Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface provide extensive data type information for 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 Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface provide long and short descriptions from a properties annotations as strings:

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

Access Information

Extractors that implement Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface provide whether properties are readable or writable as booleans:

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

The Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor looks for getter/isser/setter/hasser method in addition to whether or not a property is public to determine if it’s accessible. This based on how the PropertyAccess works.

Property Initializable Information

Extractors that implement Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface provide 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 the given property name.

Tip

The main Symfony\Component\PropertyInfo\PropertyInfoExtractor class implements all interfaces, delegating the extraction of property information to the extractors that have been registered with it.

This means that any method available on each of the extractors is also available on the main Symfony\Component\PropertyInfo\PropertyInfoExtractor class.

Type Objects

Compared to the other extractors, type information extractors provide much more information than can be represented as simple scalar values. Because of this, type extractors return an array of Symfony\Component\PropertyInfo\Type objects for each type that the property supports.

For example, if a property supports both integer and string (via the @return int|string annotation), PropertyInfoExtractor::getTypes() will return an array containing two instances of the Symfony\Component\PropertyInfo\Type class.

Note

Most extractors will return only one Symfony\Component\PropertyInfo\Type instance. The Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor is 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 these string values: array, bool, callable, float, int, iterable, null, object, resource or string.

Constants inside the Symfony\Component\PropertyInfo\Type class, in the form Type::BUILTIN_TYPE_*, are provided for convenience.

`Type::isNullable()

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

`Type::getClassName()

If the built-in PHP data type is 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 is a collection - a non-scalar value capable of containing other values. Currently this returns true if:

  • The built-in PHP data type is array;
  • The mutator method the property is derived from has a prefix of add or 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.)

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

If the property is a collection, additional type objects may be returned for both the key and value types of the collection (if the information is available), 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 information by implementing the correct interface(s).

The Symfony\Component\PropertyInfo\PropertyInfoExtractor will iterate over the relevant extractor classes in the order they were set, call the appropriate method and return the first result that is not null.

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

ReflectionExtractor

Using PHP reflection, the Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor provides list, type and access information from setter and accessor methods. It can also give the type of a property (even extracting it from the constructor arguments), and if it is initializable through the constructor. It supports return and scalar types for PHP 7:

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

Note

When using the Symfony framework, this service is automatically registered when 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 Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor provides type and description information. This extractor is automatically registered with the property_info in the Symfony Framework if the dependent library is present:

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

SerializerExtractor

Note

This extractor depends on the symfony/serializer library.

Using groups metadata from the Serializer component, the Symfony\Component\PropertyInfo\Extractor\SerializerExtractor provides list information. This extractor is not registered automatically with 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. $serializerClassMetadataFactory = new ClassMetadataFactory(
  6. new AnnotationLoader(new AnnotationReader)
  7. );
  8. $serializerExtractor = new SerializerExtractor($serializerClassMetadataFactory);
  9. // the `serializer_groups` option must be configured (may be set to null)
  10. $serializerExtractor->getProperties($class, ['serializer_groups' => ['mygroup']]);

If serializer_groups is set to null, serializer groups metadata won’t be checked but you will get only the properties considered by the Serializer Component (notably the @Ignore annotation is taken into account).

New in version 5.2: Support for the null value in serializer_groups was introduced in Symfony 5.2.

DoctrineExtractor

Note

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

Using entity mapping data from Doctrine ORM, the Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor provides list and type information. This extractor is not registered automatically with 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. $config = Setup::createAnnotationMetadataConfiguration([__DIR__], true);
  5. $entityManager = EntityManager::create([
  6. 'driver' => 'pdo_sqlite',
  7. // ...
  8. ], $config);
  9. $doctrineExtractor = new DoctrineExtractor($entityManager);
  10. // List information.
  11. $doctrineExtractor->getProperties($class);
  12. // Type information.
  13. $doctrineExtractor->getTypes($class, $property);

Creating Your Own Extractors

You can create your own property information extractors by creating a class that implements one or more of the following interfaces: Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface, Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface, Symfony\Component\PropertyInfo\PropertyListExtractorInterface, Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface and Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface.

If you have enabled the PropertyInfo component with the FrameworkBundle, you can automatically register your extractor class with the property_info service by defining it as a service with one or more of the following tags:

  • 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.
  • property_info.initializable_extractor if it provides initializable information (it checks if a property can be initialized through the constructor).

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.