Skip to content
This repository was archived by the owner on Jan 29, 2020. It is now read-only.

Commit e187d63

Browse files
committed
Allow empty array in data
- added check for empty array in data to avoid unnecessary embedded data with empty lists
1 parent 7dddd68 commit e187d63

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/HalResource.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public function __construct(array $data = [], array $links = [], array $embedded
6161
$context = __CLASS__;
6262
array_walk($data, function ($value, $name) use ($context) {
6363
$this->validateElementName($name, $context);
64-
if ($value instanceof self || $this->isResourceCollection($value, $name, $context)) {
64+
if (!empty($value) && ($value instanceof self || $this->isResourceCollection($value, $name, $context))) {
6565
$this->embedded[$name] = $value;
6666
return;
6767
}
@@ -148,7 +148,7 @@ public function withElement(string $name, $value) : HalResource
148148
{
149149
$this->validateElementName($name, __METHOD__);
150150

151-
if ($value instanceof self || $this->isResourceCollection($value, $name, __METHOD__)) {
151+
if (!empty($value) && ($value instanceof self || $this->isResourceCollection($value, $name, __METHOD__))) {
152152
return $this->embed($name, $value);
153153
}
154154

test/HalResourceTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,14 @@ public function testNonResourceOrCollectionItemsRaiseExceptionDuringConstruction
9292
$resource = new HalResource([], [], ['foo' => 'bar']);
9393
}
9494

95+
public function testEmptyArrayAsDataWillNotBeEmbeddedDuringConstruction()
96+
{
97+
$resource = new HalResource(['bar' => []]);
98+
$this->assertEquals(['bar' => []], $resource->getElements());
99+
$representation = $resource->toArray();
100+
$this->assertArrayNotHasKey('_embeded', $representation);
101+
}
102+
95103
/**
96104
* @dataProvider invalidElementNames
97105
*/
@@ -222,6 +230,15 @@ public function testWithElementProxiesToEmbedIfResourceCollectionValueProvided()
222230
$this->assertEquals(['foo' => $collection], $new->getElements());
223231
}
224232

233+
public function testWithElementNotProxiesToEmbededIfEmptyArrayValueProvided()
234+
{
235+
$resource = new HalResource(['foo' => 'bar']);
236+
$new = $resource->withElement('bar', []);
237+
238+
$representation = $new->toArray();
239+
$this->assertEquals(['foo' => 'bar', 'bar' => []], $representation);
240+
}
241+
225242
/**
226243
* @dataProvider invalidElementNames
227244
*/

0 commit comments

Comments
 (0)