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 37 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
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
[![Build Status](https://github.com/mezzio/mezzio-hal/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/mezzio/mezzio-hal/actions/workflows/continuous-integration.yml)

> ## 🇷🇺 Русским гражданам
>
>
> Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.
>
>
> У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.
>
>
> Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"
>
>
> ## 🇺🇸 To Citizens of Russia
>
>
> We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.
>
>
> One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.
>
>
> You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

This library provides utilities for modeling HAL resources with links and generating [PSR-7](https://www.php-fig.org/psr/psr-7/) responses representing both JSON and XML serializations of them.
Expand Down
39 changes: 39 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,43 @@ $resource = $resource->withLink($link);
$resource = $resource->withoutLink($link);
```

### Embed Empty Collection

> INFO: **New Feature**
> Available since version 2.7.0.

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 `config/autoload/hal.global.php` as follows:

```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:

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

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

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

With these tools, you can describe any resource you want to represent.
3 changes: 0 additions & 3 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -448,9 +448,6 @@
</MixedArrayOffset>
</file>
<file src="src/ResourceGenerator/UrlBasedCollectionStrategy.php">
<InvalidArgument>
<code>$page</code>
</InvalidArgument>
<MethodSignatureMismatch>
<code>protected function generateSelfLink(</code>
</MethodSignatureMismatch>
Expand Down
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
48 changes: 33 additions & 15 deletions src/HalResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use function array_shift;
use function array_walk;
use function count;
use function get_debug_type;
use function gettype;
use function in_array;
use function is_array;
Expand Down Expand Up @@ -47,32 +48,46 @@ class HalResource implements EvolvableLinkProviderInterface, JsonSerializable
* @param LinkInterface[] $links
* @param HalResource[][] $embedded
*/
public function __construct(array $data = [], array $links = [], array $embedded = [])
{
public function __construct(
array $data = [],
array $links = [],
array $embedded = [],
private bool $embedEmptyCollections = false
) {
$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;
}

$this->data[$name] = $value;
});

array_walk($embedded, function ($resource, $name) use ($context) {
$this->validateElementName($name, $context);
$this->detectCollisionWithData($name, $context);
if (! ($resource instanceof self || $this->isResourceCollection($resource))) {
throw new InvalidArgumentException(sprintf(
'Invalid embedded resource provided to %s constructor with name "%s"',
$context,
$name
));

if (
$resource instanceof self ||
$resource === [] ||
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$resource === [] || because old behavior allows empty arrays.

$this->isResourceCollection($resource)
) {
$this->embedded[$name] = $resource;
return;
}
$this->embedded[$name] = $resource;

throw new InvalidArgumentException(sprintf(
'Invalid embedded resource provided to %s constructor with name "%s":"%s"',
$context,
$name,
get_debug_type($resource)
));
});

if (
Expand Down Expand Up @@ -142,8 +157,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 +409,10 @@ private function isResourceCollection($value): bool
return false;
}

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

return array_reduce($value, static function ($isResource, $item) {
return $isResource && $item instanceof self;
}, true);
Expand Down
7 changes: 6 additions & 1 deletion src/ResourceGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ 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;

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

if (null !== $uri) {
return $resource->withLink(new Link('self', $uri));
Expand Down
2 changes: 1 addition & 1 deletion src/ResourceGenerator/UrlBasedCollectionStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ protected function generateLinkForPage(

switch ($paginationType) {
case Metadata\AbstractCollectionMetadata::TYPE_PLACEHOLDER:
$url = str_replace($url, $paginationParam, $page);
$url = str_replace($url, $paginationParam, (string) $page);
break;
case Metadata\AbstractCollectionMetadata::TYPE_QUERY:
// fall-through
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"
}
}
}
Loading