Commit Graph

216 Commits

Author SHA1 Message Date
Viktor Szépe
8d7c36918e
qa: remove useless PHP extensions cache 2022-07-10 19:20:27 +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
84ead04f84 misc: ignore .idea folder 2022-07-05 23:12:51 +02:00
Romain Canon
4d80ae337d doc: add google site verification meta tag 2022-07-05 23:11:16 +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
444df7090f doc: enable permalink anchor to titles 2022-06-28 16:29:14 +02:00
Romain Canon
ee53b8a5a3 doc: fix canonical path 2022-06-28 16:29:14 +02:00
Romain Canon
45f860041b release: version 0.11.0 2022-06-23 11:17:11 +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
bf2264b8e3 doc: improve documentation building process 2022-06-22 11:15:26 +02:00
dependabot[bot]
e6bf924bdf chore(deps): bump actions/cache from 3.0.2 to 3.0.4
Bumps [actions/cache](https://github.com/actions/cache) from 3.0.2 to 3.0.4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3.0.2...v3.0.4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-06-17 20:59:35 +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
982f596b8b doc: format badges in readme file 2022-06-12 17:59:12 +02:00
Romain Canon
8920725b93 doc: add Open Graph meta tags 2022-06-12 16:37:58 +02:00
Romain Canon
d9ac693827 doc: remove badges from documentation index 2022-06-11 12:48:35 +02:00
Romain Canon
36f44c37a3 doc: change some settings and adjust logos 2022-06-10 23:33:28 +02:00
Romain Canon
afda9480f4 doc: fix https links 2022-06-10 19:17:05 +02:00
Romain Canon
aa27ceeb4a release: version 0.10.0 2022-06-10 19:00:31 +02:00
Nathan Boiron
56ff6849bc
doc: introduce mkdocs as a static documentation generator 2022-06-10 17:32:07 +02:00
Philipp Scheit
eebc6511a9
doc: fix typo in code example 2022-06-08 10:37:44 +02:00
Romain Canon
741d54c32e doc: add support & thanks section 2022-06-07 15:26:18 +02:00
Romain Canon
7044801119 doc: remove duplicated section 2022-05-27 16:04:11 +02:00
Romain Canon
b794c692c4 qa: cache all QA tools results during GitHub workflow 2022-05-26 18:21:37 +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
Romain Canon
a097f60a48 release: version 0.9.0 2022-05-23 23:01:31 +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
Romain Canon
1b242d4ce7 doc: minor documentation formatting 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
Romain Canon
05cf4a4a4d feat: improve mapping error messages
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'}`.
2022-05-21 16:30:24 +02:00
Romain Canon
9642840f9a refactor: improve FakeObjectType constructors 2022-05-21 16:30:24 +02:00
Romain Canon
4ea3f39643 test: require YAML extension for test needing it 2022-05-21 16:30:24 +02:00
Romain Canon
48f936275e misc: introduce layer for object builder arguments 2022-05-21 16:30:24 +02:00
Romain Canon
11e12624aa misc!: revoke ObjectBuilder API access
Although it looked like a good idea in the first place, the current
feature of the library is probably powerful enough for most cases
without having to use a custom `ObjectBuilder`.

If for some reason keeping this interface open for custom
implementations, a revert could be considered.
2022-05-21 16:30:24 +02:00
Romain Canon
427a291341 test: add test for datetime with key but without format 2022-05-21 16:30:24 +02:00
Romain Canon
b75adb7c7c misc: change InvalidParameterIndex exception inheritance type 2022-05-21 16:30:24 +02:00
Romain Canon
a6c60eb60b release: version 0.8.0 2022-05-09 21:32:32 +02:00
afcedf9e56
feat: handle literal boolean true / false types
Allows the usage of boolean values, as follows:

```php
class Foo
{
    /** @var int|false */
    public readonly int|bool $value;
}
```
2022-05-09 21:14:46 +02:00
Romain Canon
790df8a3b8 feat: handle float value type
Allows the usage of float values, as follows:

```php
class Foo
{
    /** @var 404.42|1337.42 */
    public readonly float $value;
}
```
2022-05-09 19:17:22 +02:00
Romain Canon
6e6b9746da doc: add documentation for integer/string literal values 2022-05-09 19:17:22 +02:00
Romain Canon
9856c416ee test: add tests for negative integer value 2022-05-09 19:17:22 +02:00
Romain Canon
a60765ba80 test: use correct cache dir in integration tests 2022-05-09 19:17:22 +02:00