Completed
Push — master ( 2f89bf...8773a6 )
by Dmitry
05:59 queued 02:54
created

Repository::findOne()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Tarantool\Mapper;
4
5
use BadMethodCallException;
6
use Exception;
7
use LogicException;
8
9
class Repository implements Contracts\Repository
10
{
11
    private $type;
12
    private $entities = [];
13
    private $keyMap = [];
14
    private $findCache = [];
15
    private $original = [];
16
17
    private $magicMethodRules = [
18
        'by' => false,
19
        'firstBy' => true,
20
        'oneBy' => true,
21
    ];
22
23 60
    public function __construct(Contracts\Type $type)
24
    {
25 60
        $this->type = $type;
26 60
    }
27
28 60
    public function create($params = null)
29
    {
30 60
        if ($params && !is_array($params)) {
31 60
            $params = [$params];
32 60
        }
33
34 60
        if (!is_array($params)) {
35 1
            $params = [];
36 1
        }
37
38 60
        $data = [];
39 60
        foreach ($params as $k => $v) {
40 60
            if (is_numeric($k)) {
41 60
                if ($v instanceof Contracts\Entity) {
42 4
                    $type = $this->type->getManager()->findRepository($v)->getType();
43 4
                    $k = $this->type->getReferenceProperty($type);
44 2
                } else {
45 60
                    $primitive = [];
46 60
                    foreach ($this->type->getProperties() as $property) {
47 60
                        if (!$this->type->isReference($property)) {
48 60
                            $primitive[] = $property;
49 60
                        }
50 60
                    }
51 60
                    if (count($primitive) == 2) {
52 60
                        $k = $primitive[1];
53 60
                    } else {
54 1
                        throw new Exception("Can't calculate key name");
55
                    }
56
                }
57 60
            }
58 60 View Code Duplication
            if (!$this->type->hasProperty($k)) {
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...
59 2
                $name = $this->type->getName();
60 2
                throw new Exception("Unknown property $name.$k");
61
            }
62 60
            $data[$k] = $this->type->encodeProperty($k, $v);
63 60
        }
64 60
        foreach ($this->type->getRequiredProperties() as $property) {
65 60
            if (!array_key_exists($property, $data)) {
66 60
                $convention = $this->type->getManager()->getMeta()->getConvention();
67 60
                $propertyType = $this->type->getPropertyType($property);
68 60
                $data[$property] = $convention->getDefaultValue($propertyType);
69 60
            }
70 60
        }
71
72 60
        $this->flushCache();
73
74 60
        return $this->createInstance($data);
75
    }
76
77 60
    private function createInstance($data)
78
    {
79 60
        $class = $this->getType()->getEntityClass();
80
81 60
        return $this->register(new $class($data));
82
    }
83
84 60
    public function __call($method, $arguments)
85
    {
86 60
        foreach ($this->magicMethodRules as $prefix => $oneItem) {
87 60
            if (substr($method, 0, strlen($prefix)) == $prefix) {
88 60
                $tail = substr($method, strlen($prefix));
89 60
                $fields = array_map('strtolower', explode('And', $tail));
90
91 60
                return $this->find(array_combine($fields, $arguments), $oneItem);
92
            }
93 60
        }
94
95 1
        throw new BadMethodCallException("Method $method not found");
96
    }
97
98 17
    public function findOne($params)
99
    {
100 17
        return $this->find($params, true);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->find($params, true); of type Tarantool\Mapper\Contrac...pper\Contracts\Entity[] adds the type Tarantool\Mapper\Contracts\Entity[] to the return on line 100 which is incompatible with the return type declared by the interface Tarantool\Mapper\Contracts\Repository::findOne of type Tarantool\Mapper\Contracts\Entity.
Loading history...
101
    }
102
103 60
    public function find($params = [], $oneItem = false)
104
    {
105 60
        $query = [];
106
107 60
        if (is_string($params) && 1 * $params == $params) {
108 1
            $params = 1 * $params;
109 1
        }
110
111 60
        if (is_int($params)) {
112 10
            if (isset($this->keyMap[$params])) {
113 3
                return $this->entities[$this->keyMap[$params]];
114
            }
115
            $query = [
116 7
                'id' => $params,
117 7
            ];
118 7
            $oneItem = true;
119 7
        }
120
121 60
        if ($params instanceof Contracts\Entity) {
122 2
            $params = [$params];
123 2
        }
124
125 60
        if (is_array($params)) {
126 60
            foreach ($params as $key => $value) {
127 60
                if (is_numeric($key) && $value instanceof Contracts\Entity) {
128 2
                    $type = $this->type->getManager()->findRepository($value)->getType();
129 2
                    $key = $this->type->getReferenceProperty($type);
130 2
                }
131 60
                if ($this->type->hasProperty($key)) {
132 60
                    $query[$key] = $this->type->encodeProperty($key, $value);
133 60
                } else {
134 1
                    $name = $this->getType()->getName();
135 1
                    throw new Exception("Unknown property $name.$key");
136
                }
137 60
            }
138 60
        }
139
140 60
        $findKey = md5(json_encode($query).($oneItem ? 'x' : ''));
141 60
        if (array_key_exists($findKey, $this->findCache)) {
142 60
            return $this->findCache[$findKey];
143
        }
144
145 60
        $index = $this->type->findIndex(array_keys($query));
146 60
        if (!is_numeric($index)) {
147 2
            throw new Exception('No index found for '.json_encode(array_keys($query)));
148
        }
149
150 60
        $values = count($query) ? $this->type->getIndexTuple($index, $query) : [];
151 60
        $data = $this->type->getSpace()->select($values, $index);
152
153 60
        $result = [];
154 60
        if (!empty($data->getData())) {
155 60
            foreach ($data->getData() as $tuple) {
156 60
                $data = $this->type->fromTuple($tuple);
157 60 View Code Duplication
                if (isset($data['id']) && array_key_exists($data['id'], $this->keyMap)) {
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...
158 60
                    $entity = $this->entities[$this->keyMap[$data['id']]];
159 60
                    $entity->update($data);
160 60
                } else {
161 60
                    $entity = $this->createInstance($data);
162
                }
163 60
                if ($oneItem) {
164 60
                    return $this->findCache[$findKey] = $entity;
165
                }
166 13
                $result[] = $entity;
167 13
            }
168 13
        }
169 60
        if (!$oneItem) {
170 16
            return $this->findCache[$findKey] = $result;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->findCache[$findKey] = $result; (array) is incompatible with the return type declared by the interface Tarantool\Mapper\Contracts\Repository::find of type Tarantool\Mapper\Contrac...pper\Contracts\Entity[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
171
        }
172 60
    }
173
174
    /**
175
     * @return Entity
176
     */
177 60
    public function knows(Contracts\Entity $entity)
178
    {
179 60
        return in_array($entity, $this->entities);
180
    }
181
182 7
    public function remove(Contracts\Entity $entity)
183
    {
184 7
        unset($this->entities[$this->keyMap[$entity->id]]);
185 7
        unset($this->keyMap[$entity->id]);
186 7
        $this->flushCache();
187
188 7
        $this->type->getSpace()->delete([$entity->id]);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Tarantool\Mapper\Contracts\Entity suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
189 7
    }
190
191 1
    public function removeAll()
192
    {
193 1
        foreach ($this->find([]) as $entity) {
0 ignored issues
show
Bug introduced by
The expression $this->find(array()) of type object<Tarantool\Mapper\...pper\Contracts\Entity>> 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...
194 1
            $this->remove($entity);
195 1
        }
196 1
        $this->flushCache();
197 1
    }
198
199 60
    public function flushCache()
200
    {
201 60
        $this->findCache = [];
202 60
    }
203
204 60
    public function save(Contracts\Entity $entity)
205
    {
206 60
        if (!$this->knows($entity)) {
207 1
            throw new LogicException('Entity is not related with this repository');
208
        }
209
210 60
        if (!$entity->getId()) {
211 60
            $this->generateId($entity);
212 60
            $tuple = $this->type->getCompleteTuple($entity->toArray());
213 60
            $this->type->getSpace()->insert($tuple);
214 60
        } else {
215 17
            $array = $entity->toArray(false);
216 17
            $changes = [];
217 17
            $id = $entity->getId();
218 17
            if (!array_key_exists($id, $this->original)) {
219
                $changes = $array;
220
            } else {
221 17
                foreach ($array as $k => $v) {
222 17
                    if (!array_key_exists($k, $this->original[$id])) {
223 3
                        $changes[$k] = $v;
224 17
                    } elseif ($v !== $this->original[$id][$k]) {
225 14
                        $changes[$k] = $v;
226 14
                    }
227 17
                }
228
            }
229
230 17
            foreach ($changes as $k => $v) {
231 17 View Code Duplication
                if (!$this->type->hasProperty($k)) {
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...
232 1
                    $name = $this->type->getName();
233 1
                    throw new Exception("Unknown property $name.$k");
234
                }
235 16
            }
236
237 16
            if (count($changes)) {
238 16
                $operations = [];
239 16
                foreach ($this->type->getTuple($changes) as $key => $value) {
240 16
                    $operations[] = ['=', $key, $value];
241 16
                }
242
                try {
243 16
                    $result = $this->type->getSpace()->update($id, $operations);
244 15
                    $current = $this->type->fromTuple($result->getData()[0]);
245 15
                    $this->original[$id] = $current;
246 15
                    $entity->update($current);
247 16
                } catch (Exception $e) {
248 1
                    $this->type->getSpace()->delete([$id]);
249 1
                    $tuple = $this->type->getCompleteTuple($entity->toArray());
250 1
                    $this->type->getSpace()->insert($tuple);
251
                }
252 16
                $this->original[$id] = $entity->toArray();
253 16
            }
254
        }
255
256 60
        $this->flushCache();
257
258 60
        return $entity;
259
    }
260
261 60
    private function register(Contracts\Entity $entity)
262
    {
263 60
        if (!$this->knows($entity)) {
264 60
            $this->entities[] = $entity;
265 60
        }
266 60
        if ($entity->getId() && !array_key_exists($entity->getId(), $this->keyMap)) {
267 60
            $this->keyMap[$entity->getId()] = array_search($entity, $this->entities);
268 60
        }
269
270 60
        if ($entity->getId()) {
271 60
            $this->original[$entity->getId()] = $entity->toArray();
272 60
        }
273
274 60
        return $entity;
275
    }
276
277 60
    private function generateId(Contracts\Entity $entity)
278
    {
279 60
        $manager = $this->type->getManager();
280 60
        $name = $this->type->getName();
0 ignored issues
show
Unused Code introduced by
$name is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
281 60
        $spaceId = $this->type->getSpaceId();
282
283 60
        $sequence = $manager->get('sequence')->oneBySpace($spaceId);
284 60
        if (!$sequence) {
285 60
            $sequence = $manager->get('sequence')->create([
286 60
                'space' => $spaceId,
287 60
                'value' => 0,
288 60
            ]);
289 60
            $manager->save($sequence);
290 60
        }
291
292 60
        $nextValue = +$manager->getMeta()
293 60
            ->get('sequence')
294 60
            ->getSpace()
295 60
            ->update($sequence->id, [['+', 2, 1]])
296 60
            ->getData()[0][2];
297
298 60
        $entity->setId($nextValue);
299
300 60
        $this->register($entity);
301
302 60
        return $entity;
303
    }
304
305 60
    public function getType()
306
    {
307 60
        return $this->type;
308
    }
309
310 2
    public function evaluate($query)
311
    {
312 2
        $result = [];
313 2
        $tuples = $this->type->getManager()->getClient()->evaluate($query)->getData()[0];
314 2
        foreach ($tuples as $tuple) {
315 1
            $data = $this->type->fromTuple($tuple);
316 1 View Code Duplication
            if (isset($data['id']) && array_key_exists($data['id'], $this->keyMap)) {
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...
317 1
                $entity = $this->entities[$this->keyMap[$data['id']]];
318 1
                $entity->update($data);
319 1
            } else {
320
                $entity = $this->createInstance($data);
321
            }
322 1
            $result[] = $entity;
323 2
        }
324
325 2
        return $result;
326
    }
327
}
328