|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Remorhaz\JSON\Patch\Query; |
|
5
|
|
|
|
|
6
|
|
|
use Remorhaz\JSON\Data\Export\ValueDecoderInterface; |
|
7
|
|
|
use Remorhaz\JSON\Data\Export\ValueEncoderInterface; |
|
8
|
|
|
use Remorhaz\JSON\Data\Value\ArrayValueInterface; |
|
9
|
|
|
use Remorhaz\JSON\Data\Value\NodeValueInterface; |
|
10
|
|
|
use Remorhaz\JSON\Patch\Operation\OperationFactoryInterface; |
|
11
|
|
|
use Remorhaz\JSON\Patch\Result\ResultInterface; |
|
12
|
|
|
use Remorhaz\JSON\Pointer\Processor\ProcessorInterface as PointerProcessorInterface; |
|
13
|
|
|
use Throwable; |
|
14
|
|
|
|
|
15
|
|
|
final class LazyQuery implements QueryInterface |
|
16
|
|
|
{ |
|
17
|
|
|
|
|
18
|
|
|
private $operationFactory; |
|
19
|
|
|
|
|
20
|
|
|
private $encoder; |
|
21
|
|
|
|
|
22
|
|
|
private $decoder; |
|
23
|
|
|
|
|
24
|
|
|
private $patch; |
|
25
|
|
|
|
|
26
|
|
|
private $loadedQuery; |
|
27
|
|
|
|
|
28
|
|
|
public function __construct( |
|
29
|
|
|
OperationFactoryInterface $operationFactory, |
|
30
|
|
|
ValueEncoderInterface $encoder, |
|
31
|
|
|
ValueDecoderInterface $decoder, |
|
32
|
|
|
NodeValueInterface $patch |
|
33
|
|
|
) { |
|
34
|
|
|
$this->operationFactory = $operationFactory; |
|
35
|
|
|
$this->encoder = $encoder; |
|
36
|
|
|
$this->decoder = $decoder; |
|
37
|
|
|
$this->patch = $patch; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function __invoke(NodeValueInterface $data, PointerProcessorInterface $pointerProcessor): ResultInterface |
|
41
|
|
|
{ |
|
42
|
|
|
return $this->getLoadedQuery()($data, $pointerProcessor); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
private function getLoadedQuery(): QueryInterface |
|
46
|
|
|
{ |
|
47
|
|
|
if (!isset($this->loadedQuery)) { |
|
48
|
|
|
$this->loadedQuery = $this->loadQuery(); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return $this->loadedQuery; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
private function loadQuery(): QueryInterface |
|
55
|
|
|
{ |
|
56
|
|
|
$operations = []; |
|
57
|
|
|
try { |
|
58
|
|
|
if (!$this->patch instanceof ArrayValueInterface) { |
|
59
|
|
|
throw new Exception\InvalidPatchException($this->patch); |
|
60
|
|
|
} |
|
61
|
|
|
foreach ($this->patch->createChildIterator() as $index => $operationData) { |
|
|
|
|
|
|
62
|
|
|
$operations[] = $this |
|
63
|
|
|
->operationFactory |
|
64
|
|
|
->fromJson($operationData, $index); |
|
65
|
|
|
} |
|
66
|
|
|
} catch (Throwable $e) { |
|
67
|
|
|
throw new Exception\PatchNotLoadedException($this->patch, $e); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return new Query($this->encoder, $this->decoder, ...$operations); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|