Skip to content

Commit

Permalink
Refactor AddsIncludesToQuery trait to add default includes handling
Browse files Browse the repository at this point in the history
  • Loading branch information
inmass committed Sep 23, 2024
1 parent 34f35ce commit 1c58225
Showing 1 changed file with 32 additions and 13 deletions.
45 changes: 32 additions & 13 deletions src/Concerns/AddsIncludesToQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,35 @@
trait AddsIncludesToQuery
{
protected ?Collection $allowedIncludes = null;
protected ?Collection $defaultIncludes = null;

public function allowedIncludes($includes): static
{
$includes = is_array($includes) ? $includes : func_get_args();

$this->allowedIncludes = collect($includes)
$this->allowedIncludes = $this->parseIncludes($includes);

$this->ensureAllIncludesExist();

$includes = $this->filterNonExistingIncludes($this->request->includes());

$this->addIncludesToQuery($includes);

return $this;
}

public function defaultIncludes($includes): static
{
$this->defaultIncludes = $this->parseIncludes($includes);

$this->addIncludesToQuery(collect($includes));

return $this;
}

protected function parseIncludes($includes): Collection
{
return collect($includes)
->reject(function ($include) {
return empty($include);
})
Expand All @@ -39,17 +62,9 @@ public function allowedIncludes($includes): static

return AllowedInclude::relationship($include);
})
->unique(function (AllowedInclude $allowedInclude) {
return $allowedInclude->getName();
->unique(function (AllowedInclude $include) {
return $include->getName();
});

$this->ensureAllIncludesExist();

$includes = $this->filterNonExistingIncludes($this->request->includes());

$this->addIncludesToQuery($includes);

return $this;
}

protected function addIncludesToQuery(Collection $includes): void
Expand All @@ -63,7 +78,11 @@ protected function addIncludesToQuery(Collection $includes): void

protected function findInclude(string $include): ?AllowedInclude
{
return $this->allowedIncludes
$allowedIncludes = $this->allowedIncludes ?? collect();
$defaultIncludes = $this->defaultIncludes ?? collect();
$includes = $allowedIncludes->merge($defaultIncludes);

return $includes
->first(fn (AllowedInclude $included) => $included->isForInclude($include));
}

Expand Down Expand Up @@ -97,4 +116,4 @@ protected function filterNonExistingIncludes(Collection $includes): Collection

return $includes->filter(fn ($include) => ! is_null($this->findInclude($include)));
}
}
}

0 comments on commit 1c58225

Please sign in to comment.