Skip to content

Commit 11e0fe0

Browse files
authored
Merge pull request nilportugues#1 from HennerM/unique-inclueded-data
Unique inclueded data
2 parents 8682a00 + 0fa189f commit 11e0fe0

File tree

2 files changed

+24
-31
lines changed

2 files changed

+24
-31
lines changed

src/Helpers/DataIncludedHelper.php

+18-5
Original file line numberDiff line numberDiff line change
@@ -161,15 +161,28 @@ protected static function addToIncludedArray(array &$mappings, array &$data, arr
161161
$arrayData[JsonApiTransformer::RELATIONSHIPS_KEY] = $relationships;
162162
}
163163

164-
$data[JsonApiTransformer::INCLUDED_KEY][] = \array_filter($arrayData);
164+
$existingIndex = false;
165+
if (array_key_exists(JsonApiTransformer::INCLUDED_KEY, $data)) {
166+
$existingIndex = self::findIncludedIndex($data[JsonApiTransformer::INCLUDED_KEY], $arrayData[JsonApiTransformer::ID_KEY], $arrayData[JsonApiTransformer::TYPE_KEY]);
167+
}
168+
if ($existingIndex !== false) {
169+
$data[JsonApiTransformer::INCLUDED_KEY][$existingIndex] = \array_filter(\array_merge($data[JsonApiTransformer::INCLUDED_KEY][$existingIndex], $arrayData));
170+
} else {
171+
$data[JsonApiTransformer::INCLUDED_KEY][] = \array_filter($arrayData);
172+
}
165173
}
166174
}
175+
}
167176

168-
if (!empty($data[JsonApiTransformer::INCLUDED_KEY])) {
169-
$data[JsonApiTransformer::INCLUDED_KEY] = \array_values(
170-
\array_unique($data[JsonApiTransformer::INCLUDED_KEY], SORT_REGULAR)
171-
);
177+
protected static function findIncludedIndex($includedData, $idNeedle, $typeNeedle)
178+
{
179+
foreach ($includedData as $key => $value) {
180+
if ($value[JsonApiTransformer::ID_KEY] === $idNeedle && $value[JsonApiTransformer::TYPE_KEY] === $typeNeedle) {
181+
return $key;
182+
}
172183
}
184+
185+
return false;
173186
}
174187

175188
/**

tests/Integrations/Doctrine/DoctrineTest.php

+6-26
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,12 @@ public function testSecondLevelNestingEntitySerialize()
191191
"type":"post",
192192
"id":"1",
193193
"attributes":{
194-
"description":"Description test"
194+
"description":"Description test",
195+
"date":{
196+
"date":"2016-07-12 16:30:12.000000",
197+
"timezone_type":3,
198+
"timezone":"Europe/Madrid"
199+
}
195200
},
196201
"relationships":{
197202
"customer":{
@@ -228,31 +233,6 @@ public function testSecondLevelNestingEntitySerialize()
228233
"href":"http://example.com/comment/1"
229234
}
230235
}
231-
},
232-
{
233-
"type":"post",
234-
"id":"1",
235-
"attributes":{
236-
"date":{
237-
"date":"2016-07-12 16:30:12.000000",
238-
"timezone_type":3,
239-
"timezone":"Europe/Madrid"
240-
},
241-
"description":"Description test"
242-
},
243-
"relationships":{
244-
"customer":{
245-
"data":{
246-
"type":"customer",
247-
"id":"1"
248-
}
249-
}
250-
},
251-
"links":{
252-
"self":{
253-
"href":"http://example.com/post/1"
254-
}
255-
}
256236
}
257237
],
258238
"links":{

0 commit comments

Comments
 (0)