Skip to content

Commit 54426f0

Browse files
committed
test: relationship with custom value
1 parent 1d40abe commit 54426f0

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/Relationship.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public function toArray($request, bool $minimal = false): array
4949
];
5050
}
5151

52-
if (method_exists($resource, 'toArray')) {
52+
if (is_object($resource) && method_exists($resource, 'toArray')) {
5353
$datum = $resource->toArray($request, $minimal);
5454
} else {
5555
$datum = collect($resource)->toArray();
@@ -67,20 +67,24 @@ public function toArray($request, bool $minimal = false): array
6767
$included[] = $value;
6868
}
6969
}
70-
} else {
70+
} elseif ($resource instanceof JsonResource) {
7171
$data['data'] = [
7272
'type' => $datum['type'],
7373
'id' => $datum['id']
7474
];
7575
if (!$minimal) {
7676
$included[] = $datum;
7777
}
78+
} else {
79+
$data['data'] = $datum;
7880
}
7981

8082
return array_filter([
8183
'data' => array_filter($data),
8284
'included' => $included,
83-
'with' => method_exists($resource, 'with') ? $resource->with($request) : null
85+
'with' => is_object($resource) && method_exists($resource, 'with')
86+
? $resource->with($request)
87+
: null
8488
]);
8589
}
8690

tests/Unit/RelationshipTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,28 @@ public function testToArrayMissingValue()
140140
], $relation->toArray(new Request(), true));
141141
}
142142

143+
public function testCustomValue()
144+
{
145+
$resource = $this->getJsonResourceMissingValue();
146+
$relation = (new Relationship([
147+
'foo' => 'bar'
148+
]))->withLinks([
149+
'self' => 'link'
150+
])->withMeta([
151+
'hash' => 'azerty'
152+
]);
153+
154+
$this->assertEquals([
155+
'data' => [
156+
'data' => [
157+
'foo' => 'bar'
158+
],
159+
'links' => ['self' => 'link'],
160+
'meta' => ['hash' => 'azerty'],
161+
],
162+
], $relation->toArray(new Request(), true));
163+
}
164+
143165
private function getJsonResource()
144166
{
145167
return new class((object)['id' => 1]) extends JsonResource implements Resourceable {

0 commit comments

Comments
 (0)