PropertyPathMapper.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  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 Symfony\Component\Form\DataMapper;
  11. use Symfony\Component\Form\FormInterface;
  12. use Symfony\Component\Form\VirtualFormAwareIterator;
  13. use Symfony\Component\Form\Exception\FormException;
  14. class PropertyPathMapper implements DataMapperInterface
  15. {
  16. /**
  17. * Stores the class that the data of this form must be instances of
  18. * @var string
  19. */
  20. private $dataClass;
  21. public function __construct($dataClass = null)
  22. {
  23. $this->dataClass = $dataClass;
  24. }
  25. public function mapDataToForms($data, array $forms)
  26. {
  27. if (!empty($data) && !is_array($data) && !is_object($data)) {
  28. throw new \InvalidArgumentException(sprintf('Expected argument of type object or array, %s given', gettype($data)));
  29. }
  30. if (!empty($data)) {
  31. if ($this->dataClass && !$data instanceof $this->dataClass) {
  32. throw new FormException(sprintf('Form data should be instance of %s', $this->dataClass));
  33. }
  34. $iterator = new VirtualFormAwareIterator($forms);
  35. $iterator = new \RecursiveIteratorIterator($iterator);
  36. foreach ($iterator as $form) {
  37. $this->mapDataToForm($data, $form);
  38. }
  39. }
  40. }
  41. public function mapDataToForm($data, FormInterface $form)
  42. {
  43. if (!empty($data)) {
  44. if ($form->getAttribute('property_path') !== null) {
  45. $form->setData($form->getAttribute('property_path')->getValue($data));
  46. }
  47. }
  48. }
  49. public function mapFormsToData(array $forms, &$data)
  50. {
  51. $iterator = new VirtualFormAwareIterator($forms);
  52. $iterator = new \RecursiveIteratorIterator($iterator);
  53. foreach ($iterator as $form) {
  54. $this->mapFormToData($form, $data);
  55. }
  56. }
  57. public function mapFormToData(FormInterface $form, &$data)
  58. {
  59. if ($form->getAttribute('property_path') !== null && $form->isSynchronized()) {
  60. $propertyPath = $form->getAttribute('property_path');
  61. // If the data is identical to the value in $data, we are
  62. // dealing with a reference
  63. $isReference = $form->getData() === $propertyPath->getValue($data);
  64. $byReference = $form->getAttribute('by_reference');
  65. if (!(is_object($data) && $isReference && $byReference)) {
  66. $propertyPath->setValue($data, $form->getData());
  67. }
  68. }
  69. }
  70. }