ArrayToModelTransformer.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /*
  3. * This file is part of the Sonata project.
  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 Symfony\Component\Form\Exception\InvalidPropertyException;
  12. use Symfony\Component\Form\Exception\PropertyAccessDeniedException;
  13. use Symfony\Component\Form\DataTransformerInterface;
  14. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  15. use Symfony\Component\Form\Exception\TransformationFailedException;
  16. use Sonata\AdminBundle\Model\ModelManagerInterface;
  17. class ArrayToModelTransformer implements DataTransformerInterface
  18. {
  19. protected $modelManager;
  20. protected $className;
  21. /**
  22. * @param \Sonata\AdminBundle\Model\ModelManagerInterface $modelManager
  23. * @param string $className
  24. */
  25. public function __construct(ModelManagerInterface $modelManager, $className)
  26. {
  27. $this->modelManager = $modelManager;
  28. $this->className = $className;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function reverseTransform($array)
  34. {
  35. // when the object is created the form return an array
  36. // one the object is persisted, the edit $array is the user instance
  37. if ($array instanceof $this->className) {
  38. return $array;
  39. }
  40. $instance = new $this->className;
  41. if (!is_array($array)) {
  42. return $instance;
  43. }
  44. return $this->modelManager->modelReverseTransform($this->className, $array);
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function transform($value)
  50. {
  51. return $value;
  52. }
  53. }