Passed
Push — master ( 9676b0...44a032 )
by Anton
02:07
created

src/Relation/RefersTo.php (1 issue)

Labels
Severity
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;
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);
0 ignored issues
show
It seems like $relNode can also be of type null; however, parameter $relNode of Cycle\ORM\Relation\AbstractRelation::assertValid() does only seem to accept Cycle\ORM\Heap\Node, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

43
        $this->assertValid(/** @scrutinizer ignore-type */ $relNode);
Loading history...
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