ModelToIdTransformer.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. /**
  27. * @param \Sonata\AdminBundle\Model\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)) {
  41. return null;
  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 0;
  52. }
  53. return current( $this->modelManager->getIdentifierValues($entity) );
  54. }
  55. }