Completed
Push — master ( 8c953e...7fbcf6 )
by Thomas
37s
created

Owner::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
3
namespace ORM\Relation;
4
5
use ORM\Entity;
6
use ORM\EntityFetcher;
7
use ORM\EntityManager;
8
use ORM\Exceptions\IncompletePrimaryKey;
9
use ORM\Exceptions\InvalidRelation;
10
use ORM\Relation;
11
12
class Owner extends Relation
13
{
14
    /** Reference definition as key value pairs
15
     * @var array */
16
    protected $reference;
17
18
    /**
19
     * Owner constructor.
20
     *
21
     * @param string $name
22
     * @param string $class
23
     * @param array  $reference
24
     */
25 5
    public function __construct($name, $class, array $reference)
26
    {
27 5
        $this->name = $name;
28 5
        $this->class = $class;
29 5
        $this->reference = $reference;
30 5
    }
31
32
    /** {@inheritdoc} */
33 4
    public function fetch(Entity $me, EntityManager $entityManager)
34
    {
35 4
        $key = array_map([$me, '__get'], array_keys($this->reference));
36
37 4
        if (in_array(null, $key)) {
38 2
            return null;
39
        }
40
41 2
        return $entityManager->fetch($this->class, $key);
42
    }
43
44
    /** {@inheritdoc} */
45 5
    public function setRelated(Entity $me, Entity $entity = null)
46
    {
47 5
        if ($entity !== null && !$entity instanceof $this->class) {
48 1
            throw new InvalidRelation('Invalid entity for relation ' . $this->name);
49
        }
50
51 4
        foreach ($this->reference as $fkVar => $var) {
52 4
            if ($entity === null) {
53 1
                $me->__set($fkVar, null);
54 1
                continue;
55
            }
56
57 4
            $value = $entity->__get($var);
58
59 4
            if ($value === null) {
60 1
                throw new IncompletePrimaryKey('Key incomplete to save foreign key');
61
            }
62
63 3
            $me->__set($fkVar, $value);
64
        }
65 3
    }
66
67
    /** {@inheritdoc} */
68 2
    public function addJoin(EntityFetcher $fetcher, $join, $alias)
69
    {
70 2
        $expression = [];
71 2
        foreach ($this->reference as $myVar => $hisVar) {
72 2
            $expression[] = $alias . '.' . $myVar . ' = ' . $this->name . '.' . $hisVar;
73
        }
74
75 2
        call_user_func([$fetcher, $join], $this->class, implode(' AND ', $expression), $this->name, [], true);
76 2
    }
77
}
78