ModelToIdTransformer.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. /**
  19. * @var ModelManagerInterface
  20. */
  21. protected $modelManager;
  22. /**
  23. * @var string
  24. */
  25. protected $className;
  26. /**
  27. * @param ModelManagerInterface $modelManager
  28. * @param string $className
  29. */
  30. public function __construct(ModelManagerInterface $modelManager, $className)
  31. {
  32. $this->modelManager = $modelManager;
  33. $this->className = $className;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function reverseTransform($newId)
  39. {
  40. if (empty($newId) && !in_array($newId, array('0', 0), true)) {
  41. return;
  42. }
  43. return $this->modelManager->find($this->className, $newId);
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function transform($entity)
  49. {
  50. if (empty($entity)) {
  51. return;
  52. }
  53. return $this->modelManager->getNormalizedIdentifier($entity);
  54. }
  55. }