Completed
Push — master ( 9e245f...198c9a )
by Dmitry
03:07
created

Repository::save()   C

Complexity

Conditions 12
Paths 5

Size

Total Lines 49
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 12

Importance

Changes 10
Bugs 2 Features 1
Metric Value
c 10
b 2
f 1
dl 0
loc 49
ccs 26
cts 26
cp 1
rs 5.1474
cc 12
eloc 28
nc 5
nop 1
crap 12

How to fix   Complexity   

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