-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRememberingMapper.php
65 lines (50 loc) · 1.93 KB
/
RememberingMapper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
/*
* This file is part of rekalogika/mapper package.
*
* (c) Priyadi Iman Nurcahyo <https://rekalogika.dev>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
namespace Rekalogika\Mapper\Tests\Fixtures\RememberingMapper;
use Rekalogika\Mapper\Context\Context;
use Rekalogika\Mapper\Exception\UnexpectedValueException;
use Rekalogika\Mapper\MapperInterface;
use Rekalogika\Mapper\ObjectCache\ObjectCacheFactoryInterface;
use Rekalogika\Mapper\Transformer\Context\PresetMapping;
use Rekalogika\Mapper\Transformer\Context\PresetMappingFactory;
use Symfony\Contracts\Service\ResetInterface;
class RememberingMapper implements MapperInterface, ResetInterface
{
private PresetMapping $presetMapping;
public function __construct(
private MapperInterface $decorated,
private ObjectCacheFactoryInterface $objectCacheFactory
) {
$this->presetMapping = new PresetMapping();
}
public function reset(): void
{
$this->presetMapping = new PresetMapping();
}
public function map(object $source, object|string $target, ?Context $context = null): object
{
$objectCache = $this->objectCacheFactory->createObjectCache();
if ($context === null) {
$context = Context::create();
}
$context = $context->with($objectCache, $this->presetMapping);
$result = $this->decorated->map($source, $target, $context);
if (is_object($target)) {
$target = $target::class;
}
if (!$result instanceof $target) {
throw new UnexpectedValueException(sprintf('Expected instance of "%s", got "%s"', $target, get_class($result)));
}
$newPresetMapping = PresetMappingFactory::fromObjectCacheReversed($objectCache);
$this->presetMapping->mergeFrom($newPresetMapping);
return $result;
}
}