-
Notifications
You must be signed in to change notification settings - Fork 0
/
EntityMerger.php
244 lines (219 loc) · 9.23 KB
/
EntityMerger.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php
/*
* This file is part of the Orbitale's EntityMerger package.
*
* (c) Alexandre Rock Ancelet <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Orbitale\Component\EntityMerger;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\Serializer\SerializerInterface;
use JMS\Serializer\SerializerInterface as JMSSerializerInterface;
class EntityMerger
{
/**
* When merging objects, the merger will use the same "merge" for the associated fields,
* doing every merge recursively for each object involved.
* Be careful: if the merged object also have associations, it can be risky.
* Be sure to have the whole object mapped recursively.
*/
const ASSOCIATIONS_MERGE = 1;
/**
* For associations, the merger will search for an entity in the Database, depending on the mapping.
* It will search for the primary key identifier, and make a basic $repo->find($id),
* only if the specified identifier is mapped in the "dataObject".
*/
const ASSOCIATIONS_FIND = 2;
/**
* @var ObjectManager
*/
protected $om;
/**
* @var SerializerInterface
*/
protected $serializer;
/**
* @var int
*/
protected $associationStrategy;
public function __construct(ObjectManager $om = null, $serializer = null, $associationStrategy = null)
{
$this->om = $om;
if ($serializer && !($serializer instanceof SerializerInterface || $serializer instanceof JMSSerializerInterface)) {
throw new \InvalidArgumentException(
'Serializer must be an instance of SerializerInterface, either Symfony native or JMS one.'
);
}
$this->serializer = $serializer;
$this->associationStrategy = $associationStrategy ?: (self::ASSOCIATIONS_MERGE | self::ASSOCIATIONS_FIND);
}
/**
* @param int $strategy
*
* @return $this
*/
public function setAssociationStrategy($strategy)
{
$this->associationStrategy = (int) $strategy;
return $this;
}
/**
* @return int
*/
public function getAssociationStrategy()
{
return $this->associationStrategy;
}
/**
* Tries to merge array $dataObject into $object.
*
* @param object $object
* @param array|object $dataObject
* @param array $mapping
*
* @return object
*/
public function merge($object, $dataObject, array $mapping = [])
{
if (!is_object($object)) {
throw new \InvalidArgumentException('You must specify an object in order to merge the array in it.');
}
if (is_object($dataObject) && $this->serializer) {
// Serialize/deserialize object into array
// This allows to merge two objects together
$dataObject = json_decode($this->serializer->serialize($dataObject, 'json'), true);
}
if (!count($dataObject)) {
throw new \InvalidArgumentException('If you want to merge an array into an entity, you must populate this array.');
}
return $this->doMerge($object, $dataObject, $mapping);
}
/**
* @param $object
* @param array $dataObject
* @param array $mapping
*
* @return mixed
*/
protected function doMerge($object, array $dataObject, array $mapping = [])
{
if (count($mapping)) {
foreach ($mapping as $field => $params) {
if (is_string($params)) {
// Tries to decode if params is a string, so we can have a mapping information stringified in JSON
$params = json_decode($params, true);
}
if (!is_array($params)) {
// Allows anything to be transformed into an array
// If we used json_decode, "null" will be returned and then it'll become an empty array
// Although $params should be either "1", "true" or an array, even empty
$params = [];
}
if (array_key_exists($field, $dataObject)) {
$this->mergeField($field, $object, $dataObject[$field], $params);
} else {
throw new \InvalidArgumentException(
sprintf(
'If you want to specify "%s" as an mergeable field, then you must have to set it in your data object.',
$field
)
);
}
}
} else {
foreach ($dataObject as $field => $value) {
$this->mergeField($field, $object, $value);
}
}
return $object;
}
/**
* Will try to merge a field by automatically searching in its doctrine mapping datas.
*
* @param string $field The field to merge
* @param object $object The entity you want to "hydrate"
* @param mixed $value The datas you want to merge in the object field
* @param array $userMapping An array containing mapping informations provided by the user. Mostly used for relationships
*/
protected function mergeField($field, $object, $value, array $userMapping = [])
{
$currentlyAnalyzedClass = get_class($object);
$mapping = array_merge(
[
'pivot' => null,
'objectField' => $field,
],
$userMapping
);
if ($this->om) {
$metadatas = $this->om->getClassMetadata($currentlyAnalyzedClass);
} else {
$metadatas = new EmptyClassMetadata($currentlyAnalyzedClass);
}
$hasMapping = $metadatas->hasField($mapping['objectField']) ?: $metadatas->hasAssociation(
$mapping['objectField']
);
if ($hasMapping) {
if ($metadatas->hasField($mapping['objectField'])) {
// Handles a field
$reflectionProperty = $metadatas->getReflectionClass()->getProperty($mapping['objectField']);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, $value);
} elseif ($metadatas->hasAssociation($mapping['objectField'])) {
// Handles a relation
$relationClass = $metadatas->getAssociationTargetClass($mapping['objectField']);
$reflectionProperty = $metadatas->getReflectionClass()->getProperty($mapping['objectField']);
$reflectionProperty->setAccessible(true);
$pivotValue = isset($value[$mapping['pivot']]) ? $value[$mapping['pivot']] : null;
if (null === $pivotValue) {
// If no pivot value is specified, we'll get automatically the Entity's Primary Key
/** @var ClassMetadataInfo $relationMetadatas */
$relationMetadatas = $this->om->getMetadataFactory()->getMetadataFor($relationClass);
$pivotValue = $relationMetadatas->getSingleIdentifierFieldName();
}
if ($pivotValue && ($this->associationStrategy & self::ASSOCIATIONS_FIND)) {
// "find" strategy.
if ($metadatas->isSingleValuedAssociation($mapping['objectField'])) {
// Single valued : ManyToOne or OneToOne
$newRelationObject = null;
if ($value) {
$newRelationObject = $this->om->getRepository($relationClass)->findOneBy(
[$pivotValue => $value[$pivotValue]]
);
}
$reflectionProperty->setValue($object, $newRelationObject);
} elseif ($metadatas->isCollectionValuedAssociation($mapping['objectField'])) {
// Collection : OneToMany or ManyToMany
if ($value) {
if (!is_array($value)) {
$value = [$value];
}
$newCollection = $this->om->getRepository($relationClass)->findBy([$pivotValue => $value]);
} else {
$newCollection = [];
}
$reflectionProperty->setValue($object, $newCollection);
}
}
// "merge" strategy
if ($value && ($this->associationStrategy & self::ASSOCIATIONS_MERGE) && $metadatas->isSingleValuedAssociation($mapping['objectField'])) {
$reflectionProperty->setValue(
$object,
$this->merge($reflectionProperty->getValue($object) ?: new $relationClass(), $value)
);
}
}
} else {
throw new \InvalidArgumentException(
sprintf(
'Could not find field "%s" in class "%s"',
$mapping['objectField'],
$currentlyAnalyzedClass
)
);
}
}
}