Skip to content

Commit

Permalink
Merge pull request #80 from ghostwriter/feature/support-empty-collect…
Browse files Browse the repository at this point in the history
…ions-in-embedded-section

Support empty collections in `_embedded` section
  • Loading branch information
weierophinney committed Aug 1, 2023
2 parents 07dff20 + b432dfd commit 3d94ebd
Show file tree
Hide file tree
Showing 12 changed files with 260 additions and 31 deletions.
14 changes: 7 additions & 7 deletions README.md
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
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.

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
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
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
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 === [] ||
$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
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
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
@@ -0,0 +1,10 @@
{
"_links": {
"self": {
"href": "/api/contacts"
}
},
"_embedded": {
"contacts": []
}
}
21 changes: 21 additions & 0 deletions test/Fixture/non-empty-contacts-collection.json
@@ -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
@@ -0,0 +1,8 @@
{
"contacts": null,
"_links": {
"self": {
"href": "/api/contacts"
}
}
}

0 comments on commit 3d94ebd

Please sign in to comment.