Completed
Push — master ( 40aac0...525ff6 )
by Rougin
02:26
created

ObjectTrait::createObject()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 37
ccs 24
cts 24
cp 1
rs 8.439
cc 6
eloc 21
nc 10
nop 2
crap 6
1
<?php
2
3
namespace Rougin\Wildfire\Traits;
4
5
/**
6
 * Object Trait
7
 * 
8
 * @package Wildfire
9
 * @author  Rougin Royce Gutib <[email protected]>
10
 *
11
 * @property \Rougin\Describe\Describe $describe
12
 */
13
trait ObjectTrait
14
{
15
    /**
16
     * @var array
17
     */
18
    protected $tables = [];
19
20
    /**
21
     * Creates an object from the specified table and row.
22
     *
23
     * @param  string $table
24
     * @param  object $row
25
     * @return array
26
     */
27 15
    protected function createObject($table, $row)
28
    {
29 15
        $newTable = ucfirst(singular($table));
30 15
        $model = new $newTable;
31
32 15
        if ( ! array_key_exists($newTable, $this->tables)) {
33 15
            $tableInfo = $this->describe->getTable($newTable);
34
35 15
            $this->tables[$newTable] = $tableInfo;
36 15
        } else {
37 12
            $tableInfo = $this->tables[$newTable];
38
        }
39
40 15
        foreach ($row as $key => $value) {
41 15
            foreach ($tableInfo as $column) {
42 15
                if ($column->getField() != $key) {
43 15
                    continue;
44
                }
45
46 15
                $model->$key = $value;
47
48 15
                if ($column->isForeignKey()) {
49 15
                    $foreignColumn = $column->getReferencedField();
50 15
                    $foreignTable = $column->getReferencedTable();
51
52 15
                    $delimiters = [ $foreignColumn => $value ];
53 15
                    $foreignData = $this->find($foreignTable, $delimiters);
54
55 15
                    $newColumn = singular($foreignTable);
56
57 15
                    $model->$newColumn = $foreignData;
58 15
                }
59 15
            }
60 15
        }
61
62 15
        return $model;
63
    }
64
65
    /**
66
     * Finds the row from the specified ID or with the list of delimiters from
67
     * the specified table.
68
     *
69
     * @param  string         $table
70
     * @param  array|integer  $delimiters
71
     * @return object|boolean
72
     */
73
    abstract protected function find($table, $delimiters = []);
74
}
75