<?php

namespace Mnv\Core\Validations;

use InvalidArgumentException;
use Mnv\Core\Validations\Exceptions\InvalidEmailException;

/**
 * Class ValidateEmail
 * @package Mnv\Core\Validations
 */
final class ValidateEmail
{
    private string $email;

    /**
     * @throws InvalidEmailException
     * @throws InvalidArgumentException
     */
    private function __construct(string $email)
    {
        $this->ensureIsValidEmail($email);

        $this->email = $email;
    }


    /**
     * @throws InvalidEmailException
     * @throws InvalidArgumentException
     */
    public static function fromString(string $email): self
    {
        return new self($email);
    }

    public function __toString(): string
    {
        return $this->email;
    }

    /**
     * @throws InvalidEmailException
     * @throws InvalidArgumentException
     */
    private function ensureIsValidEmail(string $email): void
    {
        if (empty($email)) {
            throw new InvalidEmailException('empty email address');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException(sprintf('"%s" is not a valid email address', $email));
        }
    }
}