Completed
Push — master ( 1b9d57...dae4e0 )
by Rougin
05:11
created

Wildfire::as_dropdown()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Rougin\Wildfire;
4
5
use Rougin\Describe\Describe;
6
use Rougin\Describe\Driver\CodeIgniterDriver;
7
8
/**
9
 * Wildfire
10
 *
11
 * Yet another wrapper for CodeIgniter's Query Builder Class.
12
 * 
13
 * @package Wildfire
14
 * @author  Rougin Royce Gutib <[email protected]>
15
 */
16
class Wildfire
17
{
18
    /**
19
     * @var CI_DB
20
     */
21
    protected $db;
22
23
    /**
24
     * @var \Rougin\Describe\Describe
25
     */
26
    protected $describe;
27
28
    /**
29
     * @var CI_DB
30
     */
31
    protected $query;
32
33
    /**
34
     * @var string
35
     */
36
    protected $table = '';
37
38
    /**
39
     * @var array
40
     */
41
    protected $tables = [];
42
43
    /**
44
     * @param CI_DB      $database
45
     * @param CI_DB|null $query
46
     */
47 15
    public function __construct($database, $query = null)
48
    {
49 15
        $config = [];
50
51 15
        $this->db = $database;
52 15
        $this->query = $query;
53
54 15
        $config['default'] = [
55 15
            'dbdriver' => $database->dbdriver,
56 15
            'hostname' => $database->hostname,
57 15
            'username' => $database->username,
58 15
            'password' => $database->password,
59 15
            'database' => $database->database
60 15
        ];
61
62 15
        if (empty($config['default']['hostname'])) {
63 15
            $config['default']['hostname'] = $database->dsn;
64 15
        }
65
66 15
        $driver = new CodeIgniterDriver($config);
67 15
        $this->describe = new Describe($driver);
68 15
    }
69
70
    /**
71
     * Lists all data in dropdown format.
72
     *
73
     * @param  string $description
74
     * @return array
75
     */
76 3
    public function as_dropdown($description = 'description')
77
    {
78 3
        $data = [];
79 3
        $id = $this->describe->getPrimaryKey($this->table);
80
81 3
        $result = $this->query->result();
82
83 3
        foreach ($result as $row) {
84 3
            $data[$row->$id] = ucwords($row->$description);
85 3
        }
86
87 3
        return $data;
88
    }
89
90
    /**
91
     * Finds the row from the specified ID or with the list of delimiters from
92
     * the specified table.
93
     *
94
     * @param  string         $table
95
     * @param  array|integer  $delimiters
96
     * @return object|boolean
97
     */
98 12
    public function find($table, $delimiters = [])
99
    {
100 12
        if ( ! is_array($delimiters)) {
101 6
            $primaryKey = $this->describe->getPrimaryKey($table);
102
103 6
            $delimiters = [ $primaryKey => $delimiters ];
104 6
        }
105
106 12
        $this->db->where($delimiters);
107
108 12
        $query = $this->db->get($table);
109
110 12
        if ($query->num_rows() > 0) {
111 9
            return $this->createObject($table, $query->row());
112
        }
113
114 3
        return false;
115
    }
116
117
    /**
118
     * Return all rows from the specified table.
119
     * 
120
     * @param  string $table
121
     * @return self
122
     */
123 9
    public function get($table = '')
124
    {
125 9
        if ($this->query == null) {
126 6
            $this->query = $this->db->get($table);
127 6
        }
128
129 9
        $this->table = $table;
130
131
        // Guess the specified table from the query
132 9
        if (empty($table)) {
133 3
            $query = $this->db->last_query();
134
135 3
            preg_match('/\bfrom\b\s*(\w+)/i', $query, $matches);
136
137 3
            $this->table = $matches[1];
138 3
        }
139
140 9
        return $this;
141
    }
142
143
    /**
144
     * Return the result
145
     * 
146
     * @return object
147
     */
148 6
    public function result()
149
    {
150 6
        $data = $this->getQueryResult();
151 6
        $result = [];
152
153 6
        if (empty($this->table)) {
154 3
            $this->get();
155 3
        }
156
157 6
        foreach ($data as $row)
158
        {
159 6
            $object = $this->createObject($this->table, $row);
160
161 6
            array_push($result, $object);
162 6
        }
163
164 6
        return $result;
165
    }
166
167
    /**
168
     * Create an object from the specified data
169
     *
170
     * @param  string $table
171
     * @param  object $row
172
     * @return array
173
     */
174 9
    protected function createObject($table, $row)
175
    {
176 9
        $table = $this->stripTableSchema($table);
177 9
        $newTable = ucfirst(Inflector::singular($table));
178 9
        $model = new $newTable;
179
180 9
        if ( ! array_key_exists($table, $this->tables)) {
181 9
            $tableInfo = $this->describe->getTable($table);
182
183 9
            $this->tables[$table] = $tableInfo;
184 9
        } else {
185 6
            $tableInfo = $this->tables[$table];
186
        }
187
188 9
        foreach ($row as $key => $value) {
189 9
            foreach ($tableInfo as $column) {
190 9
                if ($column->getField() != $key) {
191 9
                    continue;
192
                }
193
194 9
                $model->$key = $value;
195 9
            }
196 9
        }
197
198 9
        foreach ($row as $key => $value) {
199 9
            foreach ($tableInfo as $column) {
200 9
                if ($column->getField() != $key || ! $column->isForeignKey()) {
201 9
                    continue;
202
                }
203
204 9
                $foreignColumn = $column->getReferencedField();
205 9
                $foreignTable = $column->getReferencedTable();
206
207 9
                $delimiters = [ $foreignColumn => $value ];
208 9
                $foreignData = $this->find($foreignTable, $delimiters);
209
210 9
                $foreignTable = $this->stripTableSchema($foreignTable);
211 9
                $newColumn = Inflector::singular($foreignTable);
212
213 9
                $model->$newColumn = $foreignData;
214 9
            }
215 9
        }
216
217 9
        return $model;
218
    }
219
220
    /**
221
     * Gets the data result from the specified query.
222
     * 
223
     * @return array|object
224
     */
225 6
    protected function getQueryResult()
226
    {
227 6
        $result = $this->query;
228
229 6
        if (method_exists($this->query, 'result')) {
230 6
            $result = $this->query->result();
231 6
        }
232
233 6
        return $result;
234
    }
235
236
    /**
237
     * Strips the table schema from the table name.
238
     * 
239
     * @param  string $table
240
     * @return string
241
     */
242 9
    protected function stripTableSchema($table)
243
    {
244 9
        if (strpos($table, '.') !== false) {
245
            return substr($table, strpos($table, '.') + 1);
246
        }
247
248 9
        return $table;
249
    }
250
}
251