Handles race condition when the attribute is affected to a property or
parameter that was promoted, in this case the attribute will be applied
to both `ParameterReflection` and `PropertyReflection`, but the target
argument inside the attribute class is configured to support only one of
them (parameter or property).
More details: https://wiki.php.net/rfc/constructor_promotion#attributes
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}`.
The access to class/function definition, types and exceptions did not
add value to the actual goal of the library. Keeping these features
under the public API flag causes more maintenance burden whereas
revoking their access allows more flexibility with the overall
development of the library.
This feature was a relic of the first release of the library. It had
strong design issues and was going to become a huge blocker for upcoming
features.
Although it was never documented, it may have been used in applications;
there will be no replacement for this feature. If this becomes an issue
for existing applications, an issue can be created in the repository to
discuss other possible solutions.
/!\ 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 Warmup will now recursively handle interface and their class
implementations. It is also done in a more clever way: instead of
warming up all properties and constructors, it takes only what is
needed.
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 […]
```
It is now mandatory to list all possible class-types that can be
inferred by the mapper. This change is a step towards the library being
able to deliver powerful new features such as compiling a mapper for
better performance.
BREAKING CHANGE: the existing calls to `MapperBuilder::infer` that could
return several class-names must now add a signature to the callback. The
callbacks that require no parameter and always return the same
class-name can remain unchanged.
For instance:
```php
$builder = (new \CuyZ\Valinor\MapperBuilder())
// Can remain unchanged
->infer(SomeInterface::class, fn () => SomeImplementation::class);
```
```php
$builder = (new \CuyZ\Valinor\MapperBuilder())
->infer(
SomeInterface::class,
fn (string $type) => match($type) {
'first' => ImplementationA::class,
'second' => ImplementationB::class,
default => throw new DomainException("Unhandled `$type`.")
}
)
// …should be modified with:
->infer(
SomeInterface::class,
/** @return class-string<ImplementationA|ImplementationB> */
fn (string $type) => match($type) {
'first' => ImplementationA::class,
'second' => ImplementationB::class,
default => throw new DomainException("Unhandled `$type`.")
}
);
```
This new method can be used for instance in a pipeline during the build
and deployment of the application.
The cache has to be registered first, otherwise the warmup will end up
being useless.
```php
$cache = new \CuyZ\Valinor\Cache\FileSystemCache('path/to/cache-dir');
$mapperBuilder = (new \CuyZ\Valinor\MapperBuilder())->withCache($cache);
// During the build:
$mapperBuilder->warmup(SomeClass::class, SomeOtherClass::class);
// In the application:
$mapper->mapper()->map(SomeClass::class, [/* … */]);
```
Co-authored-by: Romain Canon <romain.hydrocanon@gmail.com>
When the application runs in a development environment, the cache
implementation should be decorated with `FileWatchingCache` to prevent
invalid cache entries states, which can result in the library not
behaving as expected (missing property value, callable with outdated
signature, …).
```php
$cache = new \CuyZ\Valinor\Cache\FileSystemCache('path/to/cache-dir');
if ($isApplicationInDevelopmentEnvironment) {
$cache = new \CuyZ\Valinor\Cache\FileWatchingCache($cache);
}
(new \CuyZ\Valinor\MapperBuilder())
->withCache($cache)
->mapper()
->map(SomeClass::class, [/* … */]);
```
This behavior now forces to explicitly inject `FileWatchingCache`, when
it was done automatically before; but because it shouldn't be used in
a production environment, it will increase overall performance.
The cache implementation that was previously injected in the mapper
builder must now be manually injected. This gives better control on when
the cache should be enabled, especially depending on which environment
the application is running.
The library provides a cache implementation out of the box, which saves
cache entries into the file system.
It is also possible to use any PSR-16 compliant implementation, as long
as it is capable of caching the entries handled by the library.
```php
$cache = new \CuyZ\Valinor\Cache\FileSystemCache('path/to/cache-dir');
(new \CuyZ\Valinor\MapperBuilder())
->withCache($cache)
->mapper()
->map(SomeClass::class, [/* … */]);
```