|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Spiral Framework. |
|
4
|
|
|
* |
|
5
|
|
|
* @license MIT |
|
6
|
|
|
* @author Anton Titov (Wolfy-J) |
|
7
|
|
|
*/ |
|
8
|
|
|
declare(strict_types=1); |
|
9
|
|
|
|
|
10
|
|
|
namespace Spiral\Cycle; |
|
11
|
|
|
|
|
12
|
|
|
use Spiral\Cycle\Command\Branch\Nil; |
|
13
|
|
|
use Spiral\Cycle\Command\Branch\Split; |
|
14
|
|
|
use Spiral\Cycle\Command\CommandInterface; |
|
15
|
|
|
use Spiral\Cycle\Command\ContextCarrierInterface; |
|
16
|
|
|
use Spiral\Cycle\Command\InitCarrierInterface; |
|
17
|
|
|
use Spiral\Cycle\Heap\Node; |
|
18
|
|
|
use Spiral\Cycle\Mapper\MapperInterface; |
|
19
|
|
|
use Spiral\Cycle\Promise\PromiseInterface; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Responsible for proper command chain generation. |
|
23
|
|
|
*/ |
|
24
|
|
|
final class CommandGenerator |
|
25
|
|
|
{ |
|
26
|
|
|
/** |
|
27
|
|
|
* @inheritdoc |
|
28
|
|
|
*/ |
|
29
|
|
|
public function generateStore(MapperInterface $mapper, $entity, Node $node): ContextCarrierInterface |
|
30
|
|
|
{ |
|
31
|
|
|
if ($entity instanceof PromiseInterface) { |
|
32
|
|
|
// we do not expect to store promises |
|
33
|
|
|
return new Nil(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
if ($node->getStatus() == Node::NEW) { |
|
37
|
|
|
$cmd = $mapper->queueCreate($entity, $node->getState()); |
|
38
|
|
|
$node->getState()->setCommand($cmd); |
|
39
|
|
|
|
|
40
|
|
|
return $cmd; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$lastCommand = $node->getState()->getCommand(); |
|
44
|
|
|
if (empty($lastCommand)) { |
|
45
|
|
|
return $mapper->queueUpdate($entity, $node->getState()); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
// Command can aggregate multiple operations on soft basis. |
|
49
|
|
|
if (!$lastCommand instanceof InitCarrierInterface) { |
|
50
|
|
|
return $lastCommand; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
// in cases where we have to update new entity we can merge two commands into one |
|
54
|
|
|
$split = new Split($lastCommand, $mapper->queueUpdate($entity, $node->getState())); |
|
55
|
|
|
$node->getState()->setCommand($split); |
|
56
|
|
|
|
|
57
|
|
|
return $split; |
|
58
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @inheritdoc |
|
63
|
|
|
*/ |
|
64
|
|
|
public function generateDelete(MapperInterface $mapper, $entity, Node $node): CommandInterface |
|
65
|
|
|
{ |
|
66
|
|
|
// currently we rely on db to delete all nested records (or soft deletes) |
|
67
|
|
|
return $mapper->queueDelete($entity, $node->getState()); |
|
68
|
|
|
} |
|
69
|
|
|
} |