Completed
Push — master ( c32558...5e96b3 )
by Dmitry
02:04
created

Repository   C

Complexity

Total Complexity 59

Size/Duplication

Total Lines 297
Duplicated Lines 10.77 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 98.77%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 59
lcom 1
cbo 5
dl 32
loc 297
rs 6.1904
c 1
b 0
f 1
ccs 161
cts 163
cp 0.9877

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C create() 9 29 7
A findOne() 0 4 1
C find() 0 58 14
C getInstance() 12 30 7
A knows() 0 4 1
C update() 5 27 7
A truncate() 0 7 1
A remove() 0 14 4
B removeEntity() 3 30 5
C save() 3 63 10
A flushCache() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Repository often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Repository, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Tarantool\Mapper;
4
5
use Exception;
6
use SplObjectStorage;
7
8
class Repository
9
{
10
    private $space;
11
    private $persisted = [];
12
    private $original = [];
13
    private $keys;
14
15
    private $cache = [];
16
    private $results = [];
17
18
    public function __construct(Space $space)
19
    {
20
        $this->space = $space;
21
        $this->keys = new SplObjectStorage;
22
    }
23 64
24
    public function create($data)
25 64
    {
26 64
        $class = Entity::class;
27 View Code Duplication
        foreach($this->space->getMapper()->getPlugins() as $plugin) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
28 64
            $entityClass = $plugin->getEntityClass($this->space);
29
            if($entityClass) {
30 64
                if($class != Entity::class) {
31 64
                    throw new Exception('Entity class override');
32
                }
33
                $class = $entityClass;
34 64
            }
35 2
        }
36
        $instance = new $class();
37
        foreach($this->space->getFormat() as $row) {
38 64
            if(array_key_exists($row['name'], $data)) {
39 64
                $instance->{$row['name']} = $data[$row['name']];
40 64
            }
41 64
        }
42 4
43 4
        foreach($this->space->getMapper()->getPlugins() as $plugin) {
44
            $plugin->generateKey($instance, $this->space);
45 64
        }
46 64
47 64
        // validate instance key
48 64
        $key = $this->space->getInstanceKey($instance);
49
50
        $this->keys[$instance] = $key;
51 64
        return $instance;
52 64
    }
53
54 1
    public function findOne($params = [])
55
    {
56
        return $this->find($params, true);
57
    }
58 64
59 2
    public function find($params = [], $one = false)
60 2
    {
61
        $cacheIndex = array_search([$params, $one], $this->cache);
62 64
        if($cacheIndex !== false) {
63
            return $this->results[$cacheIndex];
64 64
        }
65 64
66 64
        if(!is_array($params)) {
67 64
            $params = [$params];
68 64
        }
69
        if(count($params) == 1 && array_key_exists(0, $params)) {
70
            $primary = $this->space->getPrimaryIndex();
71
            if(count($primary->parts) == 1) {
72 64
                $formatted = $this->space->getMapper()->getSchema()->formatValue($primary->parts[0][1], $params[0]);
73
                if($params[0] == $formatted) {
74 64
                    $params = [
75
                        $this->space->getFormat()[$primary->parts[0][0]]['name'] => $params[0]
76
                    ];
77 64
                }
78
            }
79 64
        }
80
81 64
        if(array_key_exists('id', $params)) {
82
            if(array_key_exists($params['id'], $this->persisted)) {
83
                $instance = $this->persisted[$params['id']];
84 64
                return $one ? $instance : [$instance];
85
            }
86 64
        }
87 64
88 64
89 64
        $index = $this->space->castIndex($params);
90
        if(is_null($index)) {
91 64
            throw new Exception("No index for params ".json_encode($params));
92
        }
93
94
        $cacheIndex = count($this->cache);
95 1
        $this->cache[] = [$params, $one];
96
97
        $client = $this->space->getMapper()->getClient();
98 19
        $values = $this->space->getIndexValues($index, $params);
99
100 19
        $data = $client->getSpace($this->space->getId())->select($values, $index)->getData();
101
102
        $result = [];
103 64
        foreach($data as $tuple) {
0 ignored issues
show
Bug introduced by
The expression $data of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
104
            $instance = $this->getInstance($tuple);
105 64
            if($one) {
106
                return $this->results[$cacheIndex] = $instance;
107 64
            }
108 1
            $result[] = $instance;
109
        }
110
111 64
        if($one) {
112 10
            return $this->results[$cacheIndex] = null;
113 3
        }
114
115
        return $this->results[$cacheIndex] = $result;
116 7
    }
117
118 7
    private function getInstance($tuple)
119
    {
120
        $key = $this->space->getTupleKey($tuple);
121 64
122 2
        if(array_key_exists($key, $this->persisted)) {
123
            return $this->persisted[$key];
124
        }
125 64
126 64
        $class = Entity::class;
127 View Code Duplication
        foreach($this->space->getMapper()->getPlugins() as $plugin) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128 64
            $entityClass = $plugin->getEntityClass($this->space);
129 64
            if($entityClass) {
130 18
                if($class != Entity::class) {
131 64
                    throw new Exception('Entity class override');
132
                }
133
                $class = $entityClass;
134
            }
135 64
        }
136 1
        $instance = new $class();
137
138
        $this->original[$key] = $tuple;
139 64
140 64 View Code Duplication
        foreach($this->space->getFormat() as $index => $info) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141 2
            $instance->{$info['name']} = array_key_exists($index, $tuple) ? $tuple[$index] : null;
142 2
        }
143
144 64
        $this->keys->offsetSet($instance, $key);
145 64
146
        return $this->persisted[$key] = $instance;
147 1
    }
148 64
149
    public function knows($instance)
150
    {
151
        return $this->keys->offsetExists($instance);
152
    }
153 64
154 64
    public function update(Entity $instance, $operations)
155 64
    {
156
        if(!count($operations)) {
157
            return;
158 64
        }
159 64
160 2
        $tupleOperations = [];
161
        foreach($operations as $operation) {
162
            $tupleIndex = $this->space->getPropertyIndex($operation[1]);
163 64
            $tupleOperations[] = [$operation[0], $tupleIndex, $operation[2]];
164
        }
165 64
166 1
        $pk = [];
167 1
        foreach($this->space->getPrimaryIndex()->parts as $part) {
168 1
            $pk[] = $instance->{$this->space->getFormat()[$part[0]]['name']};
169 1
        }
170 1
171
        $client = $this->space->getMapper()->getClient();
172
        $result = $client->getSpace($this->space->getId())->update($pk, $tupleOperations);
173 1
        foreach($result->getData() as $tuple) {
174 View Code Duplication
            foreach($this->space->getFormat() as $index => $info) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
175
                if(array_key_exists($index, $tuple)) {
176 1
                    $instance->{$info['name']} = $tuple[$index];
177
                }
178 1
            }
179 1
        }
180
    }
181 1
182
    public function truncate()
183
    {
184 64
        $this->cache = [];
185
        $this->results = [];
186 64
        $id = $this->space->getId();
187 64
        $this->space->getMapper()->getClient()->evaluate("box.space[$id]:truncate()");
188 64
    }
189 64
190 64
    public function remove($params = [])
191 64
    {
192 64
        if($params instanceof Entity) {
193
            return $this->removeEntity($params);
194 64
        }
195
196 64
        if(!count($params)) {
197 64
            throw new Exception("Use truncate to flush space");
198
        }
199 14
200
        foreach($this->find($params) as $entity) {
201
            $this->removeEntity($entity);
202 64
        }
203 64
    }
204
205 17
    public function removeEntity(Entity $instance)
206
    {
207
        $key = $this->space->getInstanceKey($instance);
208
209
        if(!array_key_exists($key, $this->original)) {
210
            return;
211
        }
212 64
213
        if(array_key_exists($key, $this->persisted)) {
214 64
215
            unset($this->persisted[$key]);
216
217 6
            $pk = [];
218 View Code Duplication
            foreach($this->space->getPrimaryIndex()->parts as $part) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
219 6
                $pk[] = $this->original[$key][$part[0]];
220 6
            }
221 6
            foreach($this->space->getMapper()->getPlugins() as $plugin) {
222
                $plugin->beforeRemove($instance, $this->space);
223 6
            }
224 6
225
            $this->space->getMapper()->getClient()
226 1
                ->getSpace($this->space->getId())
227
                ->delete($pk);
228 1
        }
229 1
230 1
        unset($this->original[$key]);
231
232 1
        $this->results = [];
233 1
        $this->cache = [];
234
    }
235 64
236
    public function save($instance)
237 64
    {
238 64
        $tuple = [];
239
240 64
        $size = count(get_object_vars($instance));
241
        $skipped = 0;
242 64
243 1
        foreach($this->space->getFormat() as $index => $info) {
244
            if(!property_exists($instance, $info['name'])) {
245
                $skipped++;
246 64
                $instance->{$info['name']} = null;
247 64
            }
248 64
249 64
            $instance->{$info['name']} = $this->space->getMapper()->getSchema()
250
                ->formatValue($info['type'], $instance->{$info['name']});
251 19
            $tuple[$index] = $instance->{$info['name']};
252 19
253 19
            if(count($tuple) == $size + $skipped) {
254 19
                break;
255
            }
256
        }
257 19
258 19
        $key = $this->space->getInstanceKey($instance);
259 4
        $client = $this->space->getMapper()->getClient();
260 19
261 19
        if(array_key_exists($key, $this->persisted)) {
262
            // update
263
            $update = array_diff_assoc($tuple, $this->original[$key]);
264
            if(!count($update)) {
265
                return $instance;
266 19
            }
267 19
268 1
            $operations = [];
269 19
            foreach($update as $index => $value) {
270
                $operations[] = ['=', $index, $value];
271
            }
272
273 18
            $pk = [];
274 18 View Code Duplication
            foreach($this->space->getPrimaryIndex()->parts as $part) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
275 18
                $pk[] = $this->original[$key][$part[0]];
276 18
            }
277
278
            foreach($this->space->getMapper()->getPlugins() as $plugin) {
279 18
                $plugin->beforeUpdate($instance, $this->space);
280 17
            }
281 17
282 17
            $client->getSpace($this->space->getId())->update($pk, $operations);
283 1
            $this->original[$key] = $tuple;
284 1
285 1
        } else {
286 1
287
            foreach($this->space->getMapper()->getPlugins() as $plugin) {
288 18
                $plugin->beforeCreate($instance, $this->space);
289
            }
290
291
            $client->getSpace($this->space->getId())->insert($tuple);
292 64
            $this->persisted[$key] = $instance;
293
            $this->original[$key] = $tuple;
294 64
        }
295
296
297 64
        $this->flushCache();
298
    }
299 64
300 64
    public function flushCache()
301
    {
302 64
        $this->cache = [];
303 64
    }
304
}
305