Files
mytodos/app/Models/Folder.php
T
ecdown 999d5ad28d
tests / ci (push) Canceled after 0s
folders are now alphabetical
2026-09-24 22:57:57 -07:00

118 lines
3.2 KiB
PHP

<?php
namespace App\Models;
use Database\Factories\FolderFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
/**
* @property int $id
* @property int $user_id
* @property string $name
* @property string|null $color
* @property int|null $parent_id
* @property Folder|null $parent
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['user_id', 'name', 'parent_id', 'color'])]
class Folder extends Model
{
/** @use HasFactory<FolderFactory> */
use HasFactory;
public const COLORS = [
'zinc', 'red', 'orange', 'amber', 'green', 'emerald',
'sky', 'blue', 'indigo', 'violet', 'fuchsia', 'pink',
];
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/** @return BelongsTo<Folder, $this> */
public function parent(): BelongsTo
{
return $this->belongsTo(Folder::class, 'parent_id');
}
/** @return HasMany<Folder, $this> */
public function children(): HasMany
{
return $this->hasMany(Folder::class, 'parent_id');
}
/** @return HasMany<Todo, $this> */
public function todos(): HasMany
{
return $this->hasMany(Todo::class);
}
/**
* Scope the query to folders owned by the given user.
*
* @param Builder<Folder> $query
* @return Builder<Folder>
*/
public function scopeForUser(Builder $query, User|int $user): Builder
{
return $query->where('user_id', $user instanceof User ? $user->id : $user);
}
/**
* Scope the query to top-level folders (no parent).
*
* @param Builder<Folder> $query
* @return Builder<Folder>
*/
public function scopeToplevel(Builder $query): Builder
{
return $query->whereNull('parent_id');
}
/**
* Build a flattened, depth-aware tree of the user's folders
* ordered top-down, with the full path (e.g. "Work / Acme Corp").
*
* @return Collection<int, array{folder: Folder, depth: int, path: string}>
*/
public static function treeForUser(User|int $user): Collection
{
$folders = Folder::query()
->forUser($user)
->orderBy('name')
->get()
->keyBy('id');
$tree = collect();
$visit = function (Folder $folder, int $depth, string $prefix) use (&$visit, &$tree, $folders): void {
$path = $prefix === '' ? $folder->name : $prefix.' / '.$folder->name;
$tree->push([
'folder' => $folder,
'depth' => $depth,
'path' => $path,
]);
foreach ($folders->where('parent_id', $folder->id)->values() as $child) {
$visit($child, $depth + 1, $path);
}
};
foreach ($folders->whereNull('parent_id')->values() as $topLevel) {
$visit($topLevel, 0, '');
}
return $tree;
}
}