The `\CuyZ\Valinor\Mapper\Tree\Message\Message` interface is no longer
a `Stringable`, however it defines a new method `body` that must return
the body of the message, which can contain placeholders that will be
replaced by parameters.
These parameters can now be defined by implementing the interface
`\CuyZ\Valinor\Mapper\Tree\Message\HasParameters`.
This leads to the deprecation of the no longer needed interface
`\CuyZ\Valinor\Mapper\Tree\Message\TranslatableMessage` which had a
confusing name.
```php
final class SomeException
extends DomainException
implements ErrorMessage, HasParameters, HasCode
{
private string $someParameter;
public function __construct(string $someParameter)
{
parent::__construct();
$this->someParameter = $someParameter;
}
public function body() : string
{
return 'Some message / {some_parameter} / {source_value}';
}
public function parameters(): array
{
return [
'some_parameter' => $this->someParameter,
];
}
public function code() : string
{
// A unique code that can help to identify the error
return 'some_unique_code';
}
}
```
The class `\CuyZ\Valinor\Mapper\Tree\Node` has been refactored to remove
access to unwanted methods that were not supposed to be part of the
public API. Below are a list of all changes:
- New methods `$node->sourceFilled()` and `$node->sourceValue()` allow
accessing the source value.
- The method `$node->value()` has been renamed to `$node->mappedValue()`
and will throw an exception if the node is not value.
- The method `$node->type()` now returns a string.
- The methods `$message->name()`, `$message->path()`, `$message->type()`
and `$message->value()` have been deprecated in favor of the new
method `$message->node()`.
- The message parameter `{original_value}` has been deprecated in favor
of `{source_value}`.
/!\ This change fixes a security issue.
Userland exception thrown in a constructor will not be automatically
caught by the mapper anymore. This prevents messages with sensible
information from reaching the final user — for instance an SQL exception
showing a part of a query.
To allow exceptions to be considered as safe, the new method
`MapperBuilder::filterExceptions()` must be used, with caution.
```php
final class SomeClass
{
public function __construct(private string $value)
{
\Webmozart\Assert\Assert::startsWith($value, 'foo_');
}
}
try {
(new \CuyZ\Valinor\MapperBuilder())
->filterExceptions(function (Throwable $exception) {
if ($exception instanceof \Webmozart\Assert\InvalidArgumentException) {
return \CuyZ\Valinor\Mapper\Tree\Message\ThrowableMessage::from($exception);
}
// If the exception should not be caught by this library, it
// must be thrown again.
throw $exception;
})
->mapper()
->map(SomeClass::class, 'bar_baz');
} catch (\CuyZ\Valinor\Mapper\MappingError $exception) {
// Should print something similar to:
// > Expected a value to start with "foo_". Got: "bar_baz"
echo $exception->node()->messages()[0];
}
```
The way messages can be customized has been totally revisited, requiring
several breaking changes. All existing error messages have been
rewritten to better fit the actual meaning of the error.
The content of a message can be changed to fit custom use cases; it can
contain placeholders that will be replaced with useful information.
The placeholders below are always available; even more may be used
depending on the original message.
- `{message_code}` — the code of the message
- `{node_name}` — name of the node to which the message is bound
- `{node_path}` — path of the node to which the message is bound
- `{node_type}` — type of the node to which the message is bound
- `{original_value}` — the source value that was given to the node
- `{original_message}` — the original message before being customized
```php
try {
(new \CuyZ\Valinor\MapperBuilder())
->mapper()
->map(SomeClass::class, [/* … */]);
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
$messages = new MessagesFlattener($error->node());
foreach ($messages as $message) {
if ($message->code() === 'some_code') {
$message = $message->withBody('new / {original_message}');
}
echo $message;
}
}
```
The messages are formatted using the ICU library, enabling the
placeholders to use advanced syntax to perform proper translations, for
instance currency support.
```php
try {
(new MapperBuilder())->mapper()->map('int<0, 100>', 1337);
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
$message = $error->node()->messages()[0];
if (is_numeric($message->value())) {
$message = $message->withBody(
'Invalid amount {original_value, number, currency}'
);
}
// Invalid amount: $1,337.00
echo $message->withLocale('en_US');
// Invalid amount: £1,337.00
echo $message->withLocale('en_GB');
// Invalid amount: 1 337,00 €
echo $message->withLocale('fr_FR');
}
```
If the `intl` extension is not installed, a shim will be available to
replace the placeholders, but it won't handle advanced syntax as
described above.
---
The new formatter `TranslationMessageFormatter` can be used to translate
the content of messages.
The library provides a list of all messages that can be returned; this
list can be filled or modified with custom translations.
```php
TranslationMessageFormatter::default()
// Create/override a single entry…
->withTranslation(
'fr',
'some custom message',
'un message personnalisé'
)
// …or several entries.
->withTranslations([
'some custom message' => [
'en' => 'Some custom message',
'fr' => 'Un message personnalisé',
'es' => 'Un mensaje personalizado',
],
'some other message' => [
// …
],
])
->format($message);
```
It is possible to join several formatters into one formatter by using
the `AggregateMessageFormatter`. This instance can then easily be
injected in a service that will handle messages.
The formatters will be called in the same order they are given to the
aggregate.
```php
(new AggregateMessageFormatter(
new LocaleMessageFormatter('fr'),
new MessageMapFormatter([
// …
],
TranslationMessageFormatter::default(),
))->format($message)
```
BREAKING CHANGE: The method `NodeMessage::format` has been removed,
message formatters should be used instead. If needed, the old behaviour
can be retrieved with the formatter `PlaceHolderMessageFormatter`,
although it is strongly advised to use the new placeholders feature.
BREAKING CHANGE: The signature of the method `MessageFormatter::format`
has changed.
A new class `NodeMessage` is used to wrap messages added to a node
during the mapping. This class will allow further features by giving
access to useful data related to the bound node.
BREAKING CHANGE: as of now every message is wrapped into a `NodeMessage`
it is therefore not possible to check whether the message is an instance
of `Throwable` — a new method `$message->isError()` is now to be used
for such cases.