Skip to content

Commit 99933ff

Browse files
authored
feat(mapper): json file to object mapper (#748)
1 parent af70b4e commit 99933ff

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Mapper\Mappers;
6+
7+
use function Tempest\map;
8+
use Tempest\Mapper\Mapper;
9+
use function Tempest\path;
10+
11+
final readonly class JsonFileToObjectMapper implements Mapper
12+
{
13+
public function canMap(mixed $from, mixed $to): bool
14+
{
15+
if (! is_string($from)) {
16+
return false;
17+
}
18+
19+
$path = path($from);
20+
21+
return $path->exists() && $path->extension() === 'json';
22+
}
23+
24+
public function map(mixed $from, mixed $to): array
25+
{
26+
return map(json_decode(file_get_contents($from), associative: true))->collection()->to($to);
27+
}
28+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[
2+
{
3+
"a": "a",
4+
"b": "b"
5+
},
6+
{
7+
"a": "c",
8+
"b": "d"
9+
}
10+
]
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests\Tempest\Integration\Mapper\Mappers;
6+
7+
use function Tempest\map;
8+
use Tests\Tempest\Integration\FrameworkIntegrationTestCase;
9+
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectA;
10+
11+
/**
12+
* @internal
13+
*/
14+
final class JsonFileToObjectMapperTest extends FrameworkIntegrationTestCase
15+
{
16+
public function test_mapper(): void
17+
{
18+
$objects = map(__DIR__ . '/../Fixtures/objects.json')->collection()->to(ObjectA::class);
19+
20+
$this->assertCount(2, $objects);
21+
$this->assertSame('a', $objects[0]->a);
22+
$this->assertSame('b', $objects[0]->b);
23+
$this->assertSame('c', $objects[1]->a);
24+
$this->assertSame('d', $objects[1]->b);
25+
}
26+
}

0 commit comments

Comments
 (0)