<?php

namespace App\Casts;

use App\ValueObjects\Email;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class EmailAddress implements CastsAttributes {
    /**
     * Cast the stored value from the database to an Email object.
     */
    public function get($model, string $key, $value, array $attributes): ?Email {
        return Email::tryFrom($value);
    }

    public function set($model, string $key, $value, array $attributes): ?string {
        if ($value instanceof Email) {
            return (string)$value;
        }

        return Email::tryFrom($value)?->__toString();
    }
}