adrema/app/Member/Data/NestedGroup.php

40 lines
954 B
PHP
Raw Normal View History

2023-04-25 00:28:44 +02:00
<?php
namespace App\Member\Data;
use App\Group;
use Illuminate\Support\Collection;
use Spatie\LaravelData\Data;
class NestedGroup extends Data
{
public function __construct(
public int $id,
public string $name,
) {
}
/**
* @return Collection<int, array{name: string, id: int}>
*/
public static function forSelect(?int $parentId = null, int $level = 0): Collection
{
$groups = collect([]);
foreach (Group::where('parent_id', $parentId)->orderBy('name')->get()->toBase() as $group) {
2024-09-22 01:41:56 +02:00
$groups->push(['name' => str_repeat('- ', $level) . $group->name, 'id' => $group->id]);
2023-04-25 00:28:44 +02:00
$groups = $groups->merge(static::forSelect($group->id, $level + 1));
}
return $groups;
}
/**
2024-09-22 01:41:56 +02:00
* @return Collection<int, static>
2023-04-25 00:28:44 +02:00
*/
2024-09-22 01:41:56 +02:00
public static function cacheForSelect(): Collection
2023-04-25 00:28:44 +02:00
{
2024-09-22 01:41:56 +02:00
return static::collect(static::forSelect());
2023-04-25 00:28:44 +02:00
}
}