ModelToIdTransformer.php 1.4 KB

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