<?php

namespace Mailbox\Infrastructure\Repositories\Helpers;

use DateTime;
use DateTimeInterface;

trait DateHelperTrait
{
    /**
     * фабричный метод
     * @param string|null $datetime
     * @return DateTime
     * @throws \Exception
     */
    private static function toDatetime(?string $datetime = null): DateTime
    {
        if (empty($datetime)) {
            return DateTime::createFromFormat('U', 0);
        }

        if (preg_match('~([a-z0-9,:+\- ]+)~iu', $datetime, $matches)) {
            $dateTimeFormatting = DateTime::createFromFormat(DateTimeInterface::RFC2822, trim($matches[1]));

            if ($dateTimeFormatting !== false) {
                return $dateTimeFormatting;
            }
        }

        try {
            return new DateTime($datetime);
        } catch (\Exception $e) {
            return DateTime::createFromFormat('U', 0);
        }
    }
}
