1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
/** |
4
|
|
|
* Spiral Framework. |
5
|
|
|
* |
6
|
|
|
* @license MIT |
7
|
|
|
* @author Anton Titov (Wolfy-J) |
8
|
|
|
*/ |
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\HasOne; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Inverted version of belongs to morphed. |
22
|
|
|
*/ |
23
|
|
|
class MorphedHasOne extends HasOne |
24
|
|
|
{ |
25
|
|
|
/** @var string */ |
26
|
|
|
private $morphKey; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param ORMInterface $orm |
30
|
|
|
* @param string $target |
31
|
|
|
* @param string $name |
32
|
|
|
* @param array $schema |
33
|
|
|
*/ |
34
|
|
|
public function __construct(ORMInterface $orm, string $name, string $target, array $schema) |
35
|
|
|
{ |
36
|
|
|
parent::__construct($orm, $name, $target, $schema); |
37
|
|
|
$this->morphKey = $schema[Relation::MORPH_KEY]; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @inheritdoc |
42
|
|
|
*/ |
43
|
|
|
public function initPromise(Node $parentNode): array |
44
|
|
|
{ |
45
|
|
|
if (is_null($innerKey = $this->fetchKey($parentNode, $this->innerKey))) { |
46
|
|
|
return [null, null]; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$scope = [ |
50
|
|
|
$this->outerKey => $innerKey, |
51
|
|
|
$this->morphKey => $parentNode->getRole() |
52
|
|
|
]; |
53
|
|
|
|
54
|
|
|
|
55
|
|
|
$r = $this->orm->promise($this->target, $scope); |
|
|
|
|
56
|
|
|
|
57
|
|
|
return [$r, $r]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @inheritdoc |
62
|
|
|
*/ |
63
|
|
|
public function queue(CC $parentStore, $parentEntity, Node $parentNode, $related, $original): CommandInterface |
64
|
|
|
{ |
65
|
|
|
$relStore = parent::queue($parentStore, $parentEntity, $parentNode, $related, $original); |
66
|
|
|
|
67
|
|
|
if ($relStore instanceof CC && !is_null($related)) { |
68
|
|
|
$relNode = $this->getNode($related); |
69
|
|
|
|
70
|
|
|
if ($this->fetchKey($relNode, $this->morphKey) != $parentNode->getRole()) { |
71
|
|
|
$relStore->register($this->morphKey, $parentNode->getRole(), true); |
72
|
|
|
$relNode->register($this->morphKey, $parentNode->getRole(), true); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $relStore; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Assert that given entity is allowed for the relation. |
81
|
|
|
* |
82
|
|
|
* @param Node $relNode |
83
|
|
|
* |
84
|
|
|
* @throws RelationException |
85
|
|
|
*/ |
86
|
|
|
protected function assertValid(Node $relNode) |
87
|
|
|
{ |
88
|
|
|
// no need to validate morphed relation yet |
89
|
|
|
} |
90
|
|
|
} |