ModelToIdTransformer.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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\AdminBundle\Form\DataTransformer;
  11. use Sonata\AdminBundle\Model\ModelManagerInterface;
  12. use Symfony\Component\Form\DataTransformerInterface;
  13. /**
  14. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  15. */
  16. class ModelToIdTransformer implements DataTransformerInterface
  17. {
  18. protected $modelManager;
  19. protected $className;
  20. /**
  21. * @param ModelManagerInterface $modelManager
  22. * @param string $className
  23. */
  24. public function __construct(ModelManagerInterface $modelManager, $className)
  25. {
  26. $this->modelManager = $modelManager;
  27. $this->className = $className;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function reverseTransform($newId)
  33. {
  34. if (empty($newId) && !in_array($newId, array('0', 0), true)) {
  35. return;
  36. }
  37. return $this->modelManager->find($this->className, $newId);
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function transform($entity)
  43. {
  44. if (empty($entity)) {
  45. return;
  46. }
  47. return $this->modelManager->getNormalizedIdentifier($entity);
  48. }
  49. }