This notation can be used when several cases in an enum share a common
prefix.
```php
enum SomeEnum: string
{
case FOO = 'foo';
case BAR = 'bar';
case BAZ = 'baz';
}
$mapper = (new MapperBuilder())->mapper();
$mapper->map('SomeEnum::BA*', 'foo'); // error
$mapper->map('SomeEnum::BA*', 'bar'); // ok
$mapper->map('SomeEnum::BA*', 'baz'); // ok
```
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();
```
A new constructor can be registered to declare which format(s) are
supported during the mapping of a date object. By default, any valid
timestamp or ATOM-formatted value will be accepted.
```php
(new \CuyZ\Valinor\MapperBuilder())
// Both COOKIE and ATOM formats will be accepted
->registerConstructor(
new \CuyZ\Valinor\Mapper\Object\DateTimeFormatConstructor(DATE_COOKIE, DATE_ATOM)
)
->mapper()
->map(DateTimeInterface::class, 'Monday, 08-Nov-1971 13:37:42 UTC');
```
The previously very opinionated behaviour has been removed, but can be
temporarily used to help with the migration.
```php
(new \CuyZ\Valinor\MapperBuilder())
->registerConstructor(
new \CuyZ\Valinor\Mapper\Object\BackwardCompatibilityDateTimeConstructor()
)
->mapper()
->map(DateTimeInterface::class, 'Monday, 08-Nov-1971 13:37:42 UTC');
```
In some situations the type handled by a constructor is only known at
runtime, in which case the constructor needs to know what class must be
used to instantiate the object.
For instance, an interface may declare a static constructor that is then
implemented by several child classes. One solution would be to register
the constructor for each child class, which leads to a lot of
boilerplate code and would require a new registration each time a new
child is created. Another way is to use the attribute
`\CuyZ\Valinor\Mapper\Object\DynamicConstructor`.
When a constructor uses this attribute, its first parameter must be a
string and will be filled with the name of the actual class that the
mapper needs to build when the constructor is called. Other arguments
may be added and will be mapped normally, depending on the source given
to the mapper.
```php
interface InterfaceWithStaticConstructor
{
public static function from(string $value): self;
}
final class ClassWithInheritedStaticConstructor implements InterfaceWithStaticConstructor
{
private function __construct(private SomeValueObject $value) {}
public static function from(string $value): self
{
return new self(new SomeValueObject($value));
}
}
(new \CuyZ\Valinor\MapperBuilder())
->registerConstructor(
#[\CuyZ\Valinor\Attribute\DynamicConstructor]
function (string $className, string $value): InterfaceWithStaticConstructor {
return $className::from($value);
}
)
->mapper()
->map(ClassWithInheritedStaticConstructor::class, 'foo');
```
It is now possible to register a static method constructor that can be
inherited by a child class. The constructor will then be used correctly
to map the child class.
```php
abstract class ClassWithStaticConstructor
{
public string $value;
final private function __construct(string $value)
{
$this->value = $value;
}
public static function from(string $value): static
{
return new static($value);
}
}
final class ChildClass extends ClassWithStaticConstructor {}
(new MapperBuilder())
// The constructor can be used for every child of the parent class
->registerConstructor(ClassWithStaticConstructor::from(...))
->mapper()
->map(ChildClass::class, 'foo');
```
Using two instances of the same class implementing the `__invoke()`
method in one of the mapper builder methods will now be properly handled
by the library
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 mapper is now more type-sensitive and will fail in the following
situations:
- When a value does not match exactly the awaited scalar type, for
instance a string `"42"` given to a node that awaits an integer.
- When unnecessary array keys are present, for instance mapping an array
`['foo' => …, 'bar' => …, 'baz' => …]` to an object that needs only
`foo` and `bar`.
- When permissive types like `mixed` or `object` are encountered.
These limitations can be bypassed by enabling the flexible mode:
```php
(new \CuyZ\Valinor\MapperBuilder())
->flexible()
->mapper();
->map('array{foo: int, bar: bool}', [
'foo' => '42', // Will be cast from `string` to `int`
'bar' => 'true', // Will be cast from `string` to `bool`
'baz' => '…', // Will be ignored
]);
```
When using this library for a provider application — for instance an API
endpoint that can be called with a JSON payload — it is recommended to
use the strict mode. This ensures that the consumers of the API provide
the exact awaited data structure, and prevents unknown values to be
passed.
When using this library as a consumer of an external source, it can make
sense to enable the flexible mode. This allows for instance to convert
string numeric values to integers or to ignore data that is present in
the source but not needed in the application.
---
All these changes led to a new check that runs on all registered object
constructors. If a collision is found between several constructors that
have the same signature (the same parameter names), an exception will be
thrown.
```php
final class SomeClass
{
public static function constructorA(string $foo, string $bar): self
{
// …
}
public static function constructorB(string $foo, string $bar): self
{
// …
}
}
(new \CuyZ\Valinor\MapperBuilder())
->registerConstructor(
SomeClass::constructorA(...),
SomeClass::constructorB(...),
)
->mapper();
->map(SomeClass::class, [
'foo' => 'foo',
'bar' => 'bar',
]);
// Exception: A collision was detected […]
```
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.
Enhances most of the messages for the end users.
Two major changes can be noticed:
1. In most cases no class name will be written in the message; it
prevents users that potentially have no access to the codebase to
get a useless/unclear information.
2. The input values are now properly formatted; for instance a string
value will now be written directly instead of the type `string`;
arrays are also handled with the array shape format, for instance:
`array{foo: 'some string'}`.
It is now mandatory to explicitly register custom constructors —
including named constructors — that can be used by the mapper. The
former automatic registration of named constructor feature doesn't
work anymore.
BREAKING CHANGE: existing code must list all named constructors that
were previously automatically used by the mapper, and registerer them
using the method `MapperBuilder::registerConstructor()`.
The method `MapperBuilder::bind()` has been deprecated, the method above
should be used instead.
```php
final class SomeClass
{
public static function namedConstructor(string $foo): self
{
// …
}
}
(new \CuyZ\Valinor\MapperBuilder())
->registerConstructor(
SomeClass::namedConstructor(...),
// …or for PHP < 8.1:
[SomeClass::class, 'namedConstructor'],
)
->mapper()
->map(SomeClass::class, [
// …
]);
```
This modifier can be used to change paths in the source data using a dot
notation.
The mapping is done using an associative array of path mappings. This
array must have the source path as key and the target path as value.
The source path uses the dot notation (eg `A.B.C`) and can contain one
`*` for array paths (eg `A.B.*.C`).
```php
final class Country
{
/** @var City[] */
public readonly array $cities;
}
final class City
{
public readonly string $name;
}
$source = new \CuyZ\Valinor\Mapper\Source\Modifier\PathMapping([
'towns' => [
['label' => 'Ankh Morpork'],
['label' => 'Minas Tirith'],
],
], [
'towns' => 'cities',
'towns.*.label' => 'name',
]);
// After modification this is what the source will look like:
[
'cities' => [
['name' => 'Ankh Morpork'],
['name' => 'Minas Tirith'],
],
];
(new \CuyZ\Valinor\MapperBuilder())
->mapper()
->map(Country::class, $source);
```
The method `MapperBuilder::infer()` can be used to infer an
implementation for a given interface.
The callback given to this method must return the name of a class that
implements the interface. Any arguments can be required by the callback;
they will be mapped properly using the given source.
```php
$mapper = (new \CuyZ\Valinor\MapperBuilder())
->infer(UuidInterface::class, fn () => MyUuid::class)
->infer(SomeInterface::class, fn (string $type) => match($type) {
'first' => FirstImplementation::class,
'second' => SecondImplementation::class,
default => throw new DomainException("Unhandled type `$type`.")
})->mapper();
// Will return an instance of `FirstImplementation`
$mapper->map(SomeInterface::class, [
'type' => 'first',
'uuid' => 'a6868d61-acba-406d-bcff-30ecd8c0ceb6',
'someString' => 'foo',
]);
// Will return an instance of `SecondImplementation`
$mapper->map(SomeInterface::class, [
'type' => 'second',
'uuid' => 'a6868d61-acba-406d-bcff-30ecd8c0ceb6',
'someInt' => 42,
]);
interface SomeInterface {}
final class FirstImplementation implements SomeInterface
{
public readonly UuidInterface $uuid;
public readonly string $someString;
}
final class SecondImplementation implements SomeInterface
{
public readonly UuidInterface $uuid;
public readonly int $someInt;
}
```
Inferring object unions and named constructor are now done using the
same algorithm — in class `ObjectBuilderFilterer` — which is called from
a unique entry point in `ClassNodeBuilder`.
An object may have several ways of being created — in such cases it is
common to use so-called named constructors, also known as static factory
methods. If one or more are found, they can be called during the mapping
to create an instance of the object.
What defines a named constructor is a method that:
1. is public
2. is static
3. returns an instance of the object
4. has one or more arguments
```php
final class Color
{
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
private function __construct(
public readonly int $red,
public readonly int $green,
public readonly int $blue
) {}
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
public static function fromRgb(
int $red,
int $green,
int $blue,
): self {
return new self($red, $green, $blue);
}
/**
* @param non-empty-string $hex
*/
public static function fromHex(string $hex): self
{
if (strlen($hex) !== 6) {
throw new DomainException('Must be 6 characters long');
}
/** @var int<0, 255> $red */
$red = hexdec(substr($hex, 0, 2));
/** @var int<0, 255> $green */
$green = hexdec(substr($hex, 2, 2));
/** @var int<0, 255> $blue */
$blue = hexdec(substr($hex, 4, 2));
return new self($red, $green, $blue);
}
}
```
Will recursively flatten messages of a node and all its children.
This helper can for instance be used when errors occurred during a
mapping to flatten all caught errors into a basic array of string that
can then easily be used to inform the user of what is wrong.
```
try {
// …
} catch(MappingError $error) {
$messages = (new MessagesFlattener($error->node()))->errors();
foreach ($messages as $message) {
echo $message;
}
}
```
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);
```
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.
Previously, the method `TreeMapper::map` would allow mapping only to an
object. It is now possible to map to any type handled by the library.
It is for instance possible to map to an array of objects:
```php
$objects = (new \CuyZ\Valinor\MapperBuilder())->mapper()->map(
'array<' . SomeClass::class . '>',
[/* … */]
);
```
For simple use-cases, an array shape can be used:
```php
$array = (new \CuyZ\Valinor\MapperBuilder())->mapper()->map(
'array{foo: string, bar: int}',
[/* … */]
);
echo strtolower($array['foo']);
echo $array['bar'] * 2;
```
This new feature changes the possible behaviour of the mapper, meaning
static analysis tools need help to understand the types correctly. An
extension for PHPStan and a plugin for Psalm are now provided and can be
included in a project to automatically increase the type coverage.
When an error occurs during mapping, the root instance of `Node` can now
be accessed from the exception. This recursive object allows retrieving
all needed information through the whole mapping tree: path, values,
types and messages, including the issues that caused the exception.
It can be used like the following:
```php
try {
(new \CuyZ\Valinor\MapperBuilder())
->mapper()
->map(SomeClass::class, [/* ... */]);
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
// Do something with `$error->node()`
// See README for more information
}
```
This change removes the method `MappingError::describe()` which provided
a flattened view of messages of all the errors that were encountered
during the mapping. The same behaviour can still be retrieved, see the
example below:
```php
use CuyZ\Valinor\Mapper\Tree\Message\Message;
use CuyZ\Valinor\Mapper\Tree\Node;
/**
* @implements \IteratorAggregate<string, array<\Throwable&Message>>
*/
final class MappingErrorList implements \IteratorAggregate
{
private Node $node;
public function __construct(Node $node)
{
$this->node = $node;
}
/**
* @return \Traversable<string, array<\Throwable&Message>>
*/
public function getIterator(): \Traversable
{
yield from $this->errors($this->node);
}
/**
* @return \Traversable<string, array<\Throwable&Message>>
*/
private function errors(Node $node): \Traversable
{
$errors = array_filter(
$node->messages(),
static fn (Message $m) => $m instanceof \Throwable
);
if (! empty($errors)) {
yield $node->path() => array_values($errors);
}
foreach ($node->children() as $child) {
yield from $this->errors($child);
}
}
}
try {
(new \CuyZ\Valinor\MapperBuilder())
->mapper()
->map(SomeClass::class, [/* ... */]);
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
$errors = iterator_to_array(new MappingErrorList($error->node()));
}
```
The class `CannotMapObject` is deleted, as it does not provide any
value; this means that `MappingError` which was previously an interface
becomes a class.