Commit Graph

31 Commits

Author SHA1 Message Date
Romain Canon
027d2a43da release: version 0.16.0 2022-10-19 13:46:57 +02:00
Romain Canon
0d2205edd3 release: version 0.15.0 2022-10-06 13:49:08 +02:00
Romain Canon
1244c2d68f feat: add support for class constant type
This notation is mainly useful when several cases in constants of a
class share a common prefix.

```php
final class SomeClassWithConstants
{
    public const FOO = 1337;

    public const BAR = 'bar';

    public const BAZ = 'baz';
}

$mapper = (new MapperBuilder())->mapper();

$mapper->map('SomeClassWithConstants::BA*', 1337); // error
$mapper->map('SomeClassWithConstants::BA*', 'bar'); // ok
$mapper->map('SomeClassWithConstants::BA*', 'baz'); // ok
```
2022-10-04 22:15:02 +02:00
Romain Canon
69ebd19ee8 feat: add support for wildcard in enumeration type
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
```
2022-10-04 20:44:55 +02:00
Patrick Landolt
2b9d81cc45
doc: fix typo in code example 2022-09-30 13:12:12 +02:00
Romain Canon
cb87925aac feat: introduce utility class to build messages
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();
```
2022-09-29 13:52:06 +02:00
Romain Canon
d8957c061d release: version 0.14.0 2022-09-01 12:51:11 +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
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
444747ab0a release: version 0.13.0 2022-07-31 17:23:28 +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
bd74557e75 release: version 0.12.0 2022-07-10 19:57:21 +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
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
4d80ae337d doc: add google site verification meta tag 2022-07-05 23:11:16 +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
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
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
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
Romain Canon
741d54c32e doc: add support & thanks section 2022-06-07 15:26:18 +02:00