Passed
Push — master ( a0406a...5d779f )
by Anton
06:34 queued 04:24
created

NodeTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 41
rs 10
c 1
b 0
f 0
wmc 8

1 Method

Rating   Name   Duplication   Size   Complexity  
B getNode() 0 31 8
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\ORM\Relation\Traits;
13
14
use Cycle\ORM\Heap\Node;
15
use Cycle\ORM\Promise\PromiseInterface;
16
use Cycle\ORM\Promise\ReferenceInterface;
17
18
trait NodeTrait
19
{
20
    /**
21
     * Get Node for the given entity. Null if entity does not exists. Automatically
22
     * register entity claims.
23
     *
24
     * @param object $entity
25
     * @param int    $claim
26
     * @return Node|null
27
     */
28
    protected function getNode($entity, int $claim = 0): ?Node
29
    {
30
        if ($entity === null) {
31
            return null;
32
        }
33
34
        if ($entity instanceof PromiseInterface && $entity->__loaded()) {
35
            $entity = $entity->__resolve();
36
        }
37
38
        if ($entity instanceof ReferenceInterface) {
39
            return new Node(Node::PROMISED, $entity->__scope(), $entity->__role());
40
        }
41
42
        $node = $this->orm->getHeap()->get($entity);
43
44
        if ($node === null) {
45
            // possibly rely on relation target role, it will allow context switch
46
            $node = new Node(Node::NEW, [], $this->orm->getMapper($entity)->getRole());
47
            $this->orm->getHeap()->attach($entity, $node);
48
        }
49
50
        if ($claim === 1) {
51
            $node->getState()->addClaim();
52
        }
53
54
        if ($claim === -1) {
55
            $node->getState()->decClaim();
56
        }
57
58
        return $node;
59
    }
60
}
61