Completed
Push — develop ( 05126a...56f424 )
by Mathieu
01:53
created

DBObject::loadRelation()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 8.125

Importance

Changes 0
Metric Value
cc 5
eloc 9
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 14
rs 9.6111
ccs 5
cts 10
cp 0.5
crap 8.125
1
<?php
2
namespace Suricate;
3
4
/**
5
 * DBObject, Pseudo ORM Class
6
 *
7
 * Two types of variables are available :
8
 * - $dbVariables, an array of fields contained in linked SQL table
9
 * - $protectedVariables, an array of variables not stored in SQL
10
 *     that can be triggered on access
11
 *
12
 * @package Suricate
13
 * @author  Mathieu LESNIAK <[email protected]>
14
 */
15
16
class DBObject implements Interfaces\IDBObject
17
{
18
    /** @var string Linked SQL Table */
19
    protected $tableName = '';
20
21
    /** @var string Unique ID of the SQL table */
22
    protected $tableIndex = '';
23
    
24
    /** @var string Database config name */
25
    protected $DBConfig = '';
26
27
    /**
28
     * @const RELATION_ONE_ONE : Relation one to one
29
     */
30
    const RELATION_ONE_ONE      = 1;
31
    /**
32
     * @const RELATION_ONE_MANY : Relation one to many
33
     */
34
    const RELATION_ONE_MANY     = 2;
35
    /**
36
     * @const RELATION_MANY_MANY : Relation many to many
37
     */
38
    const RELATION_MANY_MANY    = 3;
39
40
    protected $dbVariables                  = [];
41
    protected $dbValues                     = [];
42
    
43
    protected $protectedVariables           = [];
44
    protected $protectedValues              = [];
45
    protected $loadedProtectedVariables     = [];
46
47
    protected $readOnlyVariables            = [];
48
49
    protected $relations                    = [];
50
    protected $relationValues               = [];
51
    protected $loadedRelations              = [];
52
53
    protected $exportedVariables            = [];
54
55
    protected $dbLink                       = false;
56
57
    protected $validatorMessages            = [];
58
    
59
60 13
    public function __construct()
61
    {
62 13
        $this->setRelations();
63 13
    }
64
    /**
65
     * Magic getter
66
     *
67
     * Try to get object property according this order :
68
     * <ul>
69
     *     <li>$dbVariable</li>
70
     *     <li>$protectedVariable (triggger call to accessToProtectedVariable()
71
     *         if not already loaded)</li>
72
     * </ul>
73
     *
74
     * @param  string $name     Property name
75
     * @return Mixed            Property value
76
     */
77 6
    public function __get($name)
78
    {
79 6
        if ($this->isDBVariable($name)) {
80 5
            return $this->getDBVariable($name);
81 2
        } elseif ($this->isProtectedVariable($name)) {
82
            return $this->getProtectedVariable($name);
83 2
        } elseif ($this->isRelation($name)) {
84 1
            return $this->getRelation($name);
85 1
        } elseif (!empty($this->$name)) {
86
            return $this->$name;
87
        }
88
89 1
        throw new \InvalidArgumentException('Undefined property ' . $name);
90
    }
91
92
        /**
93
     * Magic setter
94
     *
95
     * Set a property to defined value
96
     * Assignment in this order :
97
     * - $dbVariable
98
     * - $protectedVariable
99
     *  </ul>
100
     * @param string $name  variable name
101
     * @param mixed $value variable value
102
     */
103 5
    public function __set($name, $value)
104
    {
105 5
        if ($this->isDBVariable($name)) {
106 4
            $this->dbValues[$name] = $value;
107 2
        } elseif ($this->isProtectedVariable($name)) {
108
            $this->protectedValues[$name] = $value;
109 2
        } elseif ($this->isRelation($name)) {
110
            $this->relationValues[$name] = $value;
111
        } else {
112 2
            $this->$name = $value;
113
        }
114 5
    }
115
116 2
    public function __isset($name)
117
    {
118 2
        if ($this->isDBVariable($name)) {
119 1
            return isset($this->dbValues[$name]);
120 2
        } elseif ($this->isProtectedVariable($name)) {
121
            // Load only one time protected variable automatically
122
            if (!$this->isProtectedVariableLoaded($name)) {
123
                $protectedAccessResult = $this->accessToProtectedVariable($name);
124
125
                if ($protectedAccessResult) {
0 ignored issues
show
introduced by
The condition $protectedAccessResult is always false.
Loading history...
126
                    $this->markProtectedVariableAsLoaded($name);
127
                }
128
            }
129
            return isset($this->protectedValues[$name]);
130 2
        } elseif ($this->isRelation($name)) {
131
            if (!$this->isRelationLoaded($name)) {
132
                $relationResult = $this->loadRelation($name);
133
134
                if ($relationResult) {
135
                    $this->markRelationAsLoaded($name);
136
                }
137
            }
138
            return isset($this->relationValues[$name]);
139
        }
140
141 2
        return false;
142
    }
143
144 4
    public function getTableName()
145
    {
146 4
        return $this->tableName;
147
    }
148
149 5
    public function getTableIndex()
150
    {
151 5
        return $this->tableIndex;
152
    }
153
154 1
    public function getDBConfig()
155
    {
156 1
        return $this->DBConfig;
157
    }
158
159
    /**
160
     * __sleep magic method, permits an inherited DBObject class to be serialized
161
     * @return Array of properties to serialize
162
     */
163
    public function __sleep()
164
    {
165
        $discardedProps = ['dbLink', 'relations'];
166
        $reflection     = new \ReflectionClass($this);
167
        $props          = $reflection->getProperties();
168
        $result         = [];
169
        foreach ($props as $currentProperty) {
170
            $result[] = $currentProperty->name;
171
        }
172
        
173
        return array_diff($result, $discardedProps);
174
    }
175
176 1
    public function __wakeup()
177
    {
178 1
        $this->dbLink = false;
179 1
        $this->setRelations();
180 1
    }
181
    
182
    /**
183
     * @param string $name
184
     */
185 5
    private function getDBVariable($name)
186
    {
187 5
        if (isset($this->dbValues[$name])) {
188 5
            return $this->dbValues[$name];
189
        }
190
191 3
        return null;
192
    }
193
194
    /**
195
     * Check if variable is from DB
196
     * @param  string  $name variable name
197
     * @return boolean
198
     */
199 8
    public function isDBVariable($name)
200
    {
201 8
        return in_array($name, $this->dbVariables);
202
    }
203
204
    /**
205
     * @param string $name
206
     */
207
    private function getProtectedVariable($name)
208
    {
209
        // Variable exists, and is already loaded
210
        if (isset($this->protectedValues[$name]) && $this->isProtectedVariableLoaded($name)) {
211
            return $this->protectedValues[$name];
212
        }
213
        // Variable has not been loaded
214
        if (!$this->isProtectedVariableLoaded($name)) {
215
            if ($this->accessToProtectedVariable($name)) {
216
                $this->markProtectedVariableAsLoaded($name);
217
            }
218
        }
219
220
        if (isset($this->protectedValues[$name])) {
221
            return $this->protectedValues[$name];
222
        }
223
224
        return null;
225
    }
226
227
    /**
228
     * @param string $name
229
     */
230 1
    protected function getRelation($name)
231
    {
232 1
        if (isset($this->relationValues[$name]) && $this->isRelationLoaded($name)) {
233 1
            return $this->relationValues[$name];
234
        }
235
236 1
        if (!$this->isRelationLoaded($name)) {
237 1
            if ($this->loadRelation($name)) {
238 1
                $this->markRelationAsLoaded($name);
239
            }
240
        }
241
242 1
        if (isset($this->relationValues[$name])) {
243 1
            return $this->relationValues[$name];
244
        }
245
246
        return null;
247
    }
248
249
    /**
250
     * Check if variable is predefined relation
251
     * @param  string  $name variable name
252
     * @return boolean
253
     */
254 5
    protected function isRelation($name)
255
    {
256 5
        return isset($this->relations[$name]);
257
    }
258
    /**
259
     * Define object relations
260
     *
261
     * @return DBObject
262
     */
263 11
    protected function setRelations()
264
    {
265 11
        $this->relations = [];
266
267 11
        return $this;
268
    }
269
270
    /**
271
     * Define object exported variables
272
     *
273
     * @return DBObject
274
     */
275 1
    protected function setExportedVariables()
276
    {
277 1
        if (count($this->exportedVariables)) {
278 1
            return $this;
279
        }
280
281 1
        $dbMappingExport = [];
282 1
        foreach ($this->dbVariables as $field) {
283 1
            $dbMappingExport[$field] = $field;
284
        }
285 1
        $this->exportedVariables = $dbMappingExport;
286
287 1
        return $this;
288
    }
289
290
    /**
291
     * Export DBObject to array
292
     *
293
     * @return array
294
     */
295 1
    public function toArray()
296
    {
297 1
        $this->setExportedVariables();
298 1
        $result = [];
299 1
        foreach ($this->exportedVariables as $sourceName => $destinationName) {
300 1
            $omitEmpty  = false;
301 1
            $castType   = null;
302 1
            if (strpos($destinationName, ',') !== false) {
303 1
                $splitted   = explode(',', $destinationName);
304 1
                array_map(function ($item) use (&$castType, &$omitEmpty) {
305 1
                    if ($item === 'omitempty') {
306
                        $omitEmpty = true;
307
                        return;
308
                    }
309 1
                    if (substr($item, 0, 5) === 'type:') {
310 1
                        $castType = substr($item, 5);
311
                    }
312 1
                }, $splitted);
313
314 1
                $destinationName = $splitted[0];
315
            }
316
317 1
            if ($destinationName === '-') {
318 1
                continue;
319
            }
320
321 1
            if ($omitEmpty && empty($this->$sourceName)) {
322
                continue;
323
            }
324 1
            $value = $this->$sourceName;
325 1
            if ($castType !== null) {
326 1
                settype($value, $castType);
327
            }
328 1
            $result[$destinationName] = $value;
329
        }
330
331 1
        return $result;
332
    }
333
334
    /**
335
     * Export DBObject to JSON format
336
     *
337
     * @return string
338
     */
339
    public function toJson()
340
    {
341
        return implode('', array_map('json_encode', $this->toArray()));
342
    }
343
344
    /**
345
     * Mark a protected variable as loaded
346
     * @param  string $name varialbe name
347
     * @return void
348
     */
349
    public function markProtectedVariableAsLoaded($name)
350
    {
351
        if ($this->isProtectedVariable($name)) {
352
            $this->loadedProtectedVariables[$name] = true;
353
        }
354
    }
355
356
    /**
357
     * Mark a relation as loaded
358
     * @param  string $name varialbe name
359
     * @return void
360
     */
361 1
    protected function markRelationAsLoaded($name)
362
    {
363 1
        if ($this->isRelation($name)) {
364 1
            $this->loadedRelations[$name] = true;
365
        }
366 1
    }
367
     /**
368
     * Check if a relation already have been loaded
369
     * @param  string  $name Variable name
370
     * @return boolean
371
     */
372 1
    protected function isRelationLoaded($name)
373
    {
374 1
        return isset($this->loadedRelations[$name]);
375
    }
376
377 1
    protected function loadRelation($name)
378
    {
379 1
        if (isset($this->relations[$name])) {
380 1
            switch ($this->relations[$name]['type']) {
381 1
                case self::RELATION_ONE_ONE:
382 1
                    return $this->loadRelationOneOne($name);
383
                case self::RELATION_ONE_MANY:
384
                    return $this->loadRelationOneMany($name);
385
                case self::RELATION_MANY_MANY:
386
                    return $this->loadRelationManyMany($name);
387
            }
388
        }
389
390
        return false;
391
    }
392
393 1
    private function loadRelationOneOne($name)
394
    {
395 1
        $target = $this->relations[$name]['target'];
396 1
        $source = $this->relations[$name]['source'];
397 1
        $this->relationValues[$name] = new $target();
398 1
        $this->relationValues[$name]->load($this->$source);
399
        
400 1
        return true;
401
    }
402
403
    private function loadRelationOneMany($name)
404
    {
405
        $target         = $this->relations[$name]['target'];
406
        $parentId       = $this->{$this->relations[$name]['source']};
407
        $parentIdField  = isset($this->relations[$name]['target_field']) ? $this->relations[$name]['target_field'] : null;
408
        $validate       = dataGet($this->relations[$name], 'validate', null);
409
        
410
        $this->relationValues[$name] = $target::loadForParentId($parentId, $parentIdField, $validate);
411
412
        return true;
413
    }
414
415
    private function loadRelationManyMany($name)
416
    {
417
        $pivot      = $this->relations[$name]['pivot'];
418
        $sourceType = $this->relations[$name]['source_type'];
419
        $target     = dataGet($this->relations[$name], 'target');
420
        $validate   = dataGet($this->relations[$name], 'validate', null);
421
422
        $this->relationValues[$name] = $pivot::loadFor($sourceType, $this->{$this->relations[$name]['source']}, $target, $validate);
423
        
424
        return true;
425
    }
426
427 3
    private function resetLoadedVariables()
428
    {
429 3
        $this->loadedProtectedVariables = [];
430 3
        $this->loadedRelations          = [];
431
432 3
        return $this;
433
    }
434
435
    /**
436
     * Check if requested property exists
437
     *
438
     * Check in following order:
439
     * <ul>
440
     *     <li>$dbVariables</li>
441
     *     <li>$protectedVariables</li>
442
     *     <li>$relations</li>
443
     *     <li>legacy property</li>
444
     * </ul>
445
     * @param  string $property Property name
446
     * @return boolean           true if exists
447
     */
448 2
    public function propertyExists($property)
449
    {
450 2
        return $this->isDBVariable($property)
451 2
            || $this->isProtectedVariable($property)
452 2
            || $this->isRelation($property)
453 2
            || property_exists($this, $property);
454
    }
455
   
456
   /**
457
    * Check if variable is a protected variable
458
    * @param  string  $name variable name
459
    * @return boolean
460
    */
461 5
    public function isProtectedVariable($name)
462
    {
463 5
        return in_array($name, $this->protectedVariables);
464
    }
465
466
    
467
468
    /**
469
     * Check if a protected variable already have been loaded
470
     * @param  string  $name Variable name
471
     * @return boolean
472
     */
473
    protected function isProtectedVariableLoaded($name)
474
    {
475
        return isset($this->loadedProtectedVariables[$name]);
476
    }
477
478
    
479
    
480
    /**
481
     * Load ORM from Database
482
     * @param  mixed $id SQL Table Unique id
483
     * @return mixed     Loaded object or false on failure
484
     */
485 3
    public function load($id)
486
    {
487 3
        $this->connectDB();
488 3
        $this->resetLoadedVariables();
489
490 3
        $query  = "SELECT *";
491 3
        $query .= " FROM `" . $this->getTableName() ."`";
492 3
        $query .= " WHERE";
493 3
        $query .= "     `" . $this->getTableIndex() . "` =  :id";
494
        
495 3
        $params         = [];
496 3
        $params['id']   = $id;
497
498 3
        return $this->loadFromSql($query, $params);
499
    }
500
501 2
    public function isLoaded()
502
    {
503 2
        return $this->{$this->getTableIndex()} !== null;
504
    }
505
506
    public function loadOrFail($id)
507
    {
508
        $this->load($id);
509
        if ($id == '' || $this->{$this->getTableIndex()} != $id) {
510
            throw (new Exception\ModelNotFoundException)->setModel(get_called_class());
511
        }
512
513
        return $this;
514
    }
515
516
    public static function loadOrCreate($arg)
517
    {
518
        $obj = static::loadOrInstanciate($arg);
519
        $obj->save();
520
521
        return $obj;
522
    }
523
524
    public static function loadOrInstanciate($arg)
525
    {
526
        $calledClass = get_called_class();
527
        $obj = new $calledClass;
528
        
529
        if (!is_array($arg)) {
530
            $arg = [$obj->getTableIndex() => $arg];
531
        }
532
        
533
534
        $sql = "SELECT *";
535
        $sql .= " FROM `" . $obj->getTableName() . "`";
536
        $sql .= " WHERE ";
537
538
        $sqlArray   = [];
539
        $params     = [];
540
        $i = 0;
541
        foreach ($arg as $key => $val) {
542
            if (is_null($val)) {
543
                $sqlArray[] = '`' . $key . '` IS :arg' . $i;
544
            } else {
545
                $sqlArray[] = '`' . $key . '`=:arg' . $i;
546
            }
547
            $params['arg' .$i] = $val;
548
            $i++;
549
        }
550
        $sql .= implode(' AND ', $sqlArray);
551
552
        if (!$obj->loadFromSql($sql, $params)) {
553
            foreach ($arg as $property => $value) {
554
                $obj->$property = $value;
555
            }
556
        }
557
558
        return $obj;
559
    }
560
    
561
    /**
562
     * @param string $sql
563
     */
564 3
    public function loadFromSql($sql, $sqlParams = [])
565
    {
566 3
        $this->connectDB();
567 3
        $this->resetLoadedVariables();
568
        
569 3
        $results = $this->dbLink->query($sql, $sqlParams)->fetch();
570
571 3
        if ($results !== false) {
572 3
            foreach ($results as $key => $value) {
573 3
                $this->$key = $value;
574
            }
575
576 3
            return $this;
577
        }
578
579
        return false;
580
    }
581
582
    /**
583
     * Construct an DBObject from an array
584
     * @param  array $data  associative array
585
     * @return DBObject       Built DBObject
586
     */
587
    public static function instanciate($data = [])
588
    {
589
        $calledClass    = get_called_class();
590
        $orm            = new $calledClass;
591
592
        return $orm->hydrate($data);
593
    }
594
595 1
    public function hydrate($data = [])
596
    {
597 1
        foreach ($data as $key => $val) {
598 1
            if ($this->propertyExists($key)) {
599 1
                $this->$key = $val;
600
            }
601
        }
602
603 1
        return $this;
604
    }
605
606
    public static function create($data = [])
607
    {
608
        $obj = static::instanciate($data);
609
        $obj->save();
610
611
        return $obj;
612
    }
613
    
614
    /**
615
     * Delete record from SQL Table
616
     *
617
     * Delete record link to current object, according SQL Table unique id
618
     * @return null
619
     */
620
    public function delete()
621
    {
622
        $this->connectDB();
623
624
        if ($this->getTableIndex() !== '') {
625
            $query  = "DELETE FROM `" . $this->getTableName() . "`";
626
            $query .= " WHERE `" . $this->getTableIndex() . "` = :id";
627
628
            $queryParams = [];
629
            $queryParams['id'] = $this->{$this->getTableIndex()};
630
            
631
            $this->dbLink->query($query, $queryParams);
632
        }
633
    }
634
    
635
    /**
636
     * Save current object into db
637
     *
638
     * Call INSERT or UPDATE if unique index is set
639
     * @param  boolean $forceInsert true to force insert instead of update
640
     * @return null
641
     */
642
    public function save($forceInsert = false)
643
    {
644
        if (count($this->dbValues)) {
645
            $this->connectDB();
646
647
            if ($this->{$this->getTableIndex()} != '' && !$forceInsert) {
648
                $this->update();
649
                $insert = false;
650
            } else {
651
                $this->insert();
652
                $insert = true;
653
            }
654
655
            // Checking protected variables
656
            foreach ($this->protectedVariables as $variable) {
657
                // only if current protected_var is set
658
                if (isset($this->protectedValues[$variable]) && $this->isProtectedVariableLoaded($variable)) {
659
                    if ($this->protectedValues[$variable] instanceof Interfaces\ICollection) {
660
                        if ($insert) {
661
                            $this->protectedValues[$variable]->setParentIdForAll($this->{$this->getTableIndex()});
662
                        }
663
                        $this->protectedValues[$variable]->save();
664
                    }
665
                }
666
            }
667
        } else {
668
            throw new \RuntimeException("Object " . get_called_class() . " has no properties to save");
669
        }
670
    }
671
672
    /**
673
     * UPDATE current object into database
674
     * @return null
675
     */
676
    private function update()
677
    {
678
        $this->connectDB();
679
680
        $sqlParams = [];
681
682
        $sql  = 'UPDATE `' . $this->getTableName() . '`';
683
        $sql .= ' SET ';
684
        
685
686
        foreach ($this->dbValues as $key => $val) {
687
            if (!in_array($key, $this->readOnlyVariables)) {
688
                $sql .= ' `' . $key . '`=:' . $key .', ';
689
                $sqlParams[$key] = $val;
690
            }
691
        }
692
        $sql  = substr($sql, 0, -2);
693
        $sql .= " WHERE `" . $this->getTableIndex() . "` = :SuricateTableIndex";
694
695
        $sqlParams[':SuricateTableIndex'] = $this->{$this->getTableIndex()};
696
697
        $this->dbLink->query($sql, $sqlParams);
698
    }
699
700
    /**
701
     * INSERT current object into database
702
     * @access  private
703
     * @return null
704
     */
705
    private function insert()
706
    {
707
        $this->connectDB();
708
        
709
        $variables = array_diff($this->dbVariables, $this->readOnlyVariables);
710
711
        $sql  = 'INSERT INTO `' . $this->getTableName() . '`';
712
        $sql .= '(`';
713
        $sql .= implode('`, `', $variables);
714
        $sql .= '`)';
715
        $sql .= ' VALUES (:';
716
        $sql .= implode(', :', $variables);
717
        $sql .= ')';
718
719
        $sqlParams = [];
720
        foreach ($variables as $field) {
721
            $sqlParams[':' . $field] = $this->$field;
722
        }
723
        
724
        $this->dbLink->query($sql, $sqlParams);
725
726
        $this->{$this->getTableIndex()} = $this->dbLink->lastInsertId();
727
    }
728
    
729 3
    protected function connectDB()
730
    {
731 3
        if (!$this->dbLink) {
732
            $this->dbLink = Suricate::Database();
0 ignored issues
show
Bug introduced by
The method Database() does not exist on Suricate\Suricate. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

732
            /** @scrutinizer ignore-call */ 
733
            $this->dbLink = Suricate::Database();
Loading history...
733
            if ($this->getDBConfig() !== '') {
734
                $this->dbLink->setConfig($this->getDBConfig());
735
            }
736
        }
737 3
    }
738
    
739
    
740
    protected function accessToProtectedVariable($name)
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

740
    protected function accessToProtectedVariable(/** @scrutinizer ignore-unused */ $name)

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

Loading history...
741
    {
742
        return false;
743
    }
744
745
    public function validate()
746
    {
747
        return true;
748
    }
749
750
    public function getValidatorMessages()
751
    {
752
        return $this->validatorMessages;
753
    }
754
}
755