Skip to content

Commit

Permalink
Links with rel="_self" are assigned to itself
Browse files Browse the repository at this point in the history
If the Page resource uses the value of the App resource as is.
  • Loading branch information
koriym committed Apr 4, 2024
1 parent 7ac9498 commit f6d131a
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/EmbedInterceptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

final class EmbedInterceptor implements MethodInterceptor
{
private const SELF_LINK = '_self';

private readonly ResourceInterface $resource;

public function __construct(
Expand Down Expand Up @@ -71,6 +73,12 @@ private function embedResource(array $embeds, ResourceObject $ro, array $query):
throw new LinkException($embed->rel); // @codeCoverageIgnore
}

if ($embed->rel === self::SELF_LINK) {
$this->linkSelf($request, $ro);

continue;
}

$ro->body[$embed->rel] = clone $request;
} catch (BadRequestException $e) {
// wrap ResourceNotFound or Uri exception
Expand Down Expand Up @@ -101,4 +109,12 @@ private function getArgsByInvocation(MethodInvocation $invocation): array

return $namedParameters;
}

public function linkSelf(Request $request, ResourceObject $ro): void
{
$result = $request();
foreach ($result as $key => $value) {
$ro->body[$key] = $value;
}
}
}
7 changes: 7 additions & 0 deletions tests/EmbedInterceptorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ public function testInvoke(): Birds
return $result;
}

public function testSelfLink(): void
{
$embeded = $this->resource->uri('app://self/bird/child')(['id' => 1]);
$result = $this->resource->uri('app://self/bird/self-link')(['id' => 1]);
$this->assertSame($result->body, $embeded->body);
}

public function testInvokeRelativePath(): BirdsRel
{
$result = $this->resource->uri('app://self/bird/birds-rel')(['id' => 1]);
Expand Down
19 changes: 19 additions & 0 deletions tests/Fake/FakeVendor/Sandbox/Resource/App/Bird/Child.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace FakeVendor\Sandbox\Resource\App\Bird;

use BEAR\Resource\ResourceObject;

class Child extends ResourceObject
{
public function onGet(string $id)
{
$this->body = [
'id' => $id
];

return $this;
}
}
18 changes: 18 additions & 0 deletions tests/Fake/FakeVendor/Sandbox/Resource/App/Bird/SelfLink.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace FakeVendor\Sandbox\Resource\App\Bird;

use BEAR\Resource\Annotation\Embed;
use BEAR\Resource\Annotation\Link;
use BEAR\Resource\ResourceObject;

class SelfLink extends ResourceObject
{
#[Embed(rel: "_self", src: "app://self/bird/child{?id}")]
public function onGet(string $id)
{
return $this;
}
}

0 comments on commit f6d131a

Please sign in to comment.