Completed
Push — master ( 254b26...d47179 )
by Oscar
01:25
created

Row   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 424
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 60
lcom 1
cbo 7
dl 0
loc 424
rs 3.6
c 0
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A __debugInfo() 0 9 1
A __call() 0 13 2
A setData() 0 6 1
A link() 0 4 1
A jsonSerialize() 0 4 1
A __toString() 0 4 1
A getTable() 0 4 1
A __get() 0 31 5
B __set() 0 27 6
A __isset() 0 6 3
A __unset() 0 6 1
A reload() 0 12 2
A toArray() 0 4 1
A edit() 0 8 2
A save() 0 26 5
A delete() 0 14 2
A relate() 0 38 5
A unrelate() 0 37 5
A unrelateAll() 0 38 5
A select() 0 9 2
A getValueName() 0 19 4
A getValue() 0 4 2

How to fix   Complexity   

Complex Class

Complex classes like Row often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Row, and based on these observations, apply Extract Interface, too.

1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud;
5
6
use BadMethodCallException;
7
use JsonSerializable;
8
use RuntimeException;
9
use SimpleCrud\Events\BeforeSaveRow;
10
use SimpleCrud\Queries\Select;
11
12
/**
13
 * Stores the data of an table row.
14
 */
15
class Row implements JsonSerializable
16
{
17
    private $table;
18
    private $values = [];
19
    private $changes = [];
20
    private $data = [];
21
22
    public function __construct(Table $table, array $values)
23
    {
24
        $this->table = $table;
25
26
        if (empty($values['id'])) {
27
            $this->values = $table->getDefaults();
28
            $this->changes = $table->getDefaults($values);
29
            unset($this->changes['id']);
30
        } else {
31
            $this->values = $table->getDefaults($values);
32
        }
33
    }
34
35
    public function __debugInfo(): array
36
    {
37
        return [
38
            'table' => (string) $this->table,
39
            'values' => $this->values,
40
            'changes' => $this->changes,
41
            'data' => $this->data,
42
        ];
43
    }
44
45
    public function __call(string $name, array $arguments): Select
46
    {
47
        $db = $this->table->getDatabase();
48
49
        //Relations
50
        if (isset($db->$name)) {
51
            return $this->select($db->$name);
52
        }
53
54
        throw new BadMethodCallException(
55
            sprintf('Invalid method call %s', $name)
56
        );
57
    }
58
59
    public function setData(array $data): self
60
    {
61
        $this->data = $data + $this->data;
62
63
        return $this;
64
    }
65
66
    /**
67
     * @param Row|RowCollection|null $row
68
     */
69
    public function link(Table $table, $row = null): self
70
    {
71
        return $this->setData([$table->getName() => $row]);
72
    }
73
74
    /**
75
     * @see JsonSerializable
76
     */
77
    public function jsonSerialize()
78
    {
79
        return $this->toArray();
80
    }
81
82
    /**
83
     * Magic method to stringify the values.
84
     */
85
    public function __toString()
86
    {
87
        return json_encode($this, JSON_NUMERIC_CHECK);
88
    }
89
90
    /**
91
     * Returns the table associated with this row
92
     */
93
    public function getTable(): Table
94
    {
95
        return $this->table;
96
    }
97
98
    /**
99
     * Returns the value of:
100
     * - a value field
101
     * - a related table
102
     */
103
    public function &__get(string $name)
104
    {
105
        if ($name === 'id') {
106
            return $this->values['id'];
107
        }
108
109
        //It's a value
110
        if ($valueName = $this->getValueName($name)) {
111
            $value = $this->getValue($valueName);
112
            return $value;
113
        }
114
115
        //It's custom data
116
        if (array_key_exists($name, $this->data)) {
117
            return $this->data[$name];
118
        }
119
120
        $db = $this->table->getDatabase();
121
122
        if (isset($db->$name)) {
123
            $this->setData([
124
                $name => $this->select($db->$name)->run(),
125
            ]);
126
127
            return $this->data[$name];
128
        }
129
130
        throw new RuntimeException(
131
            sprintf('Undefined property "%s" in the table %s', $name, $this->table)
132
        );
133
    }
134
135
    /**
136
     * Change the value of
137
     * - a field
138
     * - a localized field
139
     * @param mixed $value
140
     */
141
    public function __set(string $name, $value)
142
    {
143
        if ($name === 'id') {
144
            if (!is_null($this->values['id']) && !is_null($value)) {
145
                throw new RuntimeException('The field "id" cannot be overrided');
146
            }
147
148
            $this->values['id'] = $value;
149
150
            return $value;
151
        }
152
153
        //It's a value
154
        if ($valueName = $this->getValueName($name)) {
155
            if ($this->values[$valueName] === $value) {
156
                unset($this->changes[$valueName]);
157
            } else {
158
                $this->changes[$valueName] = $value;
159
            }
160
161
            return $value;
162
        }
163
164
        throw new RuntimeException(
165
            sprintf('The field %s does not exists', $name)
166
        );
167
    }
168
169
    /**
170
     * Check whether a value is set or not
171
     */
172
    public function __isset(string $name): bool
173
    {
174
        $valueName = $this->getValueName($name);
175
176
        return (isset($valueName) && !is_null($this->getValue($valueName))) || isset($this->data[$name]);
177
    }
178
179
    /**
180
     * Removes the value of a field
181
     */
182
    public function __unset(string $name)
183
    {
184
        unset($this->data[$name]);
185
186
        $this->__set($name, null);
187
    }
188
189
    /**
190
     * Reload the data from the database
191
     */
192
    public function reload($keepChanges = false): self
193
    {
194
        $select = $this->table->select()->where('id = ', $this->id);
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<SimpleCrud\Queries\Select>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
195
        $values = $select()->fetch(\PDO::FETCH_ASSOC);
196
        $this->values = $this->table->format($values);
197
198
        if (!$keepChanges) {
199
            $this->changes = [];
200
        }
201
202
        return $this;
203
    }
204
205
    /**
206
     * Returns an array with all fields of the row
207
     */
208
    public function toArray(): array
209
    {
210
        return $this->changes + $this->values;
211
    }
212
213
    /**
214
     * Edit the values using an array
215
     */
216
    public function edit(array $values): self
217
    {
218
        foreach ($values as $name => $value) {
219
            $this->__set($name, $value);
220
        }
221
222
        return $this;
223
    }
224
225
    /**
226
     * Insert/update the row in the database
227
     */
228
    public function save(): self
229
    {
230
        if (!empty($this->changes)) {
231
            $eventDispatcher = $this->table->getEventDispatcher();
232
233
            if ($eventDispatcher) {
234
                $eventDispatcher->dispatch(new BeforeSaveRow($this));
0 ignored issues
show
Documentation introduced by
new \SimpleCrud\Events\BeforeSaveRow($this) is of type object<SimpleCrud\Events\BeforeSaveRow>, but the function expects a object<Psr\EventDispatcher\object>.

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...
235
            }
236
237
            if (empty($this->id)) {
238
                $this->id = $this->table->insert($this->toArray())->run();
239
            } elseif (!$this->changes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->changes 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...
240
                return $this;
241
            } else {
242
                $this->table->update($this->changes)
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<SimpleCrud\Queries\Update>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
243
                    ->where('id = ', $this->id)
244
                    ->run();
245
            }
246
247
            $this->values = $this->toArray();
248
            $this->changes = [];
249
            $this->table->cache($this);
250
        }
251
252
        return $this;
253
    }
254
255
    /**
256
     * Delete the row in the database
257
     */
258
    public function delete(): self
259
    {
260
        $id = $this->id;
261
262
        if (!empty($id)) {
263
            $this->table->delete()
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<SimpleCrud\Queries\Delete>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
264
                ->where('id = ', $id)
265
                ->run();
266
267
            $this->values['id'] = null;
268
        }
269
270
        return $this;
271
    }
272
273
    /**
274
     * Relate this row with other rows
275
     */
276
    public function relate(Row ...$rows): self
277
    {
278
        $table1 = $this->table;
279
280
        foreach ($rows as $row) {
281
            $table2 = $row->getTable();
282
283
            //Has one
284
            if ($field = $table1->getJoinField($table2)) {
285
                $this->{$field->getName()} = $row->id;
286
                continue;
287
            }
288
289
            //Has many
290
            if ($field = $table2->getJoinField($table1)) {
291
                $row->{$field->getName()} = $this->id;
292
                $row->save();
293
                continue;
294
            }
295
296
            //Has many to many
297
            if ($joinTable = $table1->getJoinTable($table2)) {
298
                $joinTable->insert([
299
                    $joinTable->getJoinField($table1)->getName() => $this->id,
300
                    $joinTable->getJoinField($table2)->getName() => $row->id,
301
                ])
302
                ->run();
303
304
                continue;
305
            }
306
307
            throw new RuntimeException(
308
                sprintf('The tables %s and %s are not related', $table1, $table2)
309
            );
310
        }
311
312
        return $this->save();
313
    }
314
315
    /**
316
     * Unrelate this row with other rows
317
     */
318
    public function unrelate(Row ...$rows): self
319
    {
320
        $table1 = $this->table;
321
322
        foreach ($rows as $row) {
323
            $table2 = $row->getTable();
324
325
            //Has one
326
            if ($field = $table1->getJoinField($table2)) {
327
                $this->{$field->getName()} = null;
328
                continue;
329
            }
330
331
            //Has many
332
            if ($field = $table2->getJoinField($table1)) {
333
                $row->{$field->getName()} = null;
334
                $row->save();
335
                continue;
336
            }
337
338
            //Has many to many
339
            if ($joinTable = $table1->getJoinTable($table2)) {
340
                $joinTable->delete()
341
                    ->where("{$joinTable->getJoinField($table1)} = ", $this->id)
342
                    ->where("{$joinTable->getJoinField($table2)} = ", $row->id)
343
                    ->run();
344
345
                continue;
346
            }
347
348
            throw new RuntimeException(
349
                sprintf('The tables %s and %s are not related', $table1, $table2)
350
            );
351
        }
352
353
        return $this->save();
354
    }
355
356
    /**
357
     * Unrelate this row with all rows of other tables
358
     */
359
    public function unrelateAll(Table ...$tables): self
360
    {
361
        $table1 = $this->table;
362
363
        foreach ($tables as $table2) {
364
            //Has one
365
            if ($field = $table1->getJoinField($table2)) {
366
                $this->{$field->getName()} = null;
367
                continue;
368
            }
369
370
            //Has many
371
            if ($field = $table2->getJoinField($table1)) {
372
                $table2->update([
373
                    $field->getName() => null,
374
                ])
375
                ->relatedWith($table1)
376
                ->run();
377
                continue;
378
            }
379
380
            //Has many to many
381
            if ($joinTable = $table1->getJoinTable($table2)) {
382
                $joinTable->delete()
383
                    ->where("{$joinTable->getJoinField($table1)} = ", $this->id)
384
                    ->where("{$joinTable->getJoinField($table2)} IS NOT NULL")
385
                    ->run();
386
387
                continue;
388
            }
389
390
            throw new RuntimeException(
391
                sprintf('The tables %s and %s are not related', $table1, $table2)
392
            );
393
        }
394
395
        return $this->save();
396
    }
397
398
    /**
399
     * Creates a select query of a table related with this row
400
     */
401
    public function select(Table $table): Select
402
    {
403
        //Has one
404
        if ($this->table->getJoinField($table)) {
405
            return $table->select()->one()->relatedWith($this);
406
        }
407
408
        return $table->select()->relatedWith($this);
409
    }
410
411
    /**
412
     * Return the real field name
413
     */
414
    private function getValueName(string $name): ?string
415
    {
416
        if (array_key_exists($name, $this->values)) {
417
            return $name;
418
        }
419
420
        //It's a localizable field
421
        $language = $this->table->getDatabase()->getConfig(Database::CONFIG_LOCALE);
422
423
        if (!is_null($language)) {
424
            $name .= "_{$language}";
425
426
            if (array_key_exists($name, $this->values)) {
427
                return $name;
428
            }
429
        }
430
431
        return null;
432
    }
433
434
    private function getValue(string $name)
435
    {
436
        return array_key_exists($name, $this->changes) ? $this->changes[$name] : $this->values[$name];
437
    }
438
}
439