SerializerExtractor.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. public function __construct(
  23. private readonly ClassMetadataFactoryInterface $classMetadataFactory,
  24. ) {
  25. }
  26. public function getProperties(string $class, array $context = []): ?array
  27. {
  28. if (!\array_key_exists('serializer_groups', $context) || (null !== $context['serializer_groups'] && !\is_array($context['serializer_groups']))) {
  29. return null;
  30. }
  31. if (!$this->classMetadataFactory->hasMetadataFor($class)) {
  32. return null;
  33. }
  34. $properties = [];
  35. $serializerClassMetadata = $this->classMetadataFactory->getMetadataFor($class);
  36. foreach ($serializerClassMetadata->getAttributesMetadata() as $serializerAttributeMetadata) {
  37. if (!$serializerAttributeMetadata->isIgnored() && (null === $context['serializer_groups'] || \in_array('*', $context['serializer_groups'], true) || array_intersect($serializerAttributeMetadata->getGroups(), $context['serializer_groups']))) {
  38. $properties[] = $serializerAttributeMetadata->getName();
  39. }
  40. }
  41. return $properties;
  42. }
  43. }