mirror of
https://github.com/danog/Valinor.git
synced 2024-12-14 18:16:19 +01:00
b7a7d22993
This modifier can be used to change paths in the source data using a dot notation. The mapping is done using an associative array of path mappings. This array must have the source path as key and the target path as value. The source path uses the dot notation (eg `A.B.C`) and can contain one `*` for array paths (eg `A.B.*.C`). ```php final class Country { /** @var City[] */ public readonly array $cities; } final class City { public readonly string $name; } $source = new \CuyZ\Valinor\Mapper\Source\Modifier\PathMapping([ 'towns' => [ ['label' => 'Ankh Morpork'], ['label' => 'Minas Tirith'], ], ], [ 'towns' => 'cities', 'towns.*.label' => 'name', ]); // After modification this is what the source will look like: [ 'cities' => [ ['name' => 'Ankh Morpork'], ['name' => 'Minas Tirith'], ], ]; (new \CuyZ\Valinor\MapperBuilder()) ->mapper() ->map(Country::class, $source); ```
81 lines
2.1 KiB
PHP
81 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace CuyZ\Valinor\Tests\Unit\Mapper\Source\Modifier;
|
|
|
|
use CuyZ\Valinor\Mapper\Source\Modifier\Mapping;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
final class MappingTest extends TestCase
|
|
{
|
|
/**
|
|
* @dataProvider mappingsDataProvider
|
|
*
|
|
* @param array<string> $keys
|
|
* @param string|int $targetKey
|
|
*/
|
|
public function test_matches_string_key_at_sub_level(
|
|
array $keys,
|
|
string $to,
|
|
$targetKey,
|
|
int $targetDepth,
|
|
bool $expectedMatch,
|
|
?string $expectedTo
|
|
): void {
|
|
$mapping = new Mapping($keys, $to);
|
|
|
|
self::assertSame($expectedMatch, $mapping->matches($targetKey, $targetDepth));
|
|
self::assertSame($expectedTo, $mapping->findMappedKey($targetKey, $targetDepth));
|
|
}
|
|
|
|
/**
|
|
* @return array<mixed>
|
|
*/
|
|
public function mappingsDataProvider(): array
|
|
{
|
|
return [
|
|
[
|
|
'keys' => ['A'],
|
|
'to' => 'newA',
|
|
'targetKey' => 'A',
|
|
'targetDepth' => 0,
|
|
'expectedMatch' => true,
|
|
'expectedTo' => 'newA',
|
|
],
|
|
[
|
|
'keys' => ['A', 'B'],
|
|
'to' => 'newB',
|
|
'targetKey' => 'B',
|
|
'targetDepth' => 1,
|
|
'expectedMatch' => true,
|
|
'expectedTo' => 'newB',
|
|
],
|
|
[
|
|
'keys' => ['A', 'B', 'C'],
|
|
'to' => 'newB',
|
|
'targetKey' => 'B',
|
|
'targetDepth' => 1,
|
|
'expectedMatch' => true,
|
|
'expectedTo' => null,
|
|
],
|
|
[
|
|
'keys' => ['A', '*', 'B'],
|
|
'to' => 'newB',
|
|
'targetKey' => 'B',
|
|
'targetDepth' => 1,
|
|
'expectedMatch' => true,
|
|
'expectedTo' => null,
|
|
],
|
|
[
|
|
'keys' => ['A', '*', 'B'],
|
|
'to' => 'newB',
|
|
'targetKey' => 'B',
|
|
'targetDepth' => 2,
|
|
'expectedMatch' => true,
|
|
'expectedTo' => 'newB',
|
|
],
|
|
];
|
|
}
|
|
}
|