diff --git a/src/Item.php b/src/Item.php index 7b6fcbb..eace119 100644 --- a/src/Item.php +++ b/src/Item.php @@ -130,26 +130,27 @@ public function getRelationships(): array $relationships = []; foreach ($this->getRelations() as $name => $relation) { + if (!$relation->hasIncluded()) { + continue; + } + if ($relation instanceof OneRelationInterface) { - $relationships[$name] = ['data' => null]; + $relationships[$name]['data'] = null; if ($relation->getIncluded() !== null) { - $relationships[$name] = [ - 'data' => [ - 'type' => $relation->getIncluded()->getType(), - 'id' => $relation->getIncluded()->getId(), - ], + $relationships[$name]['data'] = [ + 'type' => $relation->getIncluded()->getType(), + 'id' => $relation->getIncluded()->getId(), ]; } } elseif ($relation instanceof ManyRelationInterface) { $relationships[$name]['data'] = []; foreach ($relation->getIncluded() as $item) { - $relationships[$name]['data'][] = - [ - 'type' => $item->getType(), - 'id' => $item->getId(), - ]; + $relationships[$name]['data'][] = [ + 'type' => $item->getType(), + 'id' => $item->getId(), + ]; } } } diff --git a/tests/ItemTest.php b/tests/ItemTest.php index 7a69859..3c64648 100644 --- a/tests/ItemTest.php +++ b/tests/ItemTest.php @@ -119,6 +119,24 @@ public function is_adds_empty_hasone_relation_in_to_json_api_array() ); } + /** + * @test + */ + public function is_does_not_add_hasone_relation_without_data_in_to_json_api_array() + { + $item = new WithRelationshipItem(); + $item->setId('1234'); + $item->hasoneRelation(); + + $this->assertSame( + [ + 'type' => 'item-with-relationship', + 'id' => '1234', + ], + $item->toJsonApiArray() + ); + } + /** * @test */ @@ -170,6 +188,24 @@ public function is_adds_empty_hasmany_relation_in_to_json_api_array() ); } + /** + * @test + */ + public function is_does_not_add_hasmany_relation_without_data_in_to_json_api_array() + { + $item = new WithRelationshipItem(); + $item->setId('1234'); + $item->hasmanyRelation(); + + $this->assertSame( + [ + 'type' => 'item-with-relationship', + 'id' => '1234', + ], + $item->toJsonApiArray() + ); + } + /** * @test */ @@ -219,6 +255,24 @@ public function is_adds_empty_morphto_relation_in_to_json_api_array() ); } + /** + * @test + */ + public function is_does_not_add_morphto_relation_without_data_in_to_json_api_array() + { + $item = new WithRelationshipItem(); + $item->setId('1234'); + $item->morphtoRelation(); + + $this->assertSame( + [ + 'type' => 'item-with-relationship', + 'id' => '1234', + ], + $item->toJsonApiArray() + ); + } + /** * @test */ @@ -270,6 +324,24 @@ public function is_adds_empty_morphtomany_relation_in_to_json_api_array() ); } + /** + * @test + */ + public function is_does_not_add_morphtomany_relation_without_data_in_to_json_api_array() + { + $item = new WithRelationshipItem(); + $item->setId('1234'); + $item->morphtomanyRelation(); + + $this->assertSame( + [ + 'type' => 'item-with-relationship', + 'id' => '1234', + ], + $item->toJsonApiArray() + ); + } + /** * @test */