<?php

namespace App\Trait;

use Illuminate\Database\Eloquent\Casts\Attribute;

trait HasName {
    protected function fullName(): Attribute {
        return Attribute::make(
            get: fn(mixed $value, array $attributes) => implode(' ', array_filter([
                $attributes['title'] ?? null,
                $attributes['name_first'] ?? null,
                $attributes['name_middle'] ?? null,
                $attributes['name_last'] ?? null,
            ])),
            set: fn(string $value) => [
                'name_first' => explode(' ', $value, 2)[0] ?? '',
                'name_last' => explode(' ', $value, 2)[1] ?? '',
            ]
        )->shouldCache();
    }
}
