DoctrineORMAdapter.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  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 Sonata\CoreBundle\Model\Adapter;
  11. use Doctrine\Common\Persistence\ManagerRegistry;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. /**
  14. * This is a port of the DoctrineORMAdminBundle / ModelManager class.
  15. */
  16. class DoctrineORMAdapter implements AdapterInterface
  17. {
  18. /**
  19. * @var ManagerRegistry
  20. */
  21. protected $registry;
  22. /**
  23. * @param ManagerRegistry $registry
  24. */
  25. public function __construct(ManagerRegistry $registry)
  26. {
  27. $this->registry = $registry;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getNormalizedIdentifier($entity)
  33. {
  34. if (is_scalar($entity)) {
  35. throw new \RunTimeException('Invalid argument, object or null required');
  36. }
  37. if (!$entity) {
  38. return;
  39. }
  40. $manager = $this->registry->getManagerForClass(get_class($entity));
  41. if (!$manager instanceof EntityManagerInterface) {
  42. return;
  43. }
  44. if (!$manager->getUnitOfWork()->isInIdentityMap($entity)) {
  45. return;
  46. }
  47. return implode(self::ID_SEPARATOR, $manager->getUnitOfWork()->getEntityIdentifier($entity));
  48. }
  49. /**
  50. * {@inheritdoc}
  51. *
  52. * The ORM implementation does nothing special but you still should use
  53. * this method when using the id in a URL to allow for future improvements.
  54. */
  55. public function getUrlsafeIdentifier($entity)
  56. {
  57. return $this->getNormalizedIdentifier($entity);
  58. }
  59. }