]> git.immae.eu Git - github/wallabag/wallabag.git/blob - vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php
twig implementation
[github/wallabag/wallabag.git] / vendor / symfony / form / Symfony / Component / Form / Extension / Core / DataMapper / PropertyPathMapper.php
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Form\Extension\Core\DataMapper;
13
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;
18
19 /**
20 * A data mapper using property paths to read/write data.
21 *
22 * @author Bernhard Schussek <bschussek@gmail.com>
23 */
24 class PropertyPathMapper implements DataMapperInterface
25 {
26 /**
27 * @var PropertyAccessorInterface
28 */
29 private $propertyAccessor;
30
31 /**
32 * Creates a new property path mapper.
33 *
34 * @param PropertyAccessorInterface $propertyAccessor
35 */
36 public function __construct(PropertyAccessorInterface $propertyAccessor = null)
37 {
38 $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::getPropertyAccessor();
39 }
40
41 /**
42 * {@inheritdoc}
43 */
44 public function mapDataToForms($data, $forms)
45 {
46 if (null === $data || array() === $data) {
47 return;
48 }
49
50 if (!is_array($data) && !is_object($data)) {
51 throw new UnexpectedTypeException($data, 'object, array or empty');
52 }
53
54 foreach ($forms as $form) {
55 $propertyPath = $form->getPropertyPath();
56 $config = $form->getConfig();
57
58 if (null !== $propertyPath && $config->getMapped()) {
59 $form->setData($this->propertyAccessor->getValue($data, $propertyPath));
60 }
61 }
62 }
63
64 /**
65 * {@inheritdoc}
66 */
67 public function mapFormsToData($forms, &$data)
68 {
69 if (null === $data) {
70 return;
71 }
72
73 if (!is_array($data) && !is_object($data)) {
74 throw new UnexpectedTypeException($data, 'object, array or empty');
75 }
76
77 foreach ($forms as $form) {
78 $propertyPath = $form->getPropertyPath();
79 $config = $form->getConfig();
80
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());
88 }
89 }
90 }
91 }
92 }