Completed
Push — master ( bbfa89...3fb487 )
by Antonio Oertel
49s
created

Mapper::extractColumns()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
crap 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 28 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
namespace Respect\Structural;
4
5
use Respect\Data\AbstractMapper;
6
use Respect\Data\CollectionIterator;
7
use Respect\Data\Collections\Collection;
8
use Exception;
9
use SplObjectStorage;
10
use Respect\Data\Collections as c;
11
use ReflectionProperty;
12
13
/** Maps objects to nosql operations */
14
class Mapper extends AbstractMapper implements
0 ignored issues
show
Bug introduced by
Possible parse error: class missing opening or closing brace
Loading history...
15
    c\Filterable,
16
    c\Mixable,
17
    c\Typable
18
{
19
    /** @var \Respect\Structural\Driver Holds our connector* */
20
    protected $driver;
21
22
    /** @var string Namespace to look for entities * */
23
    public $entityNamespace = '\\';
24
25
    /**
26
     * @param Driver $driver
27
     */
28 3
    public function __construct(Driver $driver)
29
    {
30 3
        parent::__construct();
31
32 3
        $this->driver = $driver;
33 3
    }
34
35
    /**
36
     * @return Mapper
37
     */
38 3
    public function __get($name)
39
    {
40 3
        return parent::__get($name);
41
    }
42
43
    /**
44
     * Flushes a single instance into the database. This method supports
45
     * mixing, so flushing a mixed instance will flush distinct tables on the
46
     * database
47
     *
48
     * @param object $entity Entity instance to be flushed
49
     *
50
     * @return null
51
     */
52 3
    protected function flushSingle($entity)
53
    {
54 3
        $coll = $this->tracked[$entity];
55 3
        $cols = $this->extractColumns($entity, $coll);
56
57 3
        if ($this->removed->contains($entity)) {
58 1
            $this->rawDelete($coll, $entity);
59 3
        } elseif ($this->new->contains($entity)) {
60 1
            $this->rawInsert($coll, $entity);
61 1
        } else {
62 1
            $this->rawUpdate($cols, $coll);
63
        }
64 3
    }
65
66 2
    public function persist($object, Collection $onCollection)
67
    {
68 2
        $next = $onCollection->getNext();
69
70 2
        if ($this->filterable($onCollection)) {
71
            $next->setMapper($this);
72
            $next->persist($object);
73
            return;
74
        }
75
76 2
        if ($next) {
77
            $remote = $this->getStyle()->remoteIdentifier($next->getName());
78
            $next->setMapper($this);
79
            $next->persist($object->$remote);
80
        }
81
82 2
        foreach ($onCollection->getChildren() as $child) {
83
            $remote = $this->getStyle()->remoteIdentifier($child->getName());
84
            $child->persist($object->$remote);
85 2
        }
86
87 2
        return parent::persist($object, $onCollection);
88
    }
89
90
    /**
91
     * Receives columns from an entity and her collection. Returns the columns
92
     * that belong only to the main entity. This method supports mixing, so
93
     * extracting mixins will also persist them on their respective
94
     * tables
95
     *
96
     * @param \Respect\Data\Collections\Collection $collection Target collection
97
     * @param array $cols Entity columns
98
     *
99
     * @return array Columns left for the main collection
100
     */
101 1
    protected function extractAndOperateMixins(Collection $collection, $cols)
102
    {
103 1
        if (!$this->mixable($collection)) {
104 1
            return $cols;
105
        }
106
107
        foreach ($this->getMixins($collection) as $mix => $spec) {
108
            //Extract from $cols only the columns from the mixin
109
            $mixCols = array_intersect_key(
110
                $cols,
111
                array_combine( //create array with keys only
112
                    $spec,
113
                    array_fill(0, count($spec), '')
114
                )
115
            );
116
            if (isset($cols["{$mix}_id"])) {
117
                $mixCols['id'] = $cols["{$mix}_id"];
118
                $cols = array_diff($cols, $mixCols); //Remove mixin columns
119
                $this->rawUpdate($mixCols, $this->__get($mix));
0 ignored issues
show
Documentation introduced by
$this->__get($mix) is of type object<Respect\Structural\Mapper>, but the function expects a object<Respect\Data\Collections\Collection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
120
            } else {
121
                $mixCols['id'] = null;
122
                $cols = array_diff($cols, $mixCols); //Remove mixin columns
123
                $this->rawinsert($mixCols, $this->__get($mix));
0 ignored issues
show
Documentation introduced by
$mixCols is of type array<string,null,{"id":"null"}>, but the function expects a object<Respect\Data\Collections\Collection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
124
            }
125
        }
126
127
        return $cols;
128
    }
129
130 2
    protected function guessCondition(&$columns, Collection $collection)
131
    {
132 2
        $primaryName = $this->getStyle()->identifier($collection->getName());
133 2
        $condition = array($primaryName => $columns[$primaryName]);
134 2
        unset($columns[$primaryName]);
135 2
        return $condition;
136
    }
137
138 1
    protected function rawDelete(Collection $collection, $entity)
139
    {
140 1
        $name = $collection->getName();
141 1
        $columns = $this->extractColumns($entity, $collection);
142 1
        $condition = $this->guessCondition($columns, $collection);
143
144 1
        return $this->driver->remove($name, $condition);
145
    }
146
147 1
    protected function rawUpdate(array $columns, Collection $collection)
148
    {
149 1
        $columns = $this->extractAndOperateMixins($collection, $columns);
150 1
        $name = $collection->getName();
151 1
        $condition = $this->guessCondition($columns, $collection);
152
153 1
        $this->driver->update($name, $condition, $columns);
154 1
    }
155
156 1
    protected function rawInsert(Collection $collection, $entity = null)
157
    {
158 1
        $name = $collection->getName();
159 1
        $this->driver->insert($name, $entity);
160 1
    }
161
162 3
    public function flush()
163
    {
164
        try {
165 3
            foreach ($this->changed as $entity) {
166 3
                $this->flushSingle($entity);
167 3
            }
168 3
        } catch (Exception $e) {
169
            throw $e;
170
        }
171
172 3
        $this->reset();
173 3
    }
174
175 2
    protected function createStatement(Collection $collection, $withExtra = null)
176
    {
177 2
        $query = $this->generateQuery($collection);
178
179 2
        $withExtraList = (array)$withExtra;
180
181 2
        $withExtraList = array_merge($withExtraList, $query);
182
183 2
        return $this->driver->find($collection->getName(), $withExtraList);
184
    }
185
186 2
    protected function generateQuery(Collection $collection)
187
    {
188 2
        return $this->driver->generateQuery($collection);
189
    }
190
191 3
    protected function extractColumns($entity, Collection $collection)
192
    {
193 3
        $primaryName = $this->getStyle()->identifier($collection->getName());
0 ignored issues
show
Unused Code introduced by
$primaryName 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...
194 3
        $cols = get_object_vars($entity);
195
196 3
        return $cols;
197
    }
198
199
    protected function hasComposition($entity, $next, $parent)
200
    {
201
        $s = $this->getStyle();
202
        return $entity === $s->composed($parent, $next)
203
        || $entity === $s->composed($next, $parent);
204
    }
205
206 2
    protected function fetchSingle(Collection $collection, $statement)
207
    {
208 2
        $name = $collection->getName();
209 2
        $entityName = $name;
210 2
        $row = $this->driver->fetch($statement);
211
212 2
        if (!$row) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $row of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
213
            return false;
214
        }
215
216 2
        if ($this->typable($collection)) {
217
            $entityName = $row->{$this->getType($collection)};
218
        }
219
220 2
        $entities = new SplObjectStorage();
221 2
        $entities[$this->transformSingleRow($row, $entityName)] = $collection;
222
223 2
        return $entities;
224
    }
225
226 2
    protected function getNewEntityByName($entityName)
227
    {
228 2
        $entityName = $this->getStyle()->styledName($entityName);
229 2
        $entityClass = $this->entityNamespace . $entityName;
230 2
        $entityClass = class_exists($entityClass) ? $entityClass : '\stdClass';
231 2
        return new $entityClass;
232
    }
233
234 2
    protected function transformSingleRow($row, $entityName)
235
    {
236 2
        $newRow = $this->getNewEntityByName($entityName);
237
238 2
        foreach ($row as $prop => $value) {
239 2
            $this->inferSet($newRow, $prop, $value);
240 2
        }
241 2
        return $newRow;
242
    }
243
244 2
    protected function inferSet(&$entity, $prop, $value)
245
    {
246 2
        $setterName = $this->getSetterStyle($prop);
0 ignored issues
show
Unused Code introduced by
$setterName 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...
247
        try {
248 2
            $mirror = new \ReflectionProperty($entity, $prop);
249
            $mirror->setAccessible(true);
250
            $mirror->setValue($entity, $value);
251 2
        } catch (\ReflectionException $e) {
252 2
            $entity->$prop = $value;
253
        }
254 2
    }
255
256
    protected function fetchMulti(Collection $collection, $statement)
257
    {
258
        $entityInstance = null;
0 ignored issues
show
Unused Code introduced by
$entityInstance 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...
259
        $row = $this->driver->fetch($statement);
260
261
        if (!$row) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $row of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
262
            return false;
263
        }
264
265
        $this->postHydrate(
266
            $entities = $this->createEntities($row, $statement, $collection)
267
        );
268
269
        return $entities;
270
    }
271
272
    protected function createEntities($row, $statement, Collection $collection)
273
    {
274
275
        $entities = new SplObjectStorage();
276
        $entitiesInstances = $this->buildEntitiesInstances(
277
            $collection,
278
            $entities
279
        );
280
        $entityInstance = array_pop($entitiesInstances);
281
282
        //Reversely traverses the columns to avoid conflicting foreign key names
283
        foreach (array_reverse($row, true) as $col => $value) {
284
            $columnMeta = $statement->getColumnMeta($col);
285
            $columnName = $columnMeta['name'];
286
            $primaryName = $this->getStyle()->identifier(
287
                $entities[$entityInstance]->getName()
288
            );
289
290
            $this->inferSet($entityInstance, $columnName, $value);
291
292
            if ($primaryName == $columnName) {
293
                $entityInstance = array_pop($entitiesInstances);
294
            }
295
        }
296
        return $entities;
297
    }
298
299
    protected function buildEntitiesInstances(Collection $collection, SplObjectStorage $entities) {
300
        $entitiesInstances = array();
301
302
        foreach (CollectionIterator::recursive($collection) as $c) {
303
            if ($this->filterable($c) && !$this->getFilters($c)) {
304
                continue;
305
            }
306
307
            $entityInstance = $this->getNewEntityByName($c->getName());
308
            $mixins = array();
0 ignored issues
show
Unused Code introduced by
$mixins 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...
309
310
            if ($this->mixable($c)) {
311
                $mixins = $this->getMixins($c);
312
                foreach ($mixins as $mix) {
313
                    $entitiesInstances[] = $entityInstance;
314
                }
315
            }
316
317
            $entities[$entityInstance] = $c;
318
            $entitiesInstances[] = $entityInstance;
319
        }
320
        return $entitiesInstances;
321
    }
322
323
    protected function postHydrate(SplObjectStorage $entities)
324
    {
325
        $entitiesClone = clone $entities;
326
327
        foreach ($entities as $instance) {
328
            foreach ($instance as $field => &$v) {
329
                if ($this->getStyle()->isRemoteIdentifier($field)) {
330
                    foreach ($entitiesClone as $sub) {
331
                        $this->tryHydration($entities, $sub, $field, $v);
332
                    }
333
                }
334
            }
335
        }
336
    }
337
338
    protected function tryHydration($entities, $sub, $field, &$v)
339
    {
340
        $tableName = $entities[$sub]->getName();
341
        $primaryName = $this->getStyle()->identifier($tableName);
342
343
        if ($tableName === $this->getStyle()->remoteFromIdentifier($field)
344
            && $sub->{$primaryName} === $v
345
        ) {
346
            $v = $sub;
347
        }
348
    }
349
350 2
    protected function getSetterStyle($name)
351
    {
352 2
        $name = str_replace('_', '', $this->getStyle()->styledProperty($name));
353 2
        return "set{$name}";
354
    }
355
356
    public function getFilters(Collection $collection)
357
    {
358
        return $collection->getExtra('filters');
359
    }
360
361
    public function getMixins(Collection $collection)
362
    {
363
        return $collection->getExtra('mixins');
364
    }
365
366
    public function getType(Collection $collection)
367
    {
368
        return $collection->getExtra('type');
369
    }
370
371 1
    public function mixable(Collection $collection)
372
    {
373 1
        return $collection->have('mixins');
374
    }
375
376 2
    public function typable(Collection $collection)
377
    {
378 2
        return $collection->have('type');
379
    }
380
381 2
    public function filterable(Collection $collection)
382
    {
383 2
        return $collection->have('filters');
384
    }
385
386
}
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 4 spaces, but found 0).
Loading history...
387
388