Commit Graph

129 Commits

Author SHA1 Message Date
Romain Canon
3ee526cb27 fix: fetch correct node value for children 2022-09-26 20:03:47 +02:00
Eduardo Dobay
c009ab98cc
fix: properly handle static anonymous functions
The `MethodObjectBuilder` was incorrectly used when a registered
constructor is a static anonymous functions — it was handled like a
static method closure `Class::method(...)` and would yield errors like
this:

```
Error: Call to undefined method 
stdClass::CuyZ\Valinor\Tests\Integration\Mapping\{closure}()
```

PHP Reflection does not provide any way of telling static functions and
closures of static methods apart, other than checking for the name
`{closure}`. We check that `{closure}` is actually the last part of the
fully-qualified name, instead of just checking that the string ends with
`{closure}`.
2022-09-24 20:01:53 +02:00
Lukáš Unger
0e8f12e5f7
fix: add return types for cache implementations
Fixes the following message reported by `symfony/error-handler`:

`User Deprecated: Method "Psr\SimpleCache\CacheInterface::get()" might
add "mixed" as a native return type declaration in the future. Do the
same in implementation "CuyZ\Valinor\Cache\..." now to avoid errors or
add an explicit @return annotation to suppress this message.`
2022-09-24 19:29:02 +02:00
Romain Canon
48208c1ed1 fix: correctly fetch file system cache entries
Method `\CuyZ\Valinor\Cache\FileSystemCache::get()` was not properly
looping on all delegates, leading to the values not being fetched from
the cache files and resulting in `null` (the default value) being
returned in some cases. Because of the following algorithm, the cache
entry was populated again, so the cache was not really working here.

```php
if ($this->cache->has($key)) {
    $entry = $this->cache->get($key);

    if ($entry) {
        return $entry;
    }
}

$class = $this->delegate->for($type);

$this->cache->set($key, $class);

return $class;
```
2022-09-01 12:26:32 +02:00
Romain Canon
11a7ea7252 feat: introduce helper method to describe supported date formats
```php
(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');
```
2022-09-01 12:24:24 +02:00
Romain Canon
f232cc0636 feat!: introduce constructor for custom date formats
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');
```
2022-09-01 12:24:24 +02:00
Romain Canon
3c4d29901a fix: prevent illegal characters in PSR-16 cache keys
@see https://www.php-fig.org/psr/psr-16/#12-definitions
2022-08-31 01:01:16 +02:00
Romain Canon
546fa5c6cf test: add missing test assertion 2022-08-31 01:01:16 +02:00
mtouellette
fd39aea2a7
fix: handle concurrent cache file creation 2022-08-30 22:06:53 +02:00
Romain Canon
bf445b5364 fix: allow trailing comma in shaped array
Allows the following syntax:

```php
/**
 * @var array{
 * 	   foo: string,
 *     bar: int,
 * }
 */
 ```
2022-08-30 21:20:28 +02:00
Romain Canon
e437d9405c feat: introduce attribute DynamicConstructor
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');
```
2022-08-30 15:15:41 +02:00
Romain Canon
4bc50e3e42 misc: add singleton usage of ClassStringType 2022-08-29 23:09:15 +02:00
Romain Canon
ec494cec48 misc: fetch attributes for function definition 2022-08-29 23:09:15 +02:00
Romain Canon
c37ac1e259 feat: handle abstract constructor registration
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');
```
2022-08-29 23:09:15 +02:00
Romain Canon
73b62241b6 fix: handle inherited private constructor in class definition 2022-08-29 23:09:15 +02:00
Romain Canon
2b46a60f37 misc: extract native constructor object builder 2022-08-29 23:09:15 +02:00
Romain Canon
57849c92e7 misc: change ObjectBuilderFactory::for return signature 2022-08-29 23:09:15 +02:00
Romain Canon
a401c2a2d6 fix: handle invalid nodes recursively 2022-08-29 23:09:15 +02:00
Romain Canon
2540741171 fix: handle classes in a case-sensitive way in type parser 2022-08-29 23:09:15 +02:00
Romain Canon
6414e9cf14 misc: refactor arguments instantiation 2022-08-29 23:09:15 +02:00
Romain Canon
b3cb5927e9 fix: detect invalid constructor handle type
An exception will now be thrown when a constructor is registered for
an invalid type: something other than a class.
2022-08-29 23:09:15 +02:00
Romain Canon
ae7ddcf3ca fix: properly handle callable objects of the same class
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
2022-08-29 23:09:15 +02:00
Radhi Guennichi
897ca9b65e
fix: handle native attribute on promoted parameter
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
2022-07-31 15:42:58 +02:00
Romain Canon
17328d86db test: use exception expectation API for mapping error test 2022-07-27 08:18:41 +02:00
Filippo Tessarotto
9c1e7c928b
feat: display more information in mapping error message
The message will now display the source and the number of errors, and
even the original error message if only one error was encountered.
2022-07-26 22:55:32 +02:00
Romain Canon
2c1c7cf38a feat: make MessagesFlattener countable 2022-07-26 19:39:14 +02:00
Romain Canon
0b37b48c60 misc: add fixed value for root node path
The path is no longer an empty string, the string `*root*` is now
returned.
2022-07-26 19:28:46 +02:00
Romain Canon
f61eb553fa feat: allow to declare parameter for message
The parameter can then be used with a placeholder inside the body of the
message.
2022-07-26 19:23:44 +02:00
sergkash7
96a493469c
feat: handle numeric string type
The new `numeric-string` type can be used in docblocks.

It will accept any string value that is also numeric.
2022-07-25 22:34:05 +02:00
Romain Canon
ad1207153e feat!: rework messages body and parameters features
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';
    }
}
```
2022-07-25 22:05:31 +02:00
Romain Canon
703ba55ada test: use FakeReflector instead of anonymous class 2022-07-25 22:05:31 +02:00
Romain Canon
b47a1bbb5d misc: remove types stringable behavior 2022-07-13 21:44:07 +02:00
Romain Canon
d3b1dcb64e feat!: refactor tree node API
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}`.
2022-07-10 19:28:36 +02:00
Romain Canon
63c87a2cc4 misc!: remove node visitor feature
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.
2022-07-10 19:28:36 +02:00
Romain Canon
6ce1a439ad feat!: filter userland exceptions to hide potential sensible data
/!\ 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];
}
```
2022-07-08 13:58:48 +02:00
Romain Canon
7c9ac1dd6d fix: process invalid type default value as unresolvable type 2022-07-06 18:04:41 +02:00
Romain Canon
dc45dd8ac5 fix: handle inferring methods with same names properly 2022-07-04 19:02:33 +02:00
Romain Canon
3020db20bf fix: properly display unresolvable type 2022-07-04 19:02:33 +02:00
Romain Canon
44c5f13b70 feat: improve cache warmup
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.
2022-06-23 11:00:38 +02:00
Romain Canon
90dc586018
feat!: make mapper more strict and allow flexible mode
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 […]
```
2022-06-23 10:30:36 +02:00
Romain Canon
1b0ff39af6 feat!: handle exhaustive list of interface inferring
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`.")
        }
    );
```
2022-06-17 18:03:27 +02:00
Romain Canon
628baf1294 fix: allow mapping iterable to shaped array 2022-05-26 17:56:14 +02:00
David Badura
d8eb4d830b
fix: allow declaring promoted parameter type with @var annotation 2022-05-26 17:35:33 +02:00
Filippo Tessarotto
e0a529a7e5
feat: support mapping to dates with no time 2022-05-25 18:47:24 +02:00
Maximilian Bösing
ccf09fd334
feat: introduce method to warm the cache up
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>
2022-05-23 22:01:40 +02:00
Romain Canon
105eef4738 fix: make interface type match undefined object type 2022-05-23 20:34:14 +02:00
Romain Canon
2d70efbfbb feat: extract file watching feature in own cache implementation
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.
2022-05-23 20:28:02 +02:00
Romain Canon
69ad3f4777 feat: allow injecting a cache implementation that is used by the mapper
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, [/* … */]);
```
2022-05-23 20:28:02 +02:00
Abdul Malik Ikhsan
5a50baed86
qa: include and use Rector 2022-05-21 16:37:16 +02:00
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.
2022-05-21 16:30:24 +02:00