ArrayToModelTransformer.php 1.6 KB

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