Completed
Branch master (eb6d5f)
by Dmitry
02:18
created

Repository::create()   D

Complexity

Conditions 10
Paths 13

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 33
ccs 26
cts 26
cp 1
rs 4.8196
cc 10
eloc 21
nc 13
nop 1
crap 10

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