mirror of
https://github.com/danog/Valinor.git
synced 2024-12-04 02:27:54 +01:00
cb87925aac
The new class `\CuyZ\Valinor\Mapper\Tree\Message\MessageBuilder` can be used to easily create an instance of (error) message. This new straightforward way of creating messages leads to the depreciation of `\CuyZ\Valinor\Mapper\Tree\Message\ThrowableMessage`. ```php $message = MessageBuilder::newError('Some message / {some_parameter}.') ->withCode('some_code') ->withParameter('some_parameter', 'some_value') ->build(); ```
1.7 KiB
1.7 KiB
Dealing with dates
When the mapper builds a date object, it has to know which format(s) are supported. By default, any valid timestamp or ATOM-formatted value will be accepted.
If other formats are to be supported, they need to be registered using the following method:
(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');
Custom date class implementation
By default, the library will map a DateTimeInterface
to a DateTimeImmutable
instance. If other implementations are to be supported, custom constructors can
be used.
Here is an implementation example for the nesbot/carbon library:
(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');