ArrayToModelTransformer.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. public function __construct(ModelManagerInterface $modelManager, $className)
  22. {
  23. $this->modelManager = $modelManager;
  24. $this->className = $className;
  25. }
  26. /**
  27. * @param array $ids
  28. * @return $object
  29. */
  30. public function reverseTransform($array)
  31. {
  32. // when the object is created the form return an array
  33. // one the object is persisted, the edit $array is the user instance
  34. if ($array instanceof $this->className)
  35. {
  36. return $array;
  37. }
  38. $instance = new $this->className;
  39. if (!is_array($array)) {
  40. return $instance;
  41. }
  42. return $this->modelManager->modelReverseTransform($this->className, $array);
  43. }
  44. /**
  45. * @param Collection $value
  46. */
  47. public function transform($value)
  48. {
  49. return $value;
  50. }
  51. }