Skip to content

Commit 90ec46d

Browse files
committed
Omit item from included when it has no attributes or relationships
1 parent 60109a6 commit 90ec46d

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

CHANGELOG.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
66

77
## [Unreleased]
88

9-
* Nothing
9+
### Fixed
10+
11+
* Omit item from included when it has no attributes or relationships (only type and id)
12+
N.B. This is a breaking change if you implement the `ItemInterface` yourself instead of using the supplied `Item`.
1013

1114
## [0.12.1] - 2019-01-11
1215

src/Interfaces/ItemInterface.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,9 @@ public function setRelation($relation, $value);
9393
* @return \Swis\JsonApi\Client\Collection
9494
*/
9595
public function getIncluded();
96+
97+
/**
98+
* @return bool
99+
*/
100+
public function canBeIncluded(): bool;
96101
}

src/Item.php

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,14 +203,14 @@ public function getIncluded(): Collection
203203

204204
$includedFromRelationship = $relationship->getIncluded();
205205
if ($includedFromRelationship instanceof ItemInterface) {
206-
if (!empty($includedFromRelationship->getType()) && null !== $includedFromRelationship->getId()) {
206+
if ($includedFromRelationship->canBeIncluded()) {
207207
$included->push($includedFromRelationship->toJsonApiArray());
208208
}
209209
$included = $included->merge($includedFromRelationship->getIncluded());
210210
} elseif ($includedFromRelationship instanceof Collection) {
211211
$includedFromRelationship->each(
212212
function (ItemInterface $item) use (&$included) {
213-
if (!empty($item->getType()) && null !== $item->getId()) {
213+
if ($item->canBeIncluded()) {
214214
$included->push($item->toJsonApiArray());
215215
}
216216
$included = $included->merge($item->getIncluded());
@@ -228,6 +228,26 @@ function (array $item) {
228228
);
229229
}
230230

231+
/**
232+
* @return bool
233+
*/
234+
public function canBeIncluded(): bool
235+
{
236+
if (empty($this->getType())) {
237+
return false;
238+
}
239+
240+
if (null === $this->getId()) {
241+
return false;
242+
}
243+
244+
if (empty($this->relationships) && empty($this->toArray())) {
245+
return false;
246+
}
247+
248+
return true;
249+
}
250+
231251
/**
232252
* @param string $key
233253
*

0 commit comments

Comments
 (0)