Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support empty collections in _embedded section #80

Merged
merged 38 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
1e98f8d
Update HalResourceTest.php
ghostwriter Jun 8, 2023
ec0ef25
Create empty-contacts-collection.json
ghostwriter Jun 8, 2023
a664f13
Create non-empty-contacts-collection.json
ghostwriter Jun 8, 2023
a77e5bc
Update HalResource.php
ghostwriter Jun 8, 2023
39b7a35
Update HalResourceTest.php
ghostwriter Jun 8, 2023
aa29f66
Fix Psalm issue
ghostwriter Jun 28, 2023
588faf5
Guard against invalid json decoding
ghostwriter Jun 28, 2023
3b01dbc
Fix Phpcs issue
ghostwriter Jun 28, 2023
67fa194
Update ConfigProvider.php
ghostwriter Jul 14, 2023
96327a4
Fix CS issue
ghostwriter Jul 14, 2023
88d9f06
Update HalResource.php
ghostwriter Jul 14, 2023
2538c2b
Update ResourceGenerator.php
ghostwriter Jul 15, 2023
78c2bf5
Create null-contacts-collection.json
ghostwriter Jul 15, 2023
f170e24
Update ResourceGeneratorTest.php
ghostwriter Jul 15, 2023
b0f6d89
Update HalResourceTest.php
ghostwriter Jul 15, 2023
0baf7dc
Update HalResource.php
ghostwriter Jul 15, 2023
bad20ad
Suppress Psalm issue
ghostwriter Jul 15, 2023
d49e1b9
Merge branch 'mezzio:2.7.x' into feature/support-empty-collections-in…
ghostwriter Jul 15, 2023
11ffa3b
Remove doc comment
ghostwriter Jul 18, 2023
ca2b505
Add documentation
ghostwriter Jul 18, 2023
28b572f
Update links-and-resources.md
ghostwriter Jul 18, 2023
e0ddb0e
Fix unrelated cs issue
ghostwriter Jul 18, 2023
0c2aa96
Specify configuration file path
ghostwriter Jul 18, 2023
5a24772
Update src/ResourceGenerator.php
ghostwriter Jul 31, 2023
e7e825d
Update test/HalResourceTest.php
ghostwriter Jul 31, 2023
9330126
Update test/HalResourceTest.php
ghostwriter Jul 31, 2023
228c4e7
Update test/HalResourceTest.php
ghostwriter Jul 31, 2023
27bae41
Update test/HalResourceTest.php
ghostwriter Jul 31, 2023
ba594cc
Update links-and-resources.md
ghostwriter Jul 31, 2023
188caec
Update HalResource.php
ghostwriter Jul 31, 2023
adb411d
Reinstate removed tests
ghostwriter Jul 31, 2023
6be416c
Add phpcs:ignore
ghostwriter Jul 31, 2023
a7b9f9e
Fix pslam issue
ghostwriter Jul 31, 2023
b65df9a
Update docs/book/v2/links-and-resources.md
ghostwriter Aug 1, 2023
a2f1bbf
Update docs/book/v2/links-and-resources.md
ghostwriter Aug 1, 2023
c155d75
Update docs/book/v2/links-and-resources.md
ghostwriter Aug 1, 2023
e82ee83
Update links-and-resources.md
ghostwriter Aug 1, 2023
b432dfd
Update test/HalResourceTest.php
weierophinney Aug 1, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/book/v2/links-and-resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,4 +198,42 @@ $resource = $resource->withLink($link);
$resource = $resource->withoutLink($link);
```

To maintain consistency in the structure of the response, you may choose to embed both non-empty and empty collections within the `_embedded` section. This can be achieved by enabling the `embed-empty-collections` configuration option.
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved

To enable this feature, modify the configuration file as follows:
froschdesign marked this conversation as resolved.
Show resolved Hide resolved

```php
return [
'mezzio-hal' => [
'embed-empty-collections' => false, // (default: false for compatibility reasons)
'metadata-factories' => [...],
'resource-generator' => [...],
],
];
```

The default setting of `false` ensures compatibility with existing API endpoints and prevents potential test failures.

When `embed-empty-collections` is set to `false`, the representation will be as follows:

**`empty-contacts-collection-not-embedded.json`**
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved

```json
{
"contacts": []
}
```

However, when `embed-empty-collections` is set to `true`, the representation will be as follows:

**`empty-contacts-collection-embedded.json`**
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved

``` json
{
"_embedded": {
"contacts": []
}
}
```

With these tools, you can describe any resource you want to represent.
5 changes: 3 additions & 2 deletions src/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,16 @@ public function getDependencies(): array
public function getHalConfig(): array
{
return [
'resource-generator' => [
'embed-empty-collections' => false,
'resource-generator' => [
'strategies' => [ // The registered strategies and their metadata types
RouteBasedCollectionMetadata::class => RouteBasedCollectionStrategy::class,
RouteBasedResourceMetadata::class => RouteBasedResourceStrategy::class,
UrlBasedCollectionMetadata::class => UrlBasedCollectionStrategy::class,
UrlBasedResourceMetadata::class => UrlBasedResourceStrategy::class,
],
],
'metadata-factories' => [ // The factories for the metadata types
'metadata-factories' => [ // The factories for the metadata types
RouteBasedCollectionMetadata::class => RouteBasedCollectionMetadataFactory::class,
RouteBasedResourceMetadata::class => RouteBasedResourceMetadataFactory::class,
UrlBasedCollectionMetadata::class => UrlBasedCollectionMetadataFactory::class,
Expand Down
24 changes: 16 additions & 8 deletions src/HalResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,25 @@ class HalResource implements EvolvableLinkProviderInterface, JsonSerializable
/** @var array<array-key, self|array<array-key, self>> */
private $embedded = [];

private bool $embedEmptyCollections;

/**
* @param array $data
* @param LinkInterface[] $links
* @param HalResource[][] $embedded
*/
public function __construct(array $data = [], array $links = [], array $embedded = [])
{
public function __construct(
array $data = [],
array $links = [],
array $embedded = [],
bool $embedEmptyCollections = false
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved
) {
$this->embedEmptyCollections = $embedEmptyCollections;

$context = self::class;
array_walk($data, function ($value, $name) use ($context) {
$this->validateElementName($name, $context);
if (
! empty($value)
&& ($value instanceof self || $this->isResourceCollection($value))
) {
if ($value instanceof self || $this->isResourceCollection($value)) {
$this->embedded[$name] = $value;
return;
}
Expand Down Expand Up @@ -142,8 +147,7 @@ public function withElement(string $name, $value): HalResource
$this->validateElementName($name, __METHOD__);

if (
! empty($value)
&& ($value instanceof self || $this->isResourceCollection($value))
$value instanceof self || $this->isResourceCollection($value)
) {
return $this->embed($name, $value);
}
Expand Down Expand Up @@ -395,6 +399,10 @@ private function isResourceCollection($value): bool
return false;
}

if ($this->embedEmptyCollections && $value === []) {
return true;
}

return array_reduce($value, static function ($isResource, $item) {
return $isResource && $item instanceof self;
}, true);
Expand Down
8 changes: 7 additions & 1 deletion src/ResourceGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,13 @@ public function getStrategies(): array

public function fromArray(array $data, ?string $uri = null): HalResource
{
$resource = new HalResource($data);
/** @psalm-suppress MixedArrayAccess */
$embedEmptyCollections =
$this->hydrators->has('config') &&
$this->hydrators->get('config')['mezzio-hal']['embed-empty-collections'] ??
false;
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved

$resource = new HalResource($data, [], [], $embedEmptyCollections);

if (null !== $uri) {
return $resource->withLink(new Link('self', $uri));
Expand Down
10 changes: 10 additions & 0 deletions test/Fixture/empty-contacts-collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"_links": {
"self": {
"href": "/api/contacts"
}
},
"_embedded": {
"contacts": []
}
}
21 changes: 21 additions & 0 deletions test/Fixture/non-empty-contacts-collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"_links": {
"self": {
"href": "/api/contacts"
}
},
"_embedded": {
"contacts": [
{
"id": 1,
"name": "John",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane",
"email": "jane@example.com"
}
]
}
}
8 changes: 8 additions & 0 deletions test/Fixture/null-contacts-collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"contacts": null,
"_links": {
"self": {
"href": "/api/contacts"
}
}
}
123 changes: 120 additions & 3 deletions test/HalResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@

namespace MezzioTest\Hal;

use Generator;
use InvalidArgumentException;
use Mezzio\Hal\HalResource;
use Mezzio\Hal\Link;
use PHPUnit\Framework\TestCase;
use RuntimeException;

use function array_values;
use function file_get_contents;
use function is_array;
use function json_decode;

class HalResourceTest extends TestCase
{
Expand Down Expand Up @@ -235,13 +239,22 @@ public function testWithElementProxiesToEmbedIfResourceCollectionValueProvided()
$this->assertEquals(['foo' => $collection], $new->getElements());
}

public function testWithElementDoesNotProxyToEmbedIfAnEmptyArrayValueIsProvided(): void
public function testWithElementWillEmbedAnEmptyArrayIfAnEmptyArrayValueIsProvided(): void
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved
{
$resource = new HalResource(['foo' => 'bar']);
$resource = new HalResource(['foo' => 'bar'], [], [], true);
$new = $resource->withElement('bar', []);

$representation = $new->toArray();
$this->assertEquals(['foo' => 'bar', 'bar' => []], $representation);
self::assertSame(['foo' => 'bar', '_embedded' => ['bar' => []]], $representation);
}

public function testWithElementDoesNotProxyToEmbedIfNullValueIsProvided(): void
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved
{
$resource = new HalResource(['foo' => 'bar'], [], [], true);
$new = $resource->withElement('bar', null);

$representation = $new->toArray();
self::assertSame(['foo' => 'bar', 'bar' => null], $representation);
}

/**
Expand Down Expand Up @@ -636,4 +649,108 @@ public function testAllowsForcingLinkToAggregateAsACollection(): void

$this->assertEquals($expected, $resource->toArray());
}

private function fixture(string $file): array
{
$contents = file_get_contents(__DIR__ . '/Fixture/' . $file);

if ($contents === false) {
throw new RuntimeException('Failed to read fixture file: ' . $file);
}

$json = json_decode($contents, true);
if (! is_array($json)) {
throw new RuntimeException('Failed to json_decode fixture file: ' . $file);
}

return $json;
}

/**
* @return Generator<string,array<array-key,array<array-key,HalResource>>>
*/
public static function nonEmptyCollectionDataProvider(): Generator
{
yield from [
'collection' => [
[
(new HalResource())->withElements([
'id' => 1,
'name' => 'John',
'email' => 'john@example.com',
]),
(new HalResource())->withElements([
'id' => 2,
'name' => 'Jane',
'email' => 'jane@example.com',
]),
],
],
];
}

/**
* @return Generator<'array',list{array<never,never>},mixed,void>
*/
public static function emptyCollectionDataProvider(): Generator
{
yield from [
'array' => [[]],
];
}

/**
* @dataProvider emptyCollectionDataProvider
*/
public function testEmptyCollection(mixed $collection): void
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved
{
$resource = (new HalResource([], [], [], true))
->withLink(new Link('self', '/api/contacts'))
->withElements(['contacts' => $collection]);

self::assertSame(
$this->fixture('empty-contacts-collection.json'),
$resource->toArray()
);
}

/**
* @dataProvider nonEmptyCollectionDataProvider
*/
public function testNonEmptyCollection(mixed $collection): void
{
$resource = (new HalResource())
->withLink(new Link('self', '/api/contacts'))
->withElements(['contacts' => $collection]);

self::assertSame(
$this->fixture('non-empty-contacts-collection.json'),
$resource->toArray()
);
}

/**
* @return Generator<'null',list{null},mixed,void>
*/
public static function nullCollectionDataProvider(): Generator
{
yield from [
'null' => [null],
];
}

/**
* @dataProvider nullCollectionDataProvider
*/
public function testNullCollection(mixed $collection): void
ghostwriter marked this conversation as resolved.
Show resolved Hide resolved
{
$resource = (new HalResource([], [], [], true))
->withLink(new Link('self', '/api/contacts'))
->withElements(['contacts' => $collection]);

self::assertSame(
$this->fixture('null-contacts-collection.json'),
$resource->toArray()
);
}
}
3 changes: 3 additions & 0 deletions test/ResourceGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ public function testCanGenerateResourceWithSelfLinkFromArrayData(): void
'foo' => 'bar',
'bar' => 'baz',
];

$this->hydrators->has('config')->willReturn(false);

$this->linkGenerator->fromRoute()->shouldNotBeCalled();
$this->metadataMap->has()->shouldNotBeCalled();

Expand Down
Loading