Completed
Pull Request — master (#49)
by Thomas
02:50
created

Owner::setRelated()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

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