Completed
Push — master ( 5ae7b2...20e1fc )
by Ivan
02:21
created

Mapper.php$0 ➔ flatten()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
crap 2
1
<?php
2
namespace vakata\database\schema;
3
4
use vakata\collection\Collection;
5
use vakata\database\DBInterface;
6
7
class Mapper
8
{
9
    protected $db;
10
    protected $objects;
11
12 2
    public function __construct(DBInterface $db)
13
    {
14 2
        $this->db = $db;
15 2
    }
16 12
    public function entity($definition, array $data, bool $empty = false)
17
    {
18 12
        if (!$empty) {
19 12
            $primary = [];
20 12
            foreach ($definition->getPrimaryKey() as $column) {
21 12
                $primary[$column] = $data[$column];
22
            }
23 12
            if (isset($this->objects[$definition->getName()][base64_encode(serialize($primary))])) {
24 12
                return $this->objects[$definition->getName()][base64_encode(serialize($primary))];
25
            }
26
        }
27
        $entity = new class ($this, $definition, $data, $empty) extends \StdClass {
0 ignored issues
show
Unused Code introduced by
The call to anonymous//src/schema/Mapper.php$0::__construct() has too many arguments starting with $empty.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
28
            protected $mapper;
29
            protected $empty;
30
            protected $definition;
31
            protected $initial = [];
32
            protected $changed = [];
33
            protected $fetched = [];
34
35 6
            public function __construct($mapper, $definition, array $data = [])
36
            {
37 6
                $this->mapper = $mapper;
38 6
                $this->definition = $definition;
39 6
                $this->initial = $data;
40 6
            }
41 6
            public function __lazyProperty(string $property, callable $resolve)
42
            {
43 6
                $this->fetched[$property] = $resolve;
44 6
                return $this;
45
            }
46 12
            public function __get($property)
47
            {
48 12
                if (isset($this->changed[$property])) {
49
                    return $this->changed[$property];
50
                }
51 12
                if (isset($this->initial[$property])) {
52 12
                    return $this->initial[$property];
53
                }
54 6
                if (isset($this->fetched[$property])) {
55 6
                    return is_callable($this->fetched[$property]) ?
56 2
                        $this->fetched[$property] = call_user_func($this->fetched[$property]) :
57 6
                        $this->fetched[$property];
58
                }
59
                return null;
60
            }
61
            public function __set($property, $value)
62
            {
63
                $this->changed[$property] = $value;
64
            }
65
            public function __call($method, $args)
66
            {
67
                if (isset($this->definition->getRelations()[$method])) {
68
                    if (isset($this->fetched[$method])) {
69
                        return is_callable($this->fetched[$method]) ?
70
                            $this->fetched[$method] = call_user_func($this->fetched[$method], $args[0] ?? null) :
71
                            $this->fetched[$method];
72
                    }
73
                }
74
                return null;
75
            }
76 6
            public function definition()
77
            {
78 6
                return $this->definition;
79
            }
80 6
            public function toArray(bool $fetch = false)
81
            {
82 6
                $data = [];
83 6
                foreach ($this->definition->getColumns() as $k) {
84 6
                    if (isset($this->fetched[$k])) {
85
                        if ($fetch) {
86
                            $this->fetched[$k] = call_user_func($this->fetched[$k]);
87
                        }
88
                        if (!is_callable($this->fetched[$k])) {
89
                            $data[$k] = $this->fetched[$k];
90
                        }
91
                    }
92 6
                    if (isset($this->initial[$k])) {
93 6
                        $data[$k] = $this->initial[$k];
94
                    }
95 6
                    if (isset($this->changed[$k])) {
96 6
                        $data[$k] = $this->changed[$k];
97
                    }
98
                }
99 6
                return $data;
100
            }
101
            public function fromArray(array $data)
102
            {
103
                foreach ($this->definition->getColumns() as $k) {
104
                    if (isset($data[$k])) {
105
                        $this->changed[$k] = $data[$k];
106
                    }
107
                }
108
                return $this;
109
            }
110 6
            public function id()
111
            {
112 6
                $primary = [];
113 6
                foreach ($this->definition->getPrimaryKey() as $k) {
114 6
                    $primary[$k] = $this->initial[$k] ?? null;
115
                }
116 6
                return $primary;
117
            }
118
            public function save()
119
            {
120
                $this->mapper->save($this);
121
                return $this->flatten();
122
            }
123
            public function delete()
124
            {
125
                $this->mapper->delete($this);
126
            }
127
            public function refresh()
128
            {
129
                $this->mapper->refresh($this);
130
                return $this->flatten();
131
            }
132
            public function flatten()
133
            {
134
                $this->initial = $this->toArray();
135
                $this->changed = [];
136
                return $this;
137
            }
138
        };
139 6
        if ($empty) {
140
            return $entity;
141
        }
142 6
        $this->lazy($entity);
143 6
        return $this->objects[$definition->getName()][base64_encode(serialize($primary))] = $entity;
0 ignored issues
show
Bug introduced by
The variable $primary does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
144
    }
145 12
    public function collection($iterator, $definition)
146
    {
147 12
        return Collection::from($iterator)
148 12
            ->map(function ($v) use ($definition) {
149 12
                return $this->entity($definition, $v);
150 12
            });
151
    }
152
    public function save($entity)
153
    {
154
        $query = $this->db->table($entity->definition()->getName());
155
        $primary = $entity->id();
156
        if (!isset($this->objects[$entity->definition()->getName()][base64_encode(serialize($primary))])) {
157
            $new = $query->insert($entity->toArray());
158
            $entity->fromArray($new);
159
            $this->objects[$entity->definition()->getName()][base64_encode(serialize($new))] = $entity;
160
        } else {
161
            foreach ($primary as $k => $v) {
162
                $query->filter($k, $v);
163
            }
164
            $query->update($entity->toArray());
165
            $new = [];
166
            foreach ($primary as $k => $v) {
167
                $new[$k] = $entity->{$k};
168
            }
169
            if (base64_encode(serialize($new)) !== base64_encode(serialize($primary))) {
170
                unset($this->objects[$entity->definition()->getName()][base64_encode(serialize($primary))]);
171
                $this->objects[$entity->definition()->getName()][base64_encode(serialize($new))] = $entity;
172
            }
173
        }
174
        return $this->lazy($entity);
175
    }
176
    public function delete($entity)
177
    {
178
        $query = $this->db->table($entity->definition()->getName());
179
        $primary = $entity->id();
180
        if (isset($this->objects[$entity->definition()->getName()][base64_encode(serialize($primary))])) {
181
            foreach ($primary as $k => $v) {
182
                $query->filter($k, $v);
183
            }
184
            $query->delete();
185
            unset($this->objects[$entity->definition()->getName()][base64_encode(serialize($primary))]);
186
        }
187
    }
188
    public function refresh($entity, $own = true)
0 ignored issues
show
Unused Code introduced by
The parameter $own is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
189
    {
190
        $query = $this->db->table($entity->definition()->getName());
191
        $primary = $entity->id();
192
        foreach ($primary as $k => $v) {
193
            $query->filter($k, $v);
194
        }
195
        $entity->fromArray($query[0] ?? []);
196
        return $this->lazy($entity);
197
    }
198 6
    protected function lazy($entity)
199
    {
200 6
        $data = $entity->toArray();
201 6
        $primary = $entity->id();
202 6
        $definition = $entity->definition();
203 6
        foreach ($definition->getColumns() as $column) {
204 6
            if (!isset($data[$column])) {
205 6
                $entity->__lazyProperty($column, function () use ($entity, $definition, $primary, $column) {
206
                    $query = $this->db->table($definition->getName());
207
                    foreach ($primary as $k => $v) {
208
                        $query->filter($k, $v);
209
                    }
210
                    return $query->select([$column])[0][$column] ?? null;
211 6
                });
212
            }
213
        }
214 6
        foreach ($definition->getRelations() as $name => $relation) {
215 6
            if (isset($data[$name])) {
216
                $entity->{$name} = $relation->many ? 
217
                    array_map(function ($v) use ($relation) {
218
                        return $this->entity($relation->table, $v);
219
                    }, $data[$name]) :
220
                    $this->entity($relation->table, $data[$name]);
221
            } else {
222 6
                $entity->__lazyProperty($name, function (array $columns = null) use ($entity, $definition, $primary, $relation, $data) {
223 2
                    $query = $this->db->table($relation->table->getName(), true);
0 ignored issues
show
Unused Code introduced by
The call to DBInterface::table() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
224 2
                    if ($columns !== null) {
225
                        $query->columns($columns);
226
                    }
227 2
                    if ($relation->sql) {
228
                        $query->where($relation->sql, $relation->par);
229
                    }
230 2
                    if ($relation->pivot) {
231 2
                        $nm = null;
232 2
                        foreach ($relation->table->getRelations() as $rname => $rdata) {
233 2
                            if ($rdata->pivot && $rdata->pivot->getName() === $relation->pivot->getName()) {
234 2
                                $nm = $rname;
235
                            }
236
                        }
237 2
                        if (!$nm) {
238
                            $nm = $definition->getName();
239
                            $relation->table->manyToMany(
240
                                $this->db->table($definition->getName()),
241
                                $relation->pivot,
242
                                $nm,
243
                                array_flip($relation->keymap),
244
                                $relation->pivot_keymap
245
                            );
246
                        }
247 2
                        foreach ($definition->getPrimaryKey() as $v) {
248 2
                            $query->filter($nm . '.' . $v, $data[$v] ?? null);
249
                        }
250
                    } else {
251 2
                        foreach ($relation->keymap as $k => $v) {
252 2
                            $query->filter($v, $entity->{$k} ?? null);
253
                        }
254
                    }
255 2
                    return $relation->many ?
256 2
                        $query->iterator() :
257 2
                        $query[0];
258 6
                });
259
            }
260
        }
261 6
        return $entity;
262
    }
263
}