adrema/app/Group.php

74 lines
2.0 KiB
PHP
Raw Normal View History

2020-04-12 00:26:44 +02:00
<?php
namespace App;
2024-06-29 14:36:35 +02:00
use App\Fileshare\Data\FileshareResourceData;
2023-12-30 02:02:07 +01:00
use App\Group\Enums\Level;
2023-02-05 23:35:08 +01:00
use App\Nami\HasNamiField;
2024-09-22 17:32:29 +02:00
use Database\Factories\GroupFactory;
2021-06-13 11:27:22 +02:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2021-06-23 01:05:17 +02:00
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
2023-12-30 22:21:08 +01:00
use Illuminate\Database\Eloquent\Relations\HasMany;
2020-04-12 00:26:44 +02:00
class Group extends Model
{
2024-09-22 17:32:29 +02:00
/** @use HasFactory<GroupFactory> */
2021-06-13 11:27:22 +02:00
use HasFactory;
2023-02-05 23:35:08 +01:00
use HasNamiField;
2021-06-13 11:27:22 +02:00
2024-06-29 14:36:35 +02:00
public $fillable = ['nami_id', 'name', 'inner_name', 'level', 'parent_id', 'fileshare'];
2020-04-12 00:26:44 +02:00
public $timestamps = false;
2021-06-24 23:48:08 +02:00
2023-12-30 02:02:07 +01:00
public $casts = [
2024-06-29 14:36:35 +02:00
'level' => Level::class,
'fileshare' => FileshareResourceData::class,
2023-12-30 02:02:07 +01:00
];
2023-02-17 18:57:11 +01:00
/**
2024-09-22 17:32:29 +02:00
* @return BelongsTo<self, self>
2023-02-17 18:57:11 +01:00
*/
public function parent(): BelongsTo
{
2024-09-22 17:32:29 +02:00
return $this->belongsTo(self::class, 'parent_id');
}
2023-12-30 18:46:47 +01:00
2023-12-30 22:21:08 +01:00
/**
* @return HasMany<self>
*/
public function children(): HasMany
{
2024-09-22 17:32:29 +02:00
return $this->hasMany(self::class, 'parent_id');
2023-12-30 22:21:08 +01:00
}
2023-12-30 18:46:47 +01:00
public static function booted(): void
{
static::creating(function (self $group) {
if (!$group->getAttribute('inner_name') && $group->getAttribute('name')) {
$group->setAttribute('inner_name', $group->getAttribute('name'));
}
});
}
2023-12-31 14:29:50 +01:00
2023-12-31 21:02:40 +01:00
/**
* @return array<int, array{id: int, name: string}>
*/
2023-12-31 14:29:50 +01:00
public static function forSelect(?self $parent = null, string $prefix = ''): array
{
$result = self::where('parent_id', $parent ? $parent->id : null)->withCount('children')->get();
return $result
->reduce(
2024-02-08 23:09:51 +01:00
fn ($before, $group) => $before->concat([['id' => $group->id, 'name' => $prefix . ($group->display())]])
2023-12-31 14:29:50 +01:00
->concat($group->children_count > 0 ? self::forSelect($group, $prefix . '-- ') : []),
collect([])
)
->toArray();
}
2024-02-08 23:09:51 +01:00
public function display(): string
{
return $this->inner_name ?: $this->name;
}
2020-04-12 00:26:44 +02:00
}