ArrayToModelTransformer.php 1.5 KB

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