DT.php 2.22 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
<?php

declare(strict_types=1);

namespace Kreait\Firebase\Util;

use DateTimeImmutable;
use DateTimeZone;
use Kreait\Firebase\Exception\InvalidArgumentException;
use Throwable;

/**
 * @internal
 */
class DT
{
    /**
     * @param mixed $value
     */
    public static function toUTCDateTimeImmutable($value): DateTimeImmutable
    {
        $tz = new DateTimeZone('UTC');
        $now = \time();

        if (
            ($value instanceof \DateTimeInterface)
            && $result = DateTimeImmutable::createFromFormat('U.u', $value->format('U.u'))
        ) {
            return $result->setTimezone($tz);
        }

        if ($value === null || $value === 0 || \is_bool($value)) {
            $value = '0';
        }

        if (\is_scalar($value) || (\is_object($value) && \method_exists($value, '__toString'))) {
            $value = (string) $value;
        } else {
            $type = \get_debug_type($value);

            throw new InvalidArgumentException("This {$type} cannot be parsed to a DateTime value");
        }

        if (\ctype_digit($value)) {
            // Seconds
            if (($value === '0' || \mb_strlen($value) === \mb_strlen((string) $now)) && ($result = DateTimeImmutable::createFromFormat('U', $value))) {
                return $result->setTimezone($tz);
            }

            // Milliseconds
            if (\mb_strlen($value) === \mb_strlen((string) ($now * 1000))) {
                $floatValue = (float) $value;
                $result = DateTimeImmutable::createFromFormat('U.u', \sprintf('%F', $floatValue / 1000));

                if ($result !== false) {
                    return $result->setTimezone($tz);
                }
            }
        }

        // microtime
        if (\preg_match('@(?P<msec>^0?\.\d+) (?P<sec>\d+)$@', $value, $matches)) {
            $value = (string) ((float) $matches['sec'] + (float) $matches['msec']);

            if ($result = DateTimeImmutable::createFromFormat('U.u', \sprintf('%F', $value))) {
                return $result->setTimezone($tz);
            }
        }

        try {
            return (new DateTimeImmutable($value))->setTimezone($tz);
        } catch (Throwable $e) {
            throw new InvalidArgumentException($e->getMessage());
        }
    }
}