diff --git a/src/Schema/Field/Relationship.php b/src/Schema/Field/Relationship.php index 76627f6..e900a84 100644 --- a/src/Schema/Field/Relationship.php +++ b/src/Schema/Field/Relationship.php @@ -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; @@ -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. @@ -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; } @@ -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'])) { diff --git a/src/Schema/Field/ToMany.php b/src/Schema/Field/ToMany.php index 5d9d585..9decf0b 100644 --- a/src/Schema/Field/ToMany.php +++ b/src/Schema/Field/ToMany.php @@ -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; } diff --git a/src/Schema/Field/ToOne.php b/src/Schema/Field/ToOne.php index ba6e318..85d614c 100644 --- a/src/Schema/Field/ToOne.php +++ b/src/Schema/Field/ToOne.php @@ -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; }