diff --git a/src/Core/Document/Links.php b/src/Core/Document/Links.php index fb3147a..fdbd363 100644 --- a/src/Core/Document/Links.php +++ b/src/Core/Document/Links.php @@ -191,12 +191,23 @@ public function hasRelated(): bool return $this->has('related'); } + /** + * @return $this + */ public function relatedAsSelf(): self { - if($this->forget('self')->hasRelated()){ - $this->push(Link::fromArray('self', $this->getRelated()->toArray())); + $related = $this->getRelated(); + + if ($related) { + $this->push(new Link( + key: 'self', + href: $related->href(), + meta: $related->meta(), + )); + return $this->forget('related'); } - return $this->forget('related'); + + return $this->forget('self'); } /** diff --git a/src/Core/Responses/Internal/RelatedResourceCollectionResponse.php b/src/Core/Responses/Internal/RelatedResourceCollectionResponse.php index 986046c..14e9b0b 100644 --- a/src/Core/Responses/Internal/RelatedResourceCollectionResponse.php +++ b/src/Core/Responses/Internal/RelatedResourceCollectionResponse.php @@ -60,7 +60,7 @@ public function toResponse($request) ->withResources($this->related) ->withJsonApi($this->jsonApi()) ->withMeta($this->allMeta()) - ->withLinks($this->allLinks()->relatedAsSelf()) + ->withLinks($this->allLinks()) ->toJson($this->encodeOptions); return new Response( @@ -69,4 +69,17 @@ public function toResponse($request) $this->headers() ); } + + /** + * Get all links. + * + * @return Links + */ + private function allLinks(): Links + { + return $this + ->linksForRelationship() + ->relatedAsSelf() + ->merge($this->links()); + } } diff --git a/src/Core/Responses/Internal/RelatedResourceResponse.php b/src/Core/Responses/Internal/RelatedResourceResponse.php index 6c1fc17..0b9ea61 100644 --- a/src/Core/Responses/Internal/RelatedResourceResponse.php +++ b/src/Core/Responses/Internal/RelatedResourceResponse.php @@ -61,7 +61,7 @@ public function toResponse($request) ->withResource($this->related) ->withJsonApi($this->jsonApi()) ->withMeta($this->allMeta()) - ->withLinks($this->allLinks()->relatedAsSelf()) + ->withLinks($this->allLinks()) ->toJson($this->encodeOptions); return new Response( @@ -70,4 +70,17 @@ public function toResponse($request) $this->headers() ); } + + /** + * Get all links. + * + * @return Links + */ + private function allLinks(): Links + { + return $this + ->linksForRelationship() + ->relatedAsSelf() + ->merge($this->links()); + } }