4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Form\Extension\Core\DataMapper
;
14 use Symfony\Component\Form\DataMapperInterface
;
15 use Symfony\Component\Form\Exception\UnexpectedTypeException
;
16 use Symfony\Component\PropertyAccess\PropertyAccess
;
17 use Symfony\Component\PropertyAccess\PropertyAccessorInterface
;
20 * A data mapper using property paths to read/write data.
22 * @author Bernhard Schussek <bschussek@gmail.com>
24 class PropertyPathMapper
implements DataMapperInterface
27 * @var PropertyAccessorInterface
29 private $propertyAccessor;
32 * Creates a new property path mapper.
34 * @param PropertyAccessorInterface $propertyAccessor
36 public function __construct(PropertyAccessorInterface
$propertyAccessor = null)
38 $this->propertyAccessor
= $propertyAccessor ?: PropertyAccess
::getPropertyAccessor();
44 public function mapDataToForms($data, $forms)
46 if (null === $data || array() === $data) {
50 if (!is_array($data) && !is_object($data)) {
51 throw new UnexpectedTypeException($data, 'object, array or empty');
54 foreach ($forms as $form) {
55 $propertyPath = $form->getPropertyPath();
56 $config = $form->getConfig();
58 if (null !== $propertyPath && $config->getMapped()) {
59 $form->setData($this->propertyAccessor
->getValue($data, $propertyPath));
67 public function mapFormsToData($forms, &$data)
73 if (!is_array($data) && !is_object($data)) {
74 throw new UnexpectedTypeException($data, 'object, array or empty');
77 foreach ($forms as $form) {
78 $propertyPath = $form->getPropertyPath();
79 $config = $form->getConfig();
81 // Write-back is disabled if the form is not synchronized (transformation failed)
82 // and if the form is disabled (modification not allowed)
83 if (null !== $propertyPath && $config->getMapped() && $form->isSynchronized() && !$form->isDisabled()) {
84 // If the data is identical to the value in $data, we are
85 // dealing with a reference
86 if (!is_object($data) || !$config->getByReference() || $form->getData() !== $this->propertyAccessor
->getValue($data, $propertyPath)) {
87 $this->propertyAccessor
->setValue($data, $propertyPath, $form->getData());