Valinor/tests/Unit/Mapper/TreeMapperContainerTest.php
Romain Canon b2e810e3ce feat!: allow mapping to any type
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.
2022-01-02 00:48:01 +01:00

37 lines
1.0 KiB
PHP

<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Unit\Mapper;
use CuyZ\Valinor\Mapper\Exception\InvalidMappingTypeSignature;
use CuyZ\Valinor\Mapper\Tree\Builder\RootNodeBuilder;
use CuyZ\Valinor\Mapper\TreeMapperContainer;
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Builder\FakeNodeBuilder;
use CuyZ\Valinor\Tests\Fake\Type\Parser\FakeTypeParser;
use PHPUnit\Framework\TestCase;
final class TreeMapperContainerTest extends TestCase
{
private TreeMapperContainer $mapper;
protected function setUp(): void
{
parent::setUp();
$this->mapper = new TreeMapperContainer(
new FakeTypeParser(),
new RootNodeBuilder(new FakeNodeBuilder()),
);
}
public function test_invalid_mapping_type_signature_throws_exception(): void
{
$this->expectException(InvalidMappingTypeSignature::class);
$this->expectExceptionCode(1630959692);
$this->expectExceptionMessageMatches('/^Could not parse the type `foo` that should be mapped: .*/');
$this->mapper->map('foo', []);
}
}