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; |
11
|
|
|
|
12
|
|
|
use Cycle\ORM\Command\Branch\Nil; |
13
|
|
|
use Cycle\ORM\Command\CommandInterface; |
14
|
|
|
use Cycle\ORM\Command\ContextCarrierInterface as CC; |
15
|
|
|
use Cycle\ORM\Command\Database\Update; |
16
|
|
|
use Cycle\ORM\Heap\Node; |
17
|
|
|
use Cycle\ORM\Relation\Traits\PromiseOneTrait; |
18
|
|
|
use Cycle\ORM\Schema; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Variation of belongs-to relation which provides the ability to be self. Relation can be used |
22
|
|
|
* to create cyclic references. Relation does not trigger store operation of referenced object! |
23
|
|
|
*/ |
24
|
|
|
class RefersTo extends AbstractRelation implements DependencyInterface |
25
|
|
|
{ |
26
|
|
|
use PromiseOneTrait; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @inheritdoc |
30
|
|
|
*/ |
31
|
|
|
public function queue(CC $parentStore, $parentEntity, Node $parentNode, $related, $original): CommandInterface |
32
|
|
|
{ |
33
|
|
|
// refers-to relation is always nullable (as opposite to belongs-to) |
34
|
|
|
if (is_null($related)) { |
35
|
|
|
if (!is_null($original)) { |
36
|
|
|
$parentStore->register($this->innerKey, null, true); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return new Nil(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$relNode = $this->getNode($related); |
43
|
|
|
$this->assertValid($relNode); |
|
|
|
|
44
|
|
|
|
45
|
|
|
// related object exists, we can update key immediately |
46
|
|
|
if (!is_null($outerKey = $this->fetchKey($relNode, $this->outerKey))) { |
47
|
|
|
if ($outerKey != $this->fetchKey($parentNode, $this->innerKey)) { |
48
|
|
|
$parentStore->register($this->innerKey, $outerKey, true); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return new Nil(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// update parent entity once related instance is able to provide us context key |
55
|
|
|
$update = new Update( |
56
|
|
|
$this->getSource($parentNode->getRole())->getDatabase(), |
57
|
|
|
$this->getSource($parentNode->getRole())->getTable() |
58
|
|
|
); |
59
|
|
|
|
60
|
|
|
// fastest way to identify the entity |
61
|
|
|
$pk = $this->orm->getSchema()->define($parentNode->getRole(), Schema::PRIMARY_KEY); |
|
|
|
|
62
|
|
|
|
63
|
|
|
$this->forwardContext($relNode, $this->outerKey, $update, $parentNode, $this->innerKey); |
64
|
|
|
|
65
|
|
|
// set where condition for update query |
66
|
|
|
$this->forwardScope($parentNode, $pk, $update, $pk); |
67
|
|
|
|
68
|
|
|
return $update; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|