Passed
Push — master ( 0a4fc8...34ac19 )
by Anton
04:11
created

NodeTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 37
rs 10
c 0
b 0
f 0
wmc 6

1 Method

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