Completed
Push — master ( b6f100...5caed9 )
by Rougin
03:04
created

Wildfire::setQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Rougin\Wildfire;
4
5
use Rougin\Describe\Describe;
6
use Rougin\SparkPlug\Instance;
7
use Rougin\Describe\Driver\CodeIgniterDriver;
8
9
/**
10
 * Wildfire
11
 *
12
 * Yet another wrapper for CodeIgniter's Query Builder Class.
13
 * 
14
 * @package Wildfire
15
 * @author  Rougin Royce Gutib <[email protected]>
16
 */
17
class Wildfire
18
{
19
    /**
20
     * @var CI_DB
21
     */
22
    protected $db;
23
24
    /**
25
     * @var \Rougin\Describe\Describe
26
     */
27
    protected $describe;
28
29
    /**
30
     * @var CI_DB_result
31
     */
32
    protected $query;
33
34
    /**
35
     * @var string
36
     */
37
    protected $table = '';
38
39
    /**
40
     * @var array
41
     */
42
    protected $tables = [];
43
44
    /**
45
     * @param CI_DB|null        $database
46
     * @param CI_DB_result|null $query
47
     */
48 21
    public function __construct($database = null, $query = null)
49
    {
50 21
        $config = [];
51
52 21
        if (empty($database)) {
53 3
            $ci = Instance::create();
54
55 3
            $ci->load->database();
0 ignored issues
show
Bug introduced by
The property load does not seem to exist in CI_Controller.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
56
57 3
            $database = $ci->db;
0 ignored issues
show
Bug introduced by
The property db does not seem to exist in CI_Controller.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
58 3
        }
59
60 21
        $this->db = $database;
61 21
        $this->query = $query;
62
63 21
        $config['default'] = [
64 21
            'dbdriver' => $database->dbdriver,
65 21
            'hostname' => $database->hostname,
66 21
            'username' => $database->username,
67 21
            'password' => $database->password,
68 21
            'database' => $database->database
69 21
        ];
70
71 21
        if (empty($config['default']['hostname'])) {
72 21
            $config['default']['hostname'] = $database->dsn;
73 21
        }
74
75 21
        $driver = new CodeIgniterDriver($config);
76 21
        $this->describe = new Describe($driver);
77 21
    }
78
79
    /**
80
     * Lists all data in dropdown format.
81
     *
82
     * @param  string $description
83
     * @return array
84
     */
85 3
    public function asDropdown($description = 'description')
86
    {
87 3
        $data = [];
88 3
        $id = $this->describe->getPrimaryKey($this->table);
89
90 3
        $result = $this->query->result();
91
92 3
        foreach ($result as $row) {
93 3
            $data[$row->$id] = ucwords($row->$description);
94 3
        }
95
96 3
        return $data;
97
    }
98
99
    /**
100
     * Finds the row from the specified ID or with the list of delimiters from
101
     * the specified table.
102
     *
103
     * @param  string         $table
104
     * @param  array|integer  $delimiters
105
     * @return object|boolean
106
     */
107 18
    public function find($table, $delimiters = [])
108
    {
109 18
        if ( ! is_array($delimiters)) {
110 6
            $primaryKey = $this->describe->getPrimaryKey($table);
111
112 6
            $delimiters = [ $primaryKey => $delimiters ];
113 6
        }
114
115 18
        $this->db->where($delimiters);
116
117 18
        $query = $this->db->get($table);
118
119 18
        if ($query->num_rows() > 0) {
120 15
            return $this->createObject($table, $query->row());
121
        }
122
123 3
        return false;
124
    }
125
126
    /**
127
     * Return all rows from the specified table.
128
     * 
129
     * @param  string $table
130
     * @return self
131
     */
132 15
    public function get($table = '')
133
    {
134 15
        if ($this->query == null) {
135 9
            $this->query = $this->db->get($table);
136 9
        }
137
138 15
        $this->table = $table;
139
140
        // Guess the specified table from the query
141 15
        if (empty($table)) {
142 6
            $query = $this->db->last_query();
143
144 6
            preg_match('/\bfrom\b\s*(\w+)/i', $query, $matches);
145
146 6
            $this->table = $matches[1];
147 6
        }
148
149 15
        return $this;
150
    }
151
152
    /**
153
     * Return the result
154
     * 
155
     * @return object
156
     */
157 12
    public function result()
158
    {
159 12
        $data = $this->getQueryResult();
160 12
        $result = [];
161
162 12
        if (empty($this->table)) {
163 6
            $this->get();
164 6
        }
165
166 12
        foreach ($data as $row)
167
        {
168 12
            $object = $this->createObject($this->table, $row);
169
170 12
            array_push($result, $object);
171 12
        }
172
173 12
        return $result;
174
    }
175
176
    /**
177
     * Sets the database class.
178
     * 
179
     * @param  CI_DB $database
180
     * @return self
181
     */
182 3
    public function setDatabase($database)
183
    {
184 3
        $this->db = $database;
185
186 3
        return $this;
187
    }
188
189
    /**
190
     * Sets the query result.
191
     * 
192
     * @param  CI_DB_result $query
193
     * @return self
194
     */
195 3
    public function setQuery($query)
196
    {
197 3
        $this->query = $query;
198
199 3
        return $this;
200
    }
201
202
    /**
203
     * Create an object from the specified data
204
     *
205
     * @param  string $table
206
     * @param  object $row
207
     * @return array
208
     */
209 15
    protected function createObject($table, $row)
210
    {
211 15
        $newTable = ucfirst(Inflector::singular($table));
212 15
        $model = new $newTable;
213
214 15
        if ( ! array_key_exists($table, $this->tables)) {
215 15
            $tableInfo = $this->describe->getTable($table);
216
217 15
            $this->tables[$table] = $tableInfo;
218 15
        } else {
219 12
            $tableInfo = $this->tables[$table];
220
        }
221
222 15
        foreach ($row as $key => $value) {
223 15
            foreach ($tableInfo as $column) {
224 15
                if ($column->getField() != $key) {
225 15
                    continue;
226
                }
227
228 15
                $model->$key = $value;
229 15
            }
230 15
        }
231
232 15
        foreach ($row as $key => $value) {
233 15
            foreach ($tableInfo as $column) {
234 15
                if ($column->getField() != $key || ! $column->isForeignKey()) {
235 15
                    continue;
236
                }
237
238 15
                $foreignColumn = $column->getReferencedField();
239 15
                $foreignTable = $column->getReferencedTable();
240
241 15
                $delimiters = [ $foreignColumn => $value ];
242 15
                $foreignData = $this->find($foreignTable, $delimiters);
243
244 15
                $newColumn = Inflector::singular($foreignTable);
245
246 15
                $model->$newColumn = $foreignData;
247 15
            }
248 15
        }
249
250 15
        return $model;
251
    }
252
253
    /**
254
     * Gets the data result from the specified query.
255
     * 
256
     * @return array|object
257
     */
258 12
    protected function getQueryResult()
259
    {
260 12
        $result = $this->query;
261
262 12
        if (method_exists($this->query, 'result')) {
263 12
            $result = $this->query->result();
264 12
        }
265
266 12
        return $result;
267
    }
268
269
    /**
270
     * Calls methods from this class in underscore case.
271
     * 
272
     * @param  string $method
273
     * @param  mixed  $parameters
274
     * @return mixed
275
     */
276 9
    public function __call($method, $parameters) {
277 9
        $method = Inflector::camelize($method);
278 9
        $result = $this;
279
280 9
        if (method_exists($this, $method)) {
281 9
            $class = [$this, $method];
282
            
283 9
            $result = call_user_func_array($class, $parameters);
284 9
        }
285
286 9
        return $result;
287
    }
288
}
289