1 | <?php |
||
2 | /** |
||
3 | * Cycle DataMapper ORM |
||
4 | * |
||
5 | * @license MIT |
||
6 | * @author Anton Titov (Wolfy-J) |
||
7 | */ |
||
8 | declare(strict_types=1); |
||
9 | |||
10 | namespace Cycle\ORM\Relation\Morphed; |
||
11 | |||
12 | use Cycle\ORM\Command\CommandInterface; |
||
13 | use Cycle\ORM\Command\ContextCarrierInterface as CC; |
||
14 | use Cycle\ORM\Exception\RelationException; |
||
15 | use Cycle\ORM\Heap\Node; |
||
16 | use Cycle\ORM\ORMInterface; |
||
17 | use Cycle\ORM\Relation; |
||
18 | use Cycle\ORM\Relation\BelongsTo; |
||
19 | |||
20 | class BelongsToMorphed extends BelongsTo |
||
21 | { |
||
22 | /** @var string */ |
||
23 | private $morphKey; |
||
24 | |||
25 | /** |
||
26 | * @param ORMInterface $orm |
||
27 | * @param string $target |
||
28 | * @param string $name |
||
29 | * @param array $schema |
||
30 | */ |
||
31 | public function __construct(ORMInterface $orm, string $name, string $target, array $schema) |
||
32 | { |
||
33 | parent::__construct($orm, $name, $target, $schema); |
||
34 | $this->morphKey = $schema[Relation::MORPH_KEY]; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @inheritdoc |
||
39 | */ |
||
40 | public function initPromise(Node $node): array |
||
41 | { |
||
42 | if (is_null($innerKey = $this->fetchKey($node, $this->innerKey))) { |
||
43 | return [null, null]; |
||
44 | } |
||
45 | |||
46 | /** @var string $target */ |
||
47 | $target = $this->fetchKey($node, $this->morphKey); |
||
48 | if (is_null($target)) { |
||
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
49 | return [null, null]; |
||
50 | } |
||
51 | |||
52 | $r = $this->orm->promise($target, [$this->outerKey => $innerKey]); |
||
53 | |||
54 | return [$r, $r]; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @inheritdoc |
||
59 | */ |
||
60 | public function queue(CC $store, $entity, Node $node, $related, $original): CommandInterface |
||
61 | { |
||
62 | $wrappedStore = parent::queue($store, $entity, $node, $related, $original); |
||
63 | |||
64 | if (is_null($related)) { |
||
65 | if ($this->fetchKey($node, $this->morphKey) !== null) { |
||
66 | $store->register($this->morphKey, null, true); |
||
67 | $node->register($this->morphKey, null, true); |
||
68 | } |
||
69 | } else { |
||
70 | $rNode = $this->getNode($related); |
||
71 | if ($this->fetchKey($node, $this->morphKey) != $rNode->getRole()) { |
||
72 | $store->register($this->morphKey, $rNode->getRole(), true); |
||
73 | $node->register($this->morphKey, $rNode->getRole(), true); |
||
74 | } |
||
75 | } |
||
76 | |||
77 | return $wrappedStore; |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Assert that given entity is allowed for the relation. |
||
82 | * |
||
83 | * @param Node $related |
||
84 | * |
||
85 | * @throws RelationException |
||
86 | */ |
||
87 | protected function assertValid(Node $related) |
||
88 | { |
||
89 | // no need to validate morphed relation yet |
||
90 | } |
||
91 | } |