Completed
Push — master ( 475d79...a4fb4c )
by Dmitry
03:20
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 LogicException;
7
8
class Repository implements Contracts\Repository
9
{
10
    private $type;
11
    private $entities = [];
12
    private $keyMap = [];
13
    private $findCache = [];
14
15
    private $magicMethodRules = [
16
        'by' => false,
17
        'firstBy' => true,
18
        'oneBy' => true,
19
    ];
20
21 27
    public function __construct(Contracts\Type $type)
22
    {
23 27
        $this->type = $type;
24 27
    }
25
26 27
    public function create($data = null)
27
    {
28 27
        if ($data && !is_array($data)) {
29 27
            $properties = $this->getType()->getProperties();
30 27
            if (count($properties) == 2) {
31 27
                $data = [$properties[1] => $data];
32
            } else {
33 1
                throw new LogicException('Data should be array');
34
            }
35
        }
36 27
        if ($data) {
37 27
            $newData = [];
38 27
            foreach ($data as $k => $v) {
39 27
                if (!is_numeric($k)) {
40 27
                    $newData[$k] = $v;
41 View Code Duplication
                } else {
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...
42 4
                    if ($v instanceof Contracts\Entity) {
43 3
                        $type = $this->type->getManager()->findRepository($v)->getType();
44 27
                        $newData[$this->type->getReferenceProperty($type)] = $v->getId();
45
                    }
46
                }
47
            }
48 27
            $data = $newData;
49
        }
50
51 27
        foreach ($data as $k => $v) {
52 27
            if (!$this->type->hasProperty($k)) {
53 27
                throw new \Exception("Unknown property $k");
54
            }
55
        }
56
57 27
        return $this->register(new Entity($data));
58
    }
59
60 27
    public function __call($method, $arguments)
61
    {
62 27
        foreach ($this->magicMethodRules as $prefix => $oneItem) {
63 27
            if (substr($method, 0, strlen($prefix)) == $prefix) {
64 27
                $tail = substr($method, strlen($prefix));
65 27
                $fields = array_map('strtolower', explode('And', $tail));
66
67 27
                return $this->find(array_combine($fields, $arguments), $oneItem);
68
            }
69
        }
70
71 1
        throw new BadMethodCallException("Method $method not found");
72
    }
73
74 5
    public function findOne($params)
75
    {
76 5
        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 76 which is incompatible with the return type declared by the interface Tarantool\Mapper\Contracts\Repository::findOne of type Tarantool\Mapper\Contracts\Entity.
Loading history...
77
    }
78
79 27
    public function find($params = [], $oneItem = false)
80
    {
81 27
        $query = [];
82
83 27
        if (is_string($params) && 1 * $params == $params) {
84 1
            $params = 1 * $params;
85
        }
86
87 27
        if (is_int($params)) {
88 6
            if (isset($this->keyMap[$params])) {
89 1
                return $this->entities[$this->keyMap[$params]];
90
            }
91
            $query = [
92 5
                'id' => $params,
93
            ];
94 5
            $oneItem = true;
95
        }
96
97 27
        if ($params instanceof Contracts\Entity) {
98 1
            $params = [$params];
99
        }
100
101 27
        if (is_array($params)) {
102 27
            foreach ($params as $key => $value) {
103 27 View Code Duplication
                if (is_numeric($key) && $value instanceof Contracts\Entity) {
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...
104 1
                    $type = $this->type->getManager()->findRepository($value)->getType();
105 1
                    $key = $this->type->getReferenceProperty($type);
106
                }
107 27
                if ($this->type->hasProperty($key)) {
108 27
                    $query[$key] = $this->type->encodeProperty($key, $value);
109
                }
110
            }
111
        }
112
113 27
        $findKey = md5(json_encode($query));
114 27
        if (array_key_exists($findKey, $this->findCache)) {
115 27
            return $this->findCache[$findKey];
116
        }
117
118 27
        $index = $this->type->findIndex(array_keys($query));
119 27
        $values = count($query) ? $this->type->getIndexTuple($index, $query) : [];
120
121 27
        $data = $this->type->getSpace()->select($values, $index);
122
123 27
        $result = [];
124 27
        if (!empty($data->getData())) {
125 27
            foreach ($data->getData() as $tuple) {
126 27
                $data = $this->type->fromTuple($tuple);
127 27
                if (isset($data['id']) && array_key_exists($data['id'], $this->keyMap)) {
128 27
                    $entity = $this->entities[$this->keyMap[$data['id']]];
129 27
                    $entity->update($data);
130
                } else {
131 27
                    $entity = new Entity($data);
132 27
                    $this->register($entity);
133
                }
134 27
                if ($oneItem) {
135 27
                    return $this->findCache[$findKey] = $entity;
136
                }
137 5
                $result[] = $entity;
138
            }
139
        }
140 27
        if (!$oneItem) {
141 5
            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...
142
        }
143 27
    }
144
145
    /**
146
     * @return Entity
147
     */
148 27
    public function knows(Contracts\Entity $entity)
149
    {
150 27
        return in_array($entity, $this->entities);
151
    }
152
153 1
    public function remove(Contracts\Entity $entity)
154
    {
155 1
        unset($this->entities[$this->keyMap[$entity->id]]);
156 1
        unset($this->keyMap[$entity->id]);
157
158 1
        $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...
159 1
    }
160
161 27
    public function save(Contracts\Entity $entity)
162
    {
163 27
        if (!$this->knows($entity)) {
164 1
            throw new LogicException('Entity is not related with this repository');
165
        }
166
167 27
        if (!$entity->getId()) {
168 27
            $this->generateId($entity);
169 27
            $tuple = $this->type->getTuple($entity->toArray());
170
171 27
            $required = $this->type->getRequiredProperties();
172
173 27
            foreach ($this->type->getProperties() as $index => $field) {
174 27
                if (in_array($field, $required) && !array_key_exists($index, $tuple)) {
175 1
                    if ($this->type->isReference($field)) {
176 1
                        $tuple[$index] = 0;
177
                    } else {
178 27
                        $tuple[$index] = '';
179
                    }
180
                }
181
            }
182
183
            // normalize tuple
184 27
            if (array_values($tuple) != $tuple) {
185
                // index was skipped
186 1
                $max = max(array_keys($tuple));
187 1
                foreach (range(0, $max) as $index) {
188 1
                    if (!array_key_exists($index, $tuple)) {
189 1
                        $tuple[$index] = null;
190
                    }
191
                }
192 1
                ksort($tuple);
193
            }
194
195 27
            $this->type->getSpace()->insert($tuple);
196
        } else {
197 5
            $changes = $entity->pullChanges();
198 5
            if (count($changes)) {
199 5
                $operations = [];
200 5
                foreach ($this->type->getTuple($changes) as $key => $value) {
201 5
                    $operations[] = ['=', $key, $value];
202
                }
203
204 5
                $this->type->getSpace()->update($entity->getId(), $operations);
205
            }
206
        }
207
208 27
        return $entity;
209
    }
210
211 27
    private function register(Contracts\Entity $entity)
212
    {
213 27
        if (!$this->knows($entity)) {
214 27
            $this->entities[] = $entity;
215
        }
216 27
        if ($entity->getId() && !array_key_exists($entity->getId(), $this->keyMap)) {
217 27
            $this->keyMap[$entity->getId()] = array_search($entity, $this->entities);
218
        }
219
220 27
        return $entity;
221
    }
222
223 27
    private function generateId(Contracts\Entity $entity)
224
    {
225 27
        $manager = $this->type->getManager();
226 27
        $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...
227 27
        $spaceId = $this->type->getSpaceId();
228
229 27
        $sequence = $manager->get('sequence')->oneBySpace($spaceId);
230 27
        if (!$sequence) {
231 27
            $sequence = $manager->get('sequence')->create([
232 27
                'space' => $spaceId,
233 27
                'value' => 0,
234
            ]);
235 27
            $manager->save($sequence);
236
        }
237
238 27
        $nextValue = +$manager->getMeta()
239 27
            ->get('sequence')
240 27
            ->getSpace()
241 27
            ->update($sequence->id, [['+', 2, 1]])
242 27
            ->getData()[0][2];
243
244 27
        $entity->setId($nextValue);
245
246 27
        $this->register($entity);
247
248 27
        return $entity;
249
    }
250
251 27
    public function getType()
252
    {
253 27
        return $this->type;
254
    }
255
}
256