Passed
Push — develop ( ae181d...dce625 )
by Mathieu
01:47
created

DBObject::loadOrFail()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
ccs 0
cts 5
cp 0
crap 12
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 9
    public function __construct()
61
    {
62 9
        $this->setRelations();
63 9
    }
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 3
    public function __get($name)
78
    {
79 3
        if ($this->isDBVariable($name)) {
80 2
            return $this->getDBVariable($name);
81 1
        } elseif ($this->isProtectedVariable($name)) {
82
            return $this->getProtectedVariable($name);
83 1
        } elseif ($this->isRelation($name)) {
84
            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 2
    public function __set($name, $value)
104
    {
105 2
        if ($this->isDBVariable($name)) {
106 1
            $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 2
    }
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 1
    public function getTableName()
145
    {
146 1
        return $this->tableName;
147
    }
148
149 2
    public function getTableIndex()
150
    {
151 2
        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
    public function __wakeup()
177
    {
178
        $this->dbLink = false;
179
        $this->setRelations();
180
    }
181
    
182
    /**
183
     * @param string $name
184
     */
185 2
    private function getDBVariable($name)
186
    {
187 2
        if (isset($this->dbValues[$name])) {
188 2
            return $this->dbValues[$name];
189
        }
190
191 2
        return null;
192
    }
193
194
    /**
195
     * Check if variable is from DB
196
     * @param  string  $name variable name
197
     * @return boolean
198
     */
199 5
    public function isDBVariable($name)
200
    {
201 5
        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
    private function getRelation($name)
231
    {
232
        if (isset($this->relationValues[$name]) && $this->isRelationLoaded($name)) {
233
            return $this->relationValues[$name];
234
        }
235
236
        if (!$this->isRelationLoaded($name)) {
237
            if ($this->loadRelation($name)) {
238
                $this->markRelationAsLoaded($name);
239
            }
240
        }
241
242
        if (isset($this->relationValues[$name])) {
243
            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 4
    protected function isRelation($name)
255
    {
256 4
        return isset($this->relations[$name]);
257
    }
258
    /**
259
     * Define object relations
260
     *
261
     * @return DBObject
262
     */
263 8
    protected function setRelations()
264
    {
265 8
        $this->relations = [];
266
267 8
        return $this;
268
    }
269
270
    /**
271
     * Define object exported variables
272
     *
273
     * @return DBObject
274
     */
275
    protected function setExportedVariables()
276
    {
277
        if (count($this->exportedVariables)) {
278
            return $this;
279
        }
280
281
        $dbMappingExport = [];
282
        foreach ($this->dbVariables as $field) {
283
            $dbMappingExport[$field] = $field;
284
        }
285
        $this->exportedVariables = $dbMappingExport;
286
287
        return $this;
288
    }
289
290
    /**
291
     * Export DBObject to array
292
     *
293
     * @return array
294
     */
295
    public function toArray()
296
    {
297
        $this->setExportedVariables();
298
        $result = [];
299
        foreach ($this->exportedVariables as $sourceName => $destinationName) {
300
            $omitEmpty  = false;
301
            $castType   = null;
302
            if (strpos($destinationName, ',') !== false) {
303
                $splitted   = explode(',', $destinationName);
304
                array_map(function ($item) use (&$castType, &$omitEmpty) {
305
                    if ($item === 'omitempty') {
306
                        $omitEmpty = true;
307
                        return;
308
                    }
309
                    if (substr($item, 0, 5) === 'type:') {
310
                        $castType = substr($item, 5);
311
                    }
312
                }, $splitted);
313
314
                $destinationName = $splitted[0];
315
            }
316
317
            if ($destinationName === '-') {
318
                continue;
319
            }
320
321
            if ($omitEmpty && empty($this->$sourceName)) {
322
                continue;
323
            }
324
            $value = $this->$sourceName;
325
            if ($castType !== null) {
326
                settype($value, $castType);
327
            }
328
            $result[$destinationName] = $value;
329
        }
330
331
        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
    protected function markRelationAsLoaded($name)
362
    {
363
        if ($this->isRelation($name)) {
364
            $this->loadedRelations[$name] = true;
365
        }
366
    }
367
     /**
368
     * Check if a relation already have been loaded
369
     * @param  string  $name Variable name
370
     * @return boolean
371
     */
372
    protected function isRelationLoaded($name)
373
    {
374
        return isset($this->loadedRelations[$name]);
375
    }
376
377
    protected function loadRelation($name)
378
    {
379
        if (isset($this->relations[$name])) {
380
            switch ($this->relations[$name]['type']) {
381
                case self::RELATION_ONE_ONE:
382
                    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
    private function loadRelationOneOne($name)
394
    {
395
        $target = $this->relations[$name]['target'];
396
        $source = $this->relations[$name]['source'];
397
        $this->relationValues[$name] = new $target();
398
        $this->relationValues[$name]->load($this->$source);
399
        
400
        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
    private function resetLoadedVariables()
428
    {
429
        $this->loadedProtectedVariables = [];
430
        $this->loadedRelations          = [];
431
432
        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 4
    public function isProtectedVariable($name)
462
    {
463 4
        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
    public function load($id)
486
    {
487
        $this->connectDB();
488
        $this->resetLoadedVariables();
489
490
        if ($id != '') {
491
            $query  = "SELECT *";
492
            $query .= " FROM `" . $this->getTableName() ."`";
493
            $query .= " WHERE";
494
            $query .= "     `" . $this->getTableIndex() . "` =  :id";
495
            
496
            $params         = [];
497
            $params['id']   = $id;
498
499
            return $this->loadFromSql($query, $params);
500
        }
501
        
502
        return $this;
503
    }
504
505 1
    public function isLoaded()
506
    {
507 1
        return $this->{$this->getTableIndex()} !== null;
508
    }
509
510
    public function loadOrFail($id)
511
    {
512
        $this->load($id);
513
        if ($id == '' || $this->{$this->getTableIndex()} != $id) {
514
            throw (new Exception\ModelNotFoundException)->setModel(get_called_class());
515
        }
516
517
        return $this;
518
    }
519
520
    public static function loadOrCreate($arg)
521
    {
522
        $obj = static::loadOrInstanciate($arg);
523
        $obj->save();
524
525
        return $obj;
526
    }
527
528
    public static function loadOrInstanciate($arg)
529
    {
530
        $calledClass = get_called_class();
531
        $obj = new $calledClass;
532
        
533
        if (!is_array($arg)) {
534
            $arg = [$obj->getTableIndex() => $arg];
535
        }
536
        
537
538
        $sql = "SELECT *";
539
        $sql .= " FROM `" . $obj->getTableName() . "`";
540
        $sql .= " WHERE ";
541
542
        $sqlArray   = [];
543
        $params     = [];
544
        $i = 0;
545
        foreach ($arg as $key => $val) {
546
            if (is_null($val)) {
547
                $sqlArray[] = '`' . $key . '` IS :arg' . $i;
548
            } else {
549
                $sqlArray[] = '`' . $key . '`=:arg' . $i;
550
            }
551
            $params['arg' .$i] = $val;
552
            $i++;
553
        }
554
        $sql .= implode(' AND ', $sqlArray);
555
556
        if (!$obj->loadFromSql($sql, $params)) {
557
            foreach ($arg as $property => $value) {
558
                $obj->$property = $value;
559
            }
560
        }
561
562
        return $obj;
563
    }
564
    
565
    /**
566
     * @param string $sql
567
     */
568
    public function loadFromSql($sql, $sqlParams = [])
569
    {
570
        $this->connectDB();
571
        $this->resetLoadedVariables();
572
        
573
        $results = $this->dbLink->query($sql, $sqlParams)->fetch();
574
575
        if ($results !== false) {
576
            foreach ($results as $key => $value) {
577
                $this->$key = $value;
578
            }
579
580
            return $this;
581
        }
582
583
        return false;
584
    }
585
586
    /**
587
     * Construct an DBObject from an array
588
     * @param  array $data  associative array
589
     * @return DBObject       Built DBObject
590
     */
591
    public static function instanciate($data = [])
592
    {
593
        $calledClass    = get_called_class();
594
        $orm            = new $calledClass;
595
596
        return $orm->hydrate($data);
597
    }
598
599 1
    public function hydrate($data = [])
600
    {
601 1
        foreach ($data as $key => $val) {
602 1
            if ($this->propertyExists($key)) {
603 1
                $this->$key = $val;
604
            }
605
        }
606
607 1
        return $this;
608
    }
609
610
    public static function create($data = [])
611
    {
612
        $obj = static::instanciate($data);
613
        $obj->save();
614
615
        return $obj;
616
    }
617
    
618
    /**
619
     * Delete record from SQL Table
620
     *
621
     * Delete record link to current object, according SQL Table unique id
622
     * @return null
623
     */
624
    public function delete()
625
    {
626
        $this->connectDB();
627
628
        if ($this->getTableIndex() !== '') {
629
            $query  = "DELETE FROM `" . $this->getTableName() . "`";
630
            $query .= " WHERE `" . $this->getTableIndex() . "` = :id";
631
632
            $queryParams = [];
633
            $queryParams['id'] = $this->{$this->getTableIndex()};
634
            
635
            $this->dbLink->query($query, $queryParams);
636
        }
637
    }
638
    
639
    /**
640
     * Save current object into db
641
     *
642
     * Call INSERT or UPDATE if unique index is set
643
     * @param  boolean $forceInsert true to force insert instead of update
644
     * @return null
645
     */
646
    public function save($forceInsert = false)
647
    {
648
        if (count($this->dbValues)) {
649
            $this->connectDB();
650
651
            if ($this->{$this->getTableIndex()} != '' && !$forceInsert) {
652
                $this->update();
653
                $insert = false;
654
            } else {
655
                $this->insert();
656
                $insert = true;
657
            }
658
659
            // Checking protected variables
660
            foreach ($this->protectedVariables as $variable) {
661
                // only if current protected_var is set
662
                if (isset($this->protectedValues[$variable]) && $this->isProtectedVariableLoaded($variable)) {
663
                    if ($this->protectedValues[$variable] instanceof Interfaces\ICollection) {
664
                        if ($insert) {
665
                            $this->protectedValues[$variable]->setParentIdForAll($this->{$this->getTableIndex()});
666
                        }
667
                        $this->protectedValues[$variable]->save();
668
                    }
669
                }
670
            }
671
        } else {
672
            throw new \RuntimeException("Object " . get_called_class() . " has no properties to save");
673
        }
674
    }
675
676
    /**
677
     * UPDATE current object into database
678
     * @return null
679
     */
680
    private function update()
681
    {
682
        $this->connectDB();
683
684
        $sqlParams = [];
685
686
        $sql  = 'UPDATE `' . $this->getTableName() . '`';
687
        $sql .= ' SET ';
688
        
689
690
        foreach ($this->dbValues as $key => $val) {
691
            if (!in_array($key, $this->readOnlyVariables)) {
692
                $sql .= ' `' . $key . '`=:' . $key .', ';
693
                $sqlParams[$key] = $val;
694
            }
695
        }
696
        $sql  = substr($sql, 0, -2);
697
        $sql .= " WHERE `" . $this->getTableIndex() . "` = :SuricateTableIndex";
698
699
        $sqlParams[':SuricateTableIndex'] = $this->{$this->getTableIndex()};
700
701
        $this->dbLink->query($sql, $sqlParams);
702
    }
703
704
    /**
705
     * INSERT current object into database
706
     * @access  private
707
     * @return null
708
     */
709
    private function insert()
710
    {
711
        $this->connectDB();
712
        
713
        $variables = array_diff($this->dbVariables, $this->readOnlyVariables);
714
715
        $sql  = 'INSERT INTO `' . $this->getTableName() . '`';
716
        $sql .= '(`';
717
        $sql .= implode('`, `', $variables);
718
        $sql .= '`)';
719
        $sql .= ' VALUES (:';
720
        $sql .= implode(', :', $variables);
721
        $sql .= ')';
722
723
        $sqlParams = [];
724
        foreach ($variables as $field) {
725
            $sqlParams[':' . $field] = $this->$field;
726
        }
727
        
728
        $this->dbLink->query($sql, $sqlParams);
729
730
        $this->{$this->getTableIndex()} = $this->dbLink->lastInsertId();
731
    }
732
    
733
    protected function connectDB()
734
    {
735
        if (!$this->dbLink) {
736
            $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

736
            /** @scrutinizer ignore-call */ 
737
            $this->dbLink = Suricate::Database();
Loading history...
737
            if ($this->getDBConfig() !== '') {
738
                $this->dbLink->setConfig($this->getDBConfig());
739
            }
740
        }
741
    }
742
    
743
    
744
    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

744
    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...
745
    {
746
        return false;
747
    }
748
749
    public function validate()
750
    {
751
        return true;
752
    }
753
754
    public function getValidatorMessages()
755
    {
756
        return $this->validatorMessages;
757
    }
758
}
759