1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cypress\PatchManager; |
6
|
|
|
|
7
|
|
|
use Cypress\PatchManager\Request\Operations; |
8
|
|
|
use PhpCollection\Sequence; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Match the correct handlers based on actual operations |
12
|
|
|
*/ |
13
|
|
|
class OperationMatcher |
14
|
|
|
{ |
15
|
|
|
private Sequence $handlers; |
|
|
|
|
16
|
|
|
|
17
|
|
|
private Operations $operations; |
|
|
|
|
18
|
|
|
|
19
|
7 |
|
public function __construct(Operations $operations) |
20
|
|
|
{ |
21
|
7 |
|
$this->handlers = new Sequence(); |
22
|
7 |
|
$this->operations = $operations; |
23
|
|
|
} |
24
|
|
|
|
25
|
6 |
|
public function addHandler(PatchOperationHandler $handler): void |
26
|
|
|
{ |
27
|
6 |
|
$this->handlers->add($handler); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param array|Patchable|\Traversable $subject a Patchable instance or a collection of instances |
32
|
|
|
* |
33
|
|
|
* @throws Exception\MissingOperationNameRequest |
34
|
|
|
* @throws Exception\MissingOperationRequest |
35
|
|
|
* @throws Exception\InvalidJsonRequestContent |
36
|
|
|
*/ |
37
|
7 |
|
public function getMatchedOperations($subject): Sequence |
38
|
|
|
{ |
39
|
7 |
|
$handlers = $this->handlers; |
40
|
|
|
|
41
|
7 |
|
return $this->operations |
42
|
7 |
|
->all() |
43
|
7 |
|
->foldLeft( |
44
|
7 |
|
new Sequence(), |
45
|
7 |
|
function (Sequence $matchedOperations, array $operationData) use ($handlers, $subject) { |
46
|
7 |
|
$handler = $handlers->find(fn (PatchOperationHandler $patchHandler) => $operationData[Operations::OP_KEY_NAME] === $patchHandler->getName()); |
47
|
7 |
|
if ($handler->isDefined()) { |
48
|
|
|
/** @var PatchOperationHandler $patchOperationHandler */ |
49
|
4 |
|
$patchOperationHandler = $handler->get(); |
50
|
4 |
|
if ($patchOperationHandler->canHandle($subject)) { |
51
|
3 |
|
$matchedOperations->add(MatchedPatchOperation::create($operationData, $handler->get())); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
7 |
|
return $matchedOperations; |
56
|
7 |
|
} |
57
|
7 |
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param array|Patchable|\Traversable $subject a Patchable instance or a collection of instances |
62
|
|
|
* @throws Exception\InvalidJsonRequestContent |
63
|
|
|
* @throws Exception\MissingOperationNameRequest |
64
|
|
|
* @throws Exception\MissingOperationRequest |
65
|
|
|
*/ |
66
|
2 |
|
public function getUnmatchedOperations($subject): Sequence |
67
|
|
|
{ |
68
|
2 |
|
return $this->operations |
69
|
2 |
|
->all() |
70
|
2 |
|
->filter(fn (array $operationData) => $operationData !== $this->getMatchedOperations($subject)) |
71
|
2 |
|
->map(fn (array $operationData) => $operationData['op']); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|