Passed
Push — master ( ecf49a...4e3a77 )
by Joao
02:50 queued 27s
created

Repository   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 232
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 98.1%

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 6
dl 0
loc 232
ccs 103
cts 105
cp 0.981
rs 10
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getDbDriver() 0 4 1
A get() 0 10 2
A delete() 0 9 1
A getMapper() 0 4 1
A deleteByQuery() 0 9 1
A getByFilter() 0 12 2
D getByQuery() 0 39 9
B save() 0 35 5
A insert() 0 9 2
A insertWithAutoinc() 0 6 1
A insertWithKeyGen() 0 7 1
A update() 0 9 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: jg
5
 * Date: 21/06/16
6
 * Time: 16:17
7
 */
8
9
namespace ByJG\MicroOrm;
10
11
12
use ByJG\AnyDataset\DbDriverInterface;
13
use ByJG\Serializer\BinderObject;
14
15
class Repository
16
{
17
18
    /**
19
     * @var Mapper
20
     */
21
    protected $mapper;
22
23
    /**
24
     * @var DbDriverInterface
25
     */
26
    protected $dbDriver = null;
27
28
    /**
29
     * Repository constructor.
30
     * @param DbDriverInterface $dbDataset
31
     * @param Mapper $mapper
32
     */
33 21
    public function __construct(DbDriverInterface $dbDataset, Mapper $mapper)
34
    {
35 21
        $this->dbDriver = $dbDataset;
36 21
        $this->mapper = $mapper;
37 21
    }
38
39
    /**
40
     * @return Mapper
41
     */
42 9
    public function getMapper()
43
    {
44 9
        return $this->mapper;
45
    }
46
47
    /**
48
     * @return DbDriverInterface
49
     */
50 21
    protected function getDbDriver()
51
    {
52 21
        return $this->dbDriver;
53
    }
54
55
    /**
56
     * @param array|string $id
57
     * @return mixed|null
58
     */
59 14
    public function get($id)
60
    {
61 14
        $result = $this->getByFilter($this->mapper->getPrimaryKey() . ' = [[id]]', ['id' => $id]);
62
63 14
        if (count($result) === 1) {
64 14
            return $result[0];
65
        }
66
67 3
        return null;
68
    }
69
70
    /**
71
     * @param array $id
72
     * @return mixed|null
73
     */
74 2
    public function delete($id)
75
    {
76 2
        $params = ['id' => $id];
77 2
        $updatable = Updatable::getInstance()
78 2
            ->table($this->mapper->getTable())
79 2
            ->where($this->mapper->getPrimaryKey() . ' = [[id]]', $params);
80
81 2
        return $this->deleteByQuery($updatable);
82
    }
83
84
    /**
85
     * @param $updatable
86
     * @return bool
87
     */
88 3
    public function deleteByQuery(Updatable $updatable)
89
    {
90 3
        $params = [];
91 3
        $sql = $updatable->buildDelete($params);
92
93 3
        $this->getDbDriver()->execute($sql, $params);
94
95 3
        return true;
96
    }
97
98
    /**
99
     * @param string $filter
100
     * @param array $params
101
     * @param bool $forUpdate
102
     * @return array
103
     */
104 14
    public function getByFilter($filter, array $params, $forUpdate = false)
105
    {
106 14
        $query = new Query();
107 14
        $query->table($this->mapper->getTable())
108 14
            ->where($filter, $params);
109
        
110 14
        if ($forUpdate) {
111
            $query->forUpdate();
112
        }
113
114 14
        return $this->getByQuery($query);
115
    }
116
117
    /**
118
     * @param Query $query
119
     * @param Mapper[] $mapper
120
     * @return array
121
     */
122 21
    public function getByQuery(Query $query, array $mapper = [])
123
    {
124 21
        $mapper = array_merge([$this->mapper], $mapper);
125 21
        $query = $query->build($this->getDbDriver());
126
127 21
        $params = $query['params'];
128 21
        $sql = $query['sql'];
129 21
        $result = [];
130 21
        $iterator = $this->getDbDriver()->getIterator($sql, $params);
131
132 21
        foreach ($iterator as $row) {
133 21
            $collection = [];
134 21
            foreach ($mapper as $item) {
135 21
                $instance = $item->getEntity();
136 21
                $data = $row->toArray();
137
138 21
                foreach ((array)$item->getFieldAlias() as $fieldname => $fieldalias) {
139 4
                    if (isset($data[$fieldalias])) {
140 2
                        $data[$fieldname] = $data[$fieldalias];
141 2
                        unset($fieldalias);
142 2
                    }
143 21
                }
144 21
                BinderObject::bindObject($data, $instance);
145
146 21
                foreach ((array)$item->getFieldMap() as $property => $fieldmap) {
147 10
                    $selectMask = $fieldmap[Mapper::FIELDMAP_SELECTMASK];
148 10
                    $value = isset($data[$fieldmap[Mapper::FIELDMAP_FIELD]]) ? $data[$fieldmap[Mapper::FIELDMAP_FIELD]] : "";
149 10
                    $data[$property] = $selectMask($value, $instance);
150 21
                }
151 21
                if (count($item->getFieldMap()) > 0) {
152 10
                    BinderObject::bindObject($data, $instance);
153 10
                }
154 21
                $collection[] = $instance;
155 21
            }
156 21
            $result[] = count($collection) === 1 ? $collection[0] : $collection;
157 21
        }
158
159 21
        return $result;
160
    }
161
162
    /**
163
     * @param mixed $instance
164
     */
165 8
    public function save($instance)
166
    {
167
        // Get all fields
168 8
        $array = BinderObject::toArrayFrom($instance, true);
169
170
        // Mapping the data
171 8
        foreach ((array)$this->getMapper()->getFieldMap() as $property => $fieldmap) {
172 3
            $fieldname = $fieldmap[Mapper::FIELDMAP_FIELD];
173 3
            $updateMask = $fieldmap[Mapper::FIELDMAP_UPDATEMASK];
174
175
            // If no value for UpdateMask, remove from the list;
176 3
            if (empty($updateMask)) {
177 2
                unset($array[$property]);
178 2
                continue;
179
            }
180
181
            // Get the value from the mapped field name
182 3
            $value = $array[$property];
183 3
            unset($array[$property]);
184 3
            $array[$fieldname] = $updateMask($value, $instance);
185 8
        }
186
187
        // Prepare query to insert
188 8
        $updatable = Updatable::getInstance()
189 8
            ->table($this->mapper->getTable())
190 8
            ->fields(array_keys($array));
191
192
        // Check if is insert or update
193 8
        if (empty($array[$this->mapper->getPrimaryKey()]) || count($this->get($array[$this->mapper->getPrimaryKey()])) === 0)  {
194 5
            $array[$this->mapper->getPrimaryKey()] = $this->insert($updatable, $array);
195 5
            BinderObject::bindObject($array, $instance);
196 5
        } else {
197 3
            $this->update($updatable, $array);
198
        }
199 8
    }
200
201
    /**
202
     * @param \ByJG\MicroOrm\Updatable $updatable
203
     * @param array $params
204
     * @return int
205
     * @throws \Exception
206
     */
207 5
    protected function insert(Updatable $updatable, array $params)
208
    {
209 5
        $keyGen = $this->getMapper()->generateKey();
210 5
        if (empty($keyGen)) {
211 4
            return $this->insertWithAutoinc($updatable, $params);
212
        } else {
213 1
            return $this->insertWithKeyGen($updatable, $params, $keyGen);
214
        }
215
    }
216
217 4
    protected function insertWithAutoinc(Updatable $updatable, array $params)
218
    {
219 4
        $sql = $updatable->buildInsert($params, $this->getDbDriver()->getDbHelper());
220 4
        $dbFunctions = $this->getDbDriver()->getDbHelper();
221 4
        return $dbFunctions->executeAndGetInsertedId($this->getDbDriver(), $sql, $params);
222
    }
223
224 1
    protected function insertWithKeyGen(Updatable $updatable, array $params, $keyGen)
225
    {
226 1
        $params[$this->mapper->getPrimaryKey()] = $keyGen;
227 1
        $sql = $updatable->buildInsert($params, $this->getDbDriver()->getDbHelper());
228 1
        $this->getDbDriver()->execute($sql, $params);
229 1
        return $keyGen;
230
    }
231
232
    /**
233
     * @param \ByJG\MicroOrm\Updatable $updatable
234
     * @param array $params
235
     * @throws \Exception
236
     */
237 3
    protected function update(Updatable $updatable, array $params)
238
    {
239 3
        $params = array_merge($params, ['_id' => $params[$this->mapper->getPrimaryKey()]]);
240 3
        $updatable->where($this->mapper->getPrimaryKey() . ' = [[_id]] ', ['_id' => $params['_id']]);
241
242 3
        $sql = $updatable->buildUpdate($params, $this->getDbDriver()->getDbHelper());
243
244 3
        $this->getDbDriver()->execute($sql, $params);
245 3
    }
246
}
247