ArrayToModelTransformer.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project 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. namespace Sonata\AdminBundle\Form\DataTransformer;
  11. use Sonata\AdminBundle\Model\ModelManagerInterface;
  12. use Symfony\Component\Form\DataTransformerInterface;
  13. /**
  14. * Class ArrayToModelTransformer.
  15. *
  16. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  17. */
  18. class ArrayToModelTransformer implements DataTransformerInterface
  19. {
  20. protected $modelManager;
  21. protected $className;
  22. /**
  23. * @param \Sonata\AdminBundle\Model\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($array)
  35. {
  36. // when the object is created the form return an array
  37. // one the object is persisted, the edit $array is the user instance
  38. if ($array instanceof $this->className) {
  39. return $array;
  40. }
  41. $instance = new $this->className();
  42. if (!is_array($array)) {
  43. return $instance;
  44. }
  45. return $this->modelManager->modelReverseTransform($this->className, $array);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function transform($value)
  51. {
  52. return $value;
  53. }
  54. }