SerializerExtractor.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\PropertyInfo\Extractor;
  11. use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
  12. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
  13. /**
  14. * Lists available properties using Symfony Serializer Component metadata.
  15. *
  16. * @author Kévin Dunglas <dunglas@gmail.com>
  17. *
  18. * @final
  19. */
  20. class SerializerExtractor implements PropertyListExtractorInterface
  21. {
  22. private $classMetadataFactory;
  23. public function __construct(ClassMetadataFactoryInterface $classMetadataFactory)
  24. {
  25. $this->classMetadataFactory = $classMetadataFactory;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function getProperties(string $class, array $context = []): ?array
  31. {
  32. if (!isset($context['serializer_groups']) || !\is_array($context['serializer_groups'])) {
  33. return null;
  34. }
  35. if (!$this->classMetadataFactory->getMetadataFor($class)) {
  36. return null;
  37. }
  38. $properties = [];
  39. $serializerClassMetadata = $this->classMetadataFactory->getMetadataFor($class);
  40. foreach ($serializerClassMetadata->getAttributesMetadata() as $serializerAttributeMetadata) {
  41. $ignored = method_exists($serializerClassMetadata, 'isIgnored') && $serializerAttributeMetadata->isIgnored();
  42. if (!$ignored && array_intersect($context['serializer_groups'], $serializerAttributeMetadata->getGroups())) {
  43. $properties[] = $serializerAttributeMetadata->getName();
  44. }
  45. }
  46. return $properties;
  47. }
  48. }