跳至正文

处理日期

当映射器构建日期对象时,它必须知道支持哪种格式。默认情况下,任何有效的时间戳或 RFC 3339 格式的值都将被接受,带或不带微秒。

如果要支持其他格式,需要使用以下方法注册:

(new \CuyZ\Valinor\MapperBuilder())
    // Both `Cookie` and `ATOM` formats will be accepted
    ->supportDateFormats(DATE_COOKIE, DATE_ATOM)
    ->mapper()
    ->map(DateTimeInterface::class, 'Monday, 08-Nov-1971 13:37:42 UTC');

自定义日期类实现

默认情况下,该库会将DateTimeInterface映射到DateTimeImmutable实例。如果要支持其他实现,可以使用自定义构造函数。

以下是nesbot/carbon库的实现示例:

(new MapperBuilder())
    // When the mapper meets a `DateTimeInterface` it will convert it to Carbon
    ->infer(DateTimeInterface::class, fn () => \Carbon\Carbon::class)

    // We teach the mapper how to create a Carbon instance
    ->registerConstructor(function (string $time): \Carbon\Carbon {
        // Only `Cookie` format will be accepted
        return Carbon::createFromFormat(DATE_COOKIE, $time);
    })

    // Carbon uses its own exceptions, so we need to wrap it for the mapper
    ->filterExceptions(function (Throwable $exception) {
        if ($exception instanceof \Carbon\Exceptions\Exception) {
            return \CuyZ\Valinor\Mapper\Tree\Message\MessageBuilder::from($exception);
        }

        throw $exception;
    })

    ->mapper()
    ->map(DateTimeInterface::class, 'Monday, 08-Nov-1971 13:37:42 UTC');