diff --git a/README.md b/README.md index 743a7d7..def2cc4 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/book/v2/links-and-resources.md b/docs/book/v2/links-and-resources.md index f5da3cf..c7db6ae 100644 --- a/docs/book/v2/links-and-resources.md +++ b/docs/book/v2/links-and-resources.md @@ -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. diff --git a/psalm-baseline.xml b/psalm-baseline.xml index 0f2ee51..9fd5442 100644 --- a/psalm-baseline.xml +++ b/psalm-baseline.xml @@ -448,9 +448,6 @@ - - $page - protected function generateSelfLink( diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 8eaeacc..708da08 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -69,7 +69,8 @@ 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, @@ -77,7 +78,7 @@ public function getHalConfig(): array 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, diff --git a/src/HalResource.php b/src/HalResource.php index 929a41e..f8940bc 100644 --- a/src/HalResource.php +++ b/src/HalResource.php @@ -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; @@ -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 ( @@ -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); } @@ -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); diff --git a/src/ResourceGenerator.php b/src/ResourceGenerator.php index e441b9a..4dcfd61 100644 --- a/src/ResourceGenerator.php +++ b/src/ResourceGenerator.php @@ -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)); diff --git a/src/ResourceGenerator/UrlBasedCollectionStrategy.php b/src/ResourceGenerator/UrlBasedCollectionStrategy.php index 0847f9a..8fbf67d 100644 --- a/src/ResourceGenerator/UrlBasedCollectionStrategy.php +++ b/src/ResourceGenerator/UrlBasedCollectionStrategy.php @@ -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 diff --git a/test/Fixture/empty-contacts-collection.json b/test/Fixture/empty-contacts-collection.json new file mode 100644 index 0000000..51f4231 --- /dev/null +++ b/test/Fixture/empty-contacts-collection.json @@ -0,0 +1,10 @@ +{ + "_links": { + "self": { + "href": "/api/contacts" + } + }, + "_embedded": { + "contacts": [] + } +} diff --git a/test/Fixture/non-empty-contacts-collection.json b/test/Fixture/non-empty-contacts-collection.json new file mode 100644 index 0000000..9864e3b --- /dev/null +++ b/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" + } + ] + } +} diff --git a/test/Fixture/null-contacts-collection.json b/test/Fixture/null-contacts-collection.json new file mode 100644 index 0000000..7768a7c --- /dev/null +++ b/test/Fixture/null-contacts-collection.json @@ -0,0 +1,8 @@ +{ + "contacts": null, + "_links": { + "self": { + "href": "/api/contacts" + } + } +} diff --git a/test/HalResourceTest.php b/test/HalResourceTest.php index de4c53f..005ddeb 100644 --- a/test/HalResourceTest.php +++ b/test/HalResourceTest.php @@ -4,6 +4,7 @@ namespace MezzioTest\Hal; +use Generator; use InvalidArgumentException; use Mezzio\Hal\HalResource; use Mezzio\Hal\Link; @@ -11,6 +12,9 @@ use RuntimeException; use function array_values; +use function file_get_contents; +use function is_array; +use function json_decode; class HalResourceTest extends TestCase { @@ -237,11 +241,30 @@ public function testWithElementProxiesToEmbedIfResourceCollectionValueProvided() public function testWithElementDoesNotProxyToEmbedIfAnEmptyArrayValueIsProvided(): void { - $resource = new HalResource(['foo' => 'bar']); + $resource = new HalResource(['foo' => 'bar'], embedEmptyCollections: false); $new = $resource->withElement('bar', []); $representation = $new->toArray(); - $this->assertEquals(['foo' => 'bar', 'bar' => []], $representation); + self::assertSame(['foo' => 'bar', 'bar' => []], $representation); + } + + // phpcs:ignore + public function testWithElementWillEmbedAnEmptyArrayIfAnEmptyArrayValueIsProvidedAndConfiguredToEmbedEmptyCollections(): void + { + $resource = new HalResource(['foo' => 'bar'], embedEmptyCollections: true); + $new = $resource->withElement('bar', []); + + $representation = $new->toArray(); + self::assertSame(['foo' => 'bar', '_embedded' => ['bar' => []]], $representation); + } + + public function testWithElementDoesNotProxyToEmbedIfNullValueIsProvidedAndEmbedEmptyCollectionsEnabled(): void + { + $resource = new HalResource(['foo' => 'bar'], [], [], true); + $new = $resource->withElement('bar', null); + + $representation = $new->toArray(); + self::assertSame(['foo' => 'bar', 'bar' => null], $representation); } /** @@ -636,4 +659,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>> + */ + 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},mixed,void> + */ + public static function emptyCollectionDataProvider(): Generator + { + yield from [ + 'array' => [[]], + ]; + } + + /** + * @dataProvider emptyCollectionDataProvider + */ + public function testEmptyCollectionWhenEmbedEmptyEnabled(mixed $collection): void + { + $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 testNullCollectionWhenEmbedEmptyEnabled(mixed $collection): void + { + $resource = (new HalResource([], [], [], true)) + ->withLink(new Link('self', '/api/contacts')) + ->withElements(['contacts' => $collection]); + + self::assertSame( + $this->fixture('null-contacts-collection.json'), + $resource->toArray() + ); + } } diff --git a/test/ResourceGeneratorTest.php b/test/ResourceGeneratorTest.php index 5c071e7..ddde16d 100644 --- a/test/ResourceGeneratorTest.php +++ b/test/ResourceGeneratorTest.php @@ -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();