ModelToIdTransformer.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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. */
  11. namespace Sonata\AdminBundle\Form\DataTransformer;
  12. use Symfony\Component\Form\Exception\InvalidPropertyException;
  13. use Symfony\Component\Form\Exception\PropertyAccessDeniedException;
  14. use Symfony\Component\Form\DataTransformerInterface;
  15. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  16. use Symfony\Component\Form\Exception\TransformationFailedException;
  17. use Sonata\AdminBundle\Model\ModelManagerInterface;
  18. /**
  19. *
  20. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  21. */
  22. class ModelToIdTransformer implements DataTransformerInterface
  23. {
  24. protected $modelManager;
  25. protected $className;
  26. public function __construct(ModelManagerInterface $modelManager, $className)
  27. {
  28. $this->modelManager = $modelManager;
  29. $this->className = $className;
  30. }
  31. /**
  32. * Reverse Transforming the selected id value to an Doctrine Entity.
  33. *
  34. * This handles NULL, the EntityManager#find method returns null if no entity was found.
  35. *
  36. * @param int|string $newId
  37. * @param object $oldEntity
  38. * @return object
  39. */
  40. public function reverseTransform($newId)
  41. {
  42. if (empty($newId)) {
  43. return null;
  44. }
  45. return $this->modelManager->find($this->className, $newId);
  46. }
  47. /**
  48. * @param object $entity
  49. * @return int|string
  50. */
  51. public function transform($entity)
  52. {
  53. if (empty($entity)) {
  54. return 0;
  55. }
  56. return current( $this->modelManager->getIdentifierValues($entity) );
  57. }
  58. }