Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
22 changes: 15 additions & 7 deletions src/Schema/Field/Relationship.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tobyz\JsonApiServer\Schema\Field;

use Closure;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint\Concerns\FindsResources;
use Tobyz\JsonApiServer\Exception\BadRequestException;
Expand All @@ -14,7 +15,7 @@ abstract class Relationship extends Field

public array $collections;
public bool $includable = false;
public bool $linkage = false;
public bool|Closure $linkage = false;

/**
* Set the collection(s) that this relationship is to.
Expand Down Expand Up @@ -47,9 +48,9 @@ public function includable(): static
/**
* Include linkage for this relationship.
*/
public function withLinkage(): static
public function withLinkage(bool|Closure $condition = true): static
{
$this->linkage = true;
$this->linkage = $condition;

return $this;
}
Expand All @@ -59,20 +60,27 @@ public function withLinkage(): static
*/
public function withoutLinkage(): static
{
$this->linkage = false;

return $this;
return $this->withLinkage(false);
}

public function getValue(Context $context): mixed
{
if ($context->include === null && !$this->linkage) {
if ($context->include === null && !$this->hasLinkage($context)) {
return null;
}

return parent::getValue($context);
}

public function hasLinkage(Context $context): mixed
{
if ($this->linkage instanceof Closure) {
return ($this->linkage)($context);
}

return $this->linkage;
}

protected function findResourceForIdentifier(array $identifier, Context $context): mixed
{
if (!isset($identifier['type'])) {
Expand Down
5 changes: 4 additions & 1 deletion src/Schema/Field/ToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ public function serializeValue($value, Context $context): mixed
{
$meta = $this->serializeMeta($context);

if ((($context->include === null && !$this->linkage) || $value === null) && !$meta) {
if (
(($context->include === null && !$this->hasLinkage($context)) || $value === null) &&
!$meta
) {
return null;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Schema/Field/ToOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function serializeValue($value, Context $context): mixed
{
$meta = $this->serializeMeta($context);

if ($context->include === null && !$this->linkage && !$meta) {
if ($context->include === null && !$this->hasLinkage($context) && !$meta) {
return null;
}

Expand Down