Skip to content

Commit

Permalink
Merge pull request #13559 from archilex/Allow-table-groups-to-accept-…
Browse files Browse the repository at this point in the history
…closure

Allow table groups to accept a closure
  • Loading branch information
danharrin authored Jul 17, 2024
2 parents 7d72266 + 9178bbb commit 0113c83
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions packages/tables/src/Table/Concerns/CanGroupRecords.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ trait CanGroupRecords
/**
* @var array<string, Group>
*/
protected array $groups = [];
protected ?array $cachedGroups;

/**
* @var array<string | Group> | Closure
*/
protected array | Closure $groups = [];

protected bool | Closure $isGroupsOnly = false;

Expand Down Expand Up @@ -73,17 +78,11 @@ public function defaultGroup(string | Group | null $group): static
}

/**
* @param array<Group | string> $groups
* @param array<string | Group> | Closure $groups
*/
public function groups(array $groups): static
public function groups(array | Closure $groups): static
{
foreach ($groups as $group) {
if (! $group instanceof Group) {
$group = Group::make($group);
}

$this->groups[$group->getId()] = $group;
}
$this->groups = $groups;

return $this;
}
Expand Down Expand Up @@ -168,7 +167,19 @@ public function getDefaultGroup(): ?Group
*/
public function getGroups(): array
{
return $this->groups;
return $this->cachedGroups ??= array_reduce(
$this->evaluate($this->groups),
function (array $carry, $group): array {
if (! $group instanceof Group) {
$group = Group::make($group);
}

$groups[$group->getId()] = $group;

return $groups;
},
initial: [],
);
}

public function getGroup(string $id): ?Group
Expand Down

0 comments on commit 0113c83

Please sign in to comment.