ModelToIdTransformer.php 1.5 KB

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