IdAwareRepository   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 100
c 0
b 0
f 0
wmc 9
lcom 1
cbo 4
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A persist() 0 4 1
A persistEntity() 0 8 2
A remove() 0 4 1
A insert() 0 11 2
A update() 0 10 1
A removeEntity() 0 11 1
A getIdField() 0 4 1
1
<?php
2
3
namespace Koine\Repository;
4
5
use Koine\Repository\Entity\GeneratedIdInterface;
6
7
class IdAwareRepository extends Repository
8
{
9
    /**
10
     * {@inheritdoc}
11
     *
12
     * @param GeneratedIdInterface $entity
13
     *
14
     * @return mixed
15
     */
16
    public function persist($entity)
17
    {
18
        return $this->persistEntity($entity);
19
    }
20
21
    /**
22
     * {@inheritdoc}
23
     *
24
     * @param GeneratedIdInterface $entity
25
     *
26
     * @return mixed
27
     */
28
    protected function persistEntity(GeneratedIdInterface $entity)
29
    {
30
        if ($entity->getId()) {
31
            return $this->update($entity);
32
        } else {
33
            return $this->insert($entity);
34
        }
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     *
40
     * @param GeneratedIdInterface $entity
41
     *
42
     * @return mixed
43
     */
44
    public function remove($entity)
45
    {
46
        return $this->removeEntity($entity);
47
    }
48
49
    /**
50
     * @param GeneratedIdInterface $entity
51
     *
52
     * @return int
53
     */
54
    protected function insert(GeneratedIdInterface $entity)
55
    {
56
        $data = $this->getHydrator()->extract($entity);
57
        $generatedId = $this->getStorage()->insert($data);
58
59
        if ($generatedId) {
60
            $entity->setGeneratedId($generatedId);
61
        }
62
63
        return $generatedId;
64
    }
65
66
    /**
67
     * @param GeneratedIdInterface $entity
68
     *
69
     * @return mixed
70
     */
71
    protected function update(GeneratedIdInterface $entity)
72
    {
73
        $data = $this->getHydrator()->extract($entity);
74
75
        $conditions = array(
76
            $this->getIdField() => $entity->getId(),
77
        );
78
79
        return $this->getStorage()->updateWhere($conditions, $data);
80
    }
81
82
    /**
83
     * @param GeneratedIdInterface $entity
84
     *
85
     * @return mixed
86
     */
87
    private function removeEntity(GeneratedIdInterface $entity)
88
    {
89
        $conditions = array(
90
            $this->getIdField() => $entity->getId(),
91
        );
92
93
        $result = $this->getStorage()->deleteWhere($conditions);
94
        $entity->setGeneratedId(null);
95
96
        return $result;
97
    }
98
99
    /**
100
     * @return string
101
     */
102
    protected function getIdField()
103
    {
104
        return 'id';
105
    }
106
}
107