ArrayToModelTransformer.php 1.6 KB

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