mirror of
https://github.com/danog/Valinor.git
synced 2024-12-14 18:16:19 +01:00
bf2264b8e3
2 Commits
Author | SHA1 | Message | Date | |
---|---|---|---|---|
Romain Canon
|
60a6656141 |
feat!: improve message customization with formatters
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. |
||
Romain Canon
|
ddf69efaaa |
feat: introduce helper class MessageMapFormatter
Can be used to customize the content of messages added during a mapping. An implementation is provided by the library — `MessageMapFormatter`: The constructor parameter is an array where each key represents either: - The code of the message to be replaced - The content of the message to be replaced - The class name of the message to be replaced If none of those is found, the content of the message will stay unchanged unless a default one is given to this class. If one of these keys is found, the array entry will be used to replace the content of the message. This entry can be either a plain text or a callable that takes the message as a parameter and returns a string; it is for instance advised to use a callable in cases where a translation service is used — to avoid useless greedy operations. In any case, the content can contain placeholders that can be used the same way as `\CuyZ\Valinor\Mapper\Tree\Message\NodeMessage::format()`. See usage examples below: ``` $formatter = (new MessageMapFormatter([ // Will match if the given message has this exact code 'some_code' => 'new content / previous code was: %1$s', // Will match if the given message has this exact content 'Some message content' => 'new content / previous message: %2$s', // Will match if the given message is an instance of this class SomeError::class => ' - Original code of the message: %1$s - Original content of the message: %2$s - Node type: %3$s - Node name: %4$s - Node path: %5$s ', // A callback can be used to get access to the message instance OtherError::class => function (NodeMessage $message): string { if ((string)$message->type() === 'string|int') { // … } return 'Some message content'; }, // For greedy operation, it is advised to use a lazy-callback 'bar' => fn () => $this->translator->translate('foo.bar'), ])) ->defaultsTo('some default message') // …or… ->defaultsTo(fn () => $this->translator->translate('default')); $content = $formatter->format($message); ``` |