TestRepositoryFactory.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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\Bridge\Doctrine\Test;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Doctrine\ORM\Mapping\ClassMetadata;
  13. use Doctrine\ORM\Repository\RepositoryFactory;
  14. use Doctrine\Persistence\ObjectRepository;
  15. /**
  16. * @author Andreas Braun <alcaeus@alcaeus.org>
  17. */
  18. final class TestRepositoryFactory implements RepositoryFactory
  19. {
  20. /**
  21. * @var ObjectRepository[]
  22. */
  23. private $repositoryList = [];
  24. /**
  25. * {@inheritdoc}
  26. *
  27. * @return ObjectRepository
  28. */
  29. public function getRepository(EntityManagerInterface $entityManager, $entityName)
  30. {
  31. $repositoryHash = $this->getRepositoryHash($entityManager, $entityName);
  32. if (isset($this->repositoryList[$repositoryHash])) {
  33. return $this->repositoryList[$repositoryHash];
  34. }
  35. return $this->repositoryList[$repositoryHash] = $this->createRepository($entityManager, $entityName);
  36. }
  37. public function setRepository(EntityManagerInterface $entityManager, string $entityName, ObjectRepository $repository)
  38. {
  39. $repositoryHash = $this->getRepositoryHash($entityManager, $entityName);
  40. $this->repositoryList[$repositoryHash] = $repository;
  41. }
  42. private function createRepository(EntityManagerInterface $entityManager, string $entityName): ObjectRepository
  43. {
  44. /* @var $metadata ClassMetadata */
  45. $metadata = $entityManager->getClassMetadata($entityName);
  46. $repositoryClassName = $metadata->customRepositoryClassName ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();
  47. return new $repositoryClassName($entityManager, $metadata);
  48. }
  49. private function getRepositoryHash(EntityManagerInterface $entityManager, string $entityName): string
  50. {
  51. return $entityManager->getClassMetadata($entityName)->getName().spl_object_hash($entityManager);
  52. }
  53. }