Completed
Push — master ( 04cbfe...3e8a03 )
by Dmitry
02:26
created

Repository::save()   C

Complexity

Conditions 9
Paths 15

Size

Total Lines 58
Code Lines 34

Duplication

Lines 3
Ratio 5.17 %

Code Coverage

Tests 36
CRAP Score 9.0015

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 3
loc 58
rs 6.9928
c 1
b 0
f 1
ccs 36
cts 37
cp 0.973
cc 9
eloc 34
nc 15
nop 1
crap 9.0015

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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->beforeCreate($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 remove($instance)
183
    {
184 64
        $key = $this->space->getInstanceKey($instance);
185
186 64
        if(!array_key_exists($key, $this->original)) {
187 64
            return;
188 64
        }
189 64
190 64
        if(array_key_exists($key, $this->persisted)) {
191 64
192 64
            unset($this->persisted[$key]);
193
194 64
            $pk = [];
195 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...
196 64
                $pk[] = $this->original[$key][$part[0]];
197 64
            }
198
            foreach($this->space->getMapper()->getPlugins() as $plugin) {
199 14
                $plugin->beforeRemove($instance, $this->space);
200
            }
201
202 64
            $this->space->getMapper()->getClient()
203 64
                ->getSpace($this->space->getId())
204
                ->delete($pk);
205 17
206
        }
207
208
        unset($this->original[$key]);
209
210
        $this->results = [];
211
    }
212 64
213
    public function save($instance)
214 64
    {
215
        $tuple = [];
216
217 6
        $size = count(get_object_vars($instance));
218
        $skipped = 0;
219 6
220 6
        foreach($this->space->getFormat() as $index => $info) {
221 6
            if(!property_exists($instance, $info['name'])) {
222
                $skipped++;
223 6
                $instance->{$info['name']} = null;
224 6
            }
225
226 1
            $instance->{$info['name']} = $this->space->getMapper()->getSchema()
227
                ->formatValue($info['type'], $instance->{$info['name']});
228 1
            $tuple[$index] = $instance->{$info['name']};
229 1
230 1
            if(count($tuple) == $size + $skipped) {
231
                break;
232 1
            }
233 1
        }
234
235 64
        $key = $this->space->getInstanceKey($instance);
236
        $client = $this->space->getMapper()->getClient();
237 64
238 64
        if(array_key_exists($key, $this->persisted)) {
239
            // update
240 64
            $update = array_diff_assoc($tuple, $this->original[$key]);
241
            if(!count($update)) {
242 64
                return $instance;
243 1
            }
244
245
            $operations = [];
246 64
            foreach($update as $index => $value) {
247 64
                $operations[] = ['=', $index, $value];
248 64
            }
249 64
250
            $pk = [];
251 19 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...
252 19
                $pk[] = $this->original[$key][$part[0]];
253 19
            }
254 19
255
            foreach($this->space->getMapper()->getPlugins() as $plugin) {
256
                $plugin->beforeCreate($instance, $this->space);
257 19
            }
258 19
259 4
            $client->getSpace($this->space->getId())->update($pk, $operations);
260 19
            $this->original[$key] = $tuple;
261 19
262
        } else {
263
            $client->getSpace($this->space->getId())->insert($tuple);
264
            $this->persisted[$key] = $instance;
265
            $this->original[$key] = $tuple;
266 19
        }
267 19
268 1
269 19
        $this->flushCache();
270
    }
271
272
    public function flushCache()
273 18
    {
274 18
        $this->cache = [];
275 18
    }
276
}
277