<?php
declare(strict_types=1);
/**
* @author Piotr Kowalski <piotr.kowalski@autentika.pl>
* date: 2018-03-16 10:29
*/
namespace Hitso\Bundle\CommonBundle\Serializer\Extractor;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
/**
* Class EntityExtractor.
*/
class EntityExtractor implements PropertyTypeExtractorInterface
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* EntityExtractor constructor.
*
* @param EntityManagerInterface $entityManager
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* Try extract types from Doctrine associations first,
* when fail then reflection extractor enter the game.
*
* {@inheritdoc}
*/
public function getTypes($class, $property, array $context = []): ?array
{
$doctrineExtractor = new DoctrineExtractor($this->entityManager->getMetadataFactory());
$reflectionExtractor = new ReflectionExtractor();
$types = $doctrineExtractor->getTypes($class, $property, $context);
if (isset($types[0]) && null !== $types[0]->getClassName()) {
return $types;
}
return $reflectionExtractor->getTypes($class, $property, $context);
}
}