Completed
Push — v2 ( d9a4e1...8ef8ed )
by Berend
49:49 queued 46:53
created
src/AbstractActiveRecord.php 2 patches
Indentation   +742 added lines, -742 removed lines patch added patch discarded remove patch
@@ -18,752 +18,752 @@
 block discarded – undo
18 18
  */
19 19
 abstract class AbstractActiveRecord implements ActiveRecordInterface
20 20
 {
21
-	const COLUMN_NAME_ID = 'id';
22
-	const COLUMN_TYPE_ID = 'INT UNSIGNED';
23
-
24
-	/** @var \PDO The PDO object. */
25
-	protected $pdo;
26
-
27
-	/** @var null|int The ID. */
28
-	private $id;
29
-
30
-	/** @var array A map of column name to functions that hook the insert function */
31
-	protected $registeredCreateHooks;
32
-
33
-	/** @var array A map of column name to functions that hook the read function */
34
-	protected $registeredReadHooks;
35
-
36
-	/** @var array A map of column name to functions that hook the update function */
37
-	protected $registeredUpdateHooks;
38
-
39
-	/** @var array A map of column name to functions that hook the update function */
40
-	protected $registeredDeleteHooks;	
41
-
42
-	/** @var array A map of column name to functions that hook the search function */
43
-	protected $registeredSearchHooks;
44
-
45
-	/** @var array A list of table column definitions */
46
-	protected $tableDefinition;
47
-
48
-	/**
49
-	 * Construct an abstract active record with the given PDO.
50
-	 *
51
-	 * @param \PDO $pdo
52
-	 */
53
-	public function __construct(\PDO $pdo)
54
-	{
55
-		$pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
56
-		$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
57
-
58
-		$this->setPdo($pdo);
59
-		$this->tableDefinition = $this->getActiveRecordTableDefinition();
60
-		$this->registeredCreateHooks = [];
61
-		$this->registeredReadHooks = [];
62
-		$this->registeredUpdateHooks = [];
63
-		$this->registeredDeleteHooks = [];
64
-		$this->registeredSearchHooks = [];
65
-
66
-		// Extend table definition with default ID field, throw exception if field already exists
67
-		if (array_key_exists('id', $this->tableDefinition)) {
68
-			$message = "Table definition in record contains a field with name \"id\"";
69
-			$message .= ", which is a reserved name by ActiveRecord";
70
-			throw new ActiveRecordException($message, 0);
71
-		}
72
-
73
-		$this->tableDefinition[self::COLUMN_NAME_ID] =
74
-		[
75
-			'value' => &$this->id,
76
-			'validate' => null,
77
-			'type' => self::COLUMN_TYPE_ID,
78
-			'properties' => ColumnProperty::NOT_NULL | ColumnProperty::IMMUTABLE | ColumnProperty::AUTO_INCREMENT | ColumnProperty::PRIMARY_KEY
79
-		];
80
-	}
81
-
82
-	/**
83
-	 * Register a new hook for a specific column that gets called before execution of the create() method
84
-	 * Only one hook per column can be registered at a time
85
-	 * @param string $columnName The name of the column that is registered.
86
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
87
-	 */
88
-	public function registerCreateHook($columnName, $fn) 
89
-	{
90
-		// Check whether column exists
91
-		if (!array_key_exists($columnName, $this->tableDefinition)) 
92
-		{
93
-			throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
94
-		}
95
-
96
-		// Enforcing 1 hook per table column
97
-		if (array_key_exists($columnName, $this->registeredCreateHooks)) {
98
-			$message = "Hook is trying to register on an already registered column \"$columnName\", ";
99
-			$message .= "do you have conflicting traits?";
100
-			throw new ActiveRecordException($message, 0);
101
-		}
102
-
103
-		if (is_string($fn) && is_callable([$this, $fn])) {
104
-			$this->registeredCreateHooks[$columnName] = [$this, $fn];
105
-		} else if (is_callable($fn)) {
106
-			$this->registeredCreateHooks[$columnName] = $fn;
107
-		} else {
108
-			throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
109
-		}
110
-	}
111
-
112
-	/**
113
-	 * Register a new hook for a specific column that gets called before execution of the read() method
114
-	 * Only one hook per column can be registered at a time
115
-	 * @param string $columnName The name of the column that is registered.
116
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
117
-	 */
118
-	public function registerReadHook($columnName, $fn)
119
-	{
120
-		// Check whether column exists
121
-		if (!array_key_exists($columnName, $this->tableDefinition)) 
122
-		{
123
-			throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
124
-		}
125
-
126
-		// Enforcing 1 hook per table column
127
-		if (array_key_exists($columnName, $this->registeredReadHooks)) {
128
-			$message = "Hook is trying to register on an already registered column \"$columnName\", ";
129
-			$message .= "do you have conflicting traits?";
130
-			throw new ActiveRecordException($message, 0);
131
-		}
132
-
133
-		if (is_string($fn) && is_callable([$this, $fn])) {
134
-			$this->registeredReadHooks[$columnName] = [$this, $fn];
135
-		} else if (is_callable($fn)) {
136
-			$this->registeredReadHooks[$columnName] = $fn;
137
-		} else {
138
-			throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * Register a new hook for a specific column that gets called before execution of the update() method
144
-	 * Only one hook per column can be registered at a time
145
-	 * @param string $columnName The name of the column that is registered.
146
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
147
-	 */
148
-	public function registerUpdateHook($columnName, $fn)
149
-	{
150
-		// Check whether column exists
151
-		if (!array_key_exists($columnName, $this->tableDefinition)) 
152
-		{
153
-			throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
154
-		}
155
-
156
-		// Enforcing 1 hook per table column
157
-		if (array_key_exists($columnName, $this->registeredUpdateHooks)) {
158
-			$message = "Hook is trying to register on an already registered column \"$columnName\", ";
159
-			$message .= "do you have conflicting traits?";
160
-			throw new ActiveRecordException($message, 0);
161
-		}
162
-
163
-		if (is_string($fn) && is_callable([$this, $fn])) {
164
-			$this->registeredUpdateHooks[$columnName] = [$this, $fn];
165
-		} else if (is_callable($fn)) {
166
-			$this->registeredUpdateHooks[$columnName] = $fn;
167
-		} else {
168
-			throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
169
-		}
170
-	}
171
-
172
-	/**
173
-	 * Register a new hook for a specific column that gets called before execution of the delete() method
174
-	 * Only one hook per column can be registered at a time
175
-	 * @param string $columnName The name of the column that is registered.
176
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
177
-	 */
178
-	public function registerDeleteHook($columnName, $fn)
179
-	{
180
-		// Check whether column exists
181
-		if (!array_key_exists($columnName, $this->tableDefinition)) 
182
-		{
183
-			throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
184
-		}
185
-
186
-		// Enforcing 1 hook per table column
187
-		if (array_key_exists($columnName, $this->registeredDeleteHooks)) {
188
-			$message = "Hook is trying to register on an already registered column \"$columnName\", ";
189
-			$message .= "do you have conflicting traits?";
190
-			throw new ActiveRecordException($message, 0);
191
-		}
192
-
193
-		if (is_string($fn) && is_callable([$this, $fn])) {
194
-			$this->registeredDeleteHooks[$columnName] = [$this, $fn];
195
-		} else if (is_callable($fn)) {
196
-			$this->registeredDeleteHooks[$columnName] = $fn;
197
-		} else {
198
-			throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
199
-		}
200
-	}
201
-
202
-	/**
203
-	 * Register a new hook for a specific column that gets called before execution of the search() method
204
-	 * Only one hook per column can be registered at a time
205
-	 * @param string $columnName The name of the column that is registered.
206
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object. The callable is required to take one argument: an instance of miBadger\Query\Query; 
207
-	 */
208
-	public function registerSearchHook($columnName, $fn)
209
-	{
210
-		// Check whether column exists
211
-		if (!array_key_exists($columnName, $this->tableDefinition)) 
212
-		{
213
-			throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
214
-		}
215
-
216
-		// Enforcing 1 hook per table column
217
-		if (array_key_exists($columnName, $this->registeredSearchHooks)) {
218
-			$message = "Hook is trying to register on an already registered column \"$columnName\", ";
219
-			$message .= "do you have conflicting traits?";
220
-			throw new ActiveRecordException($message, 0);
221
-		}
222
-
223
-		if (is_string($fn) && is_callable([$this, $fn])) {
224
-			$this->registeredSearchHooks[$columnName] = [$this, $fn];
225
-		} else if (is_callable($fn)) {
226
-			$this->registeredSearchHooks[$columnName] = $fn;
227
-		} else {
228
-			throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * Adds a new column definition to the table.
234
-	 * @param string $columnName The name of the column that is registered.
235
-	 * @param Array $definition The definition of that column.
236
-	 */
237
-	public function extendTableDefinition($columnName, $definition)
238
-	{
239
-		if ($this->tableDefinition === null) {
240
-			throw new ActiveRecordException("tableDefinition is null, most likely due to parent class not having been initialized in constructor");
241
-		}
242
-
243
-		// Enforcing table can only be extended with new columns
244
-		if (array_key_exists($columnName, $this->tableDefinition)) {
245
-			$message = "Table is being extended with a column that already exists, ";
246
-			$message .= "\"$columnName\" conflicts with your table definition";
247
-			throw new ActiveRecordException($message, 0);
248
-		}
249
-
250
-		$this->tableDefinition[$columnName] = $definition;
251
-	}
252
-
253
-	/**
254
-	 * Returns the type string as it should appear in the mysql create table statement for the given column
255
-	 * @return string The type string
256
-	 */
257
-	private function getDatabaseTypeString($colName, $type, $length)
258
-	{
259
-		if ($type === null) 
260
-		{
261
-			throw new ActiveRecordException(sprintf("Column %s has invalid type \"NULL\"", $colName));
262
-		}
263
-
264
-		switch (strtoupper($type)) {
265
-			case 'DATETIME':
266
-			case 'DATE':
267
-			case 'TIME':
268
-			case 'TEXT':
269
-			case 'INT UNSIGNED':
270
-				return $type;
271
-
272
-			case 'VARCHAR':
273
-				if ($length === null) {
274
-					throw new ActiveRecordException(sprintf("field type %s requires specified column field \"LENGTH\"", $colName));
275
-				} else {
276
-					return sprintf('%s(%d)', $type, $length);	
277
-				}
278
-
279
-			case 'INT':
280
-			case 'TINYINT':
281
-			case 'BIGINT':
282
-			default: 	
283
-			// @TODO(Default): throw exception, or implicitly assume that type is correct? (For when using SQL databases with different types)
284
-				if ($length === null) {
285
-					return $type;
286
-				} else {
287
-					return sprintf('%s(%d)', $type, $length);	
288
-				}
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * Builds the part of a MySQL create table statement that corresponds to the supplied column
294
-	 * @param string $colName 	Name of the database column
295
-	 * @param string $type 		The type of the string
296
-	 * @param int $properties 	The set of Column properties that apply to this column (See ColumnProperty for options)
297
-	 * @return string
298
-	 */
299
-	private function buildCreateTableColumnEntry($colName, $type, $length, $properties, $default)
300
-	{
301
-
302
-		$stmnt = sprintf('`%s` %s ', $colName, $this->getDatabaseTypeString($colName, $type, $length));
303
-		if ($properties & ColumnProperty::NOT_NULL) {
304
-			$stmnt .= 'NOT NULL ';
305
-		} else {
306
-			$stmnt .= 'NULL ';
307
-		}
308
-
309
-		if ($default !== NULL) {
310
-			$stmnt .= ' DEFAULT ' . $default . ' ';
311
-		}
312
-
313
-		if ($properties & ColumnProperty::AUTO_INCREMENT) {
314
-			$stmnt .= 'AUTO_INCREMENT ';
315
-		}
316
-
317
-		if ($properties & ColumnProperty::UNIQUE) {
318
-			$stmnt .= 'UNIQUE ';
319
-		}
320
-
321
-		if ($properties & ColumnProperty::PRIMARY_KEY) {
322
-			$stmnt .= 'PRIMARY KEY ';
323
-		}
324
-
325
-		return $stmnt;
326
-	}
327
-
328
-	/**
329
-	 * Sorts the column statement components in the order such that the id appears first, 
330
-	 * 		followed by all other columns in alphabetical ascending order
331
-	 * @param   Array $colStatements Array of column statements
332
-	 * @return  Array
333
-	 */
334
-	private function sortColumnStatements($colStatements)
335
-	{
336
-		// Find ID statement and put it first
337
-		$sortedStatements = [];
338
-
339
-		$sortedStatements[] = $colStatements[self::COLUMN_NAME_ID];
340
-		unset($colStatements[self::COLUMN_NAME_ID]);
341
-
342
-		// Sort remaining columns in alphabetical order
343
-		$columns = array_keys($colStatements);
344
-		sort($columns);
345
-		foreach ($columns as $colName) {
346
-			$sortedStatements[] = $colStatements[$colName];
347
-		}
348
-
349
-		return $sortedStatements;
350
-	}
351
-
352
-	/**
353
-	 * Builds the MySQL Create Table statement for the internal table definition
354
-	 * @return string
355
-	 */
356
-	public function buildCreateTableSQL()
357
-	{
358
-		$columnStatements = [];
359
-		foreach ($this->tableDefinition as $colName => $definition) {
360
-			// Destructure column definition
361
-			$type    = $definition['type'] ?? null;
362
-			$default = $definition['default'] ?? null;
363
-			$length  = $definition['length'] ?? null;
364
-			$properties = $definition['properties'] ?? null;
365
-
366
-			if (isset($definition['relation']) && $type !== null) {
367
-				$msg = "Column \"$colName\": ";
368
-				$msg .= "Relationship columns have an automatically inferred type, so type should be omitted";
369
-				throw new ActiveRecordException($msg);
370
-			} else if (isset($definition['relation'])) {
371
-				$type = self::COLUMN_TYPE_ID;
372
-			}
373
-
374
-			$columnStatements[$colName] = $this->buildCreateTableColumnEntry($colName, $type, $length, $properties, $default);
375
-		}
376
-
377
-		// Sort table (first column is id, the remaining are alphabetically sorted)
378
-		$columnStatements = $this->sortColumnStatements($columnStatements);
379
-
380
-		$sql = 'CREATE TABLE ' . $this->getActiveRecordTable() . ' ';
381
-		$sql .= "(\n";
382
-		$sql .= join($columnStatements, ",\n");
383
-		$sql .= "\n);";
384
-
385
-		return $sql;
386
-	}
387
-
388
-	/**
389
-	 * Creates the entity as a table in the database
390
-	 */
391
-	public function createTable()
392
-	{
393
-		$this->pdo->query($this->buildCreateTableSQL());
394
-	}
395
-
396
-	/**
397
-	 * builds a MySQL constraint statement for the given parameters
398
-	 * @param string $parentTable
399
-	 * @param string $parentColumn
400
-	 * @param string $childTable
401
-	 * @param string $childColumn
402
-	 * @return string The MySQL table constraint string
403
-	 */
404
-	protected function buildConstraint($parentTable, $parentColumn, $childTable, $childColumn)
405
-	{
406
-		$template = <<<SQL
21
+    const COLUMN_NAME_ID = 'id';
22
+    const COLUMN_TYPE_ID = 'INT UNSIGNED';
23
+
24
+    /** @var \PDO The PDO object. */
25
+    protected $pdo;
26
+
27
+    /** @var null|int The ID. */
28
+    private $id;
29
+
30
+    /** @var array A map of column name to functions that hook the insert function */
31
+    protected $registeredCreateHooks;
32
+
33
+    /** @var array A map of column name to functions that hook the read function */
34
+    protected $registeredReadHooks;
35
+
36
+    /** @var array A map of column name to functions that hook the update function */
37
+    protected $registeredUpdateHooks;
38
+
39
+    /** @var array A map of column name to functions that hook the update function */
40
+    protected $registeredDeleteHooks;	
41
+
42
+    /** @var array A map of column name to functions that hook the search function */
43
+    protected $registeredSearchHooks;
44
+
45
+    /** @var array A list of table column definitions */
46
+    protected $tableDefinition;
47
+
48
+    /**
49
+     * Construct an abstract active record with the given PDO.
50
+     *
51
+     * @param \PDO $pdo
52
+     */
53
+    public function __construct(\PDO $pdo)
54
+    {
55
+        $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
56
+        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
57
+
58
+        $this->setPdo($pdo);
59
+        $this->tableDefinition = $this->getActiveRecordTableDefinition();
60
+        $this->registeredCreateHooks = [];
61
+        $this->registeredReadHooks = [];
62
+        $this->registeredUpdateHooks = [];
63
+        $this->registeredDeleteHooks = [];
64
+        $this->registeredSearchHooks = [];
65
+
66
+        // Extend table definition with default ID field, throw exception if field already exists
67
+        if (array_key_exists('id', $this->tableDefinition)) {
68
+            $message = "Table definition in record contains a field with name \"id\"";
69
+            $message .= ", which is a reserved name by ActiveRecord";
70
+            throw new ActiveRecordException($message, 0);
71
+        }
72
+
73
+        $this->tableDefinition[self::COLUMN_NAME_ID] =
74
+        [
75
+            'value' => &$this->id,
76
+            'validate' => null,
77
+            'type' => self::COLUMN_TYPE_ID,
78
+            'properties' => ColumnProperty::NOT_NULL | ColumnProperty::IMMUTABLE | ColumnProperty::AUTO_INCREMENT | ColumnProperty::PRIMARY_KEY
79
+        ];
80
+    }
81
+
82
+    /**
83
+     * Register a new hook for a specific column that gets called before execution of the create() method
84
+     * Only one hook per column can be registered at a time
85
+     * @param string $columnName The name of the column that is registered.
86
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
87
+     */
88
+    public function registerCreateHook($columnName, $fn) 
89
+    {
90
+        // Check whether column exists
91
+        if (!array_key_exists($columnName, $this->tableDefinition)) 
92
+        {
93
+            throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
94
+        }
95
+
96
+        // Enforcing 1 hook per table column
97
+        if (array_key_exists($columnName, $this->registeredCreateHooks)) {
98
+            $message = "Hook is trying to register on an already registered column \"$columnName\", ";
99
+            $message .= "do you have conflicting traits?";
100
+            throw new ActiveRecordException($message, 0);
101
+        }
102
+
103
+        if (is_string($fn) && is_callable([$this, $fn])) {
104
+            $this->registeredCreateHooks[$columnName] = [$this, $fn];
105
+        } else if (is_callable($fn)) {
106
+            $this->registeredCreateHooks[$columnName] = $fn;
107
+        } else {
108
+            throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
109
+        }
110
+    }
111
+
112
+    /**
113
+     * Register a new hook for a specific column that gets called before execution of the read() method
114
+     * Only one hook per column can be registered at a time
115
+     * @param string $columnName The name of the column that is registered.
116
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
117
+     */
118
+    public function registerReadHook($columnName, $fn)
119
+    {
120
+        // Check whether column exists
121
+        if (!array_key_exists($columnName, $this->tableDefinition)) 
122
+        {
123
+            throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
124
+        }
125
+
126
+        // Enforcing 1 hook per table column
127
+        if (array_key_exists($columnName, $this->registeredReadHooks)) {
128
+            $message = "Hook is trying to register on an already registered column \"$columnName\", ";
129
+            $message .= "do you have conflicting traits?";
130
+            throw new ActiveRecordException($message, 0);
131
+        }
132
+
133
+        if (is_string($fn) && is_callable([$this, $fn])) {
134
+            $this->registeredReadHooks[$columnName] = [$this, $fn];
135
+        } else if (is_callable($fn)) {
136
+            $this->registeredReadHooks[$columnName] = $fn;
137
+        } else {
138
+            throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
139
+        }
140
+    }
141
+
142
+    /**
143
+     * Register a new hook for a specific column that gets called before execution of the update() method
144
+     * Only one hook per column can be registered at a time
145
+     * @param string $columnName The name of the column that is registered.
146
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
147
+     */
148
+    public function registerUpdateHook($columnName, $fn)
149
+    {
150
+        // Check whether column exists
151
+        if (!array_key_exists($columnName, $this->tableDefinition)) 
152
+        {
153
+            throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
154
+        }
155
+
156
+        // Enforcing 1 hook per table column
157
+        if (array_key_exists($columnName, $this->registeredUpdateHooks)) {
158
+            $message = "Hook is trying to register on an already registered column \"$columnName\", ";
159
+            $message .= "do you have conflicting traits?";
160
+            throw new ActiveRecordException($message, 0);
161
+        }
162
+
163
+        if (is_string($fn) && is_callable([$this, $fn])) {
164
+            $this->registeredUpdateHooks[$columnName] = [$this, $fn];
165
+        } else if (is_callable($fn)) {
166
+            $this->registeredUpdateHooks[$columnName] = $fn;
167
+        } else {
168
+            throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
169
+        }
170
+    }
171
+
172
+    /**
173
+     * Register a new hook for a specific column that gets called before execution of the delete() method
174
+     * Only one hook per column can be registered at a time
175
+     * @param string $columnName The name of the column that is registered.
176
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
177
+     */
178
+    public function registerDeleteHook($columnName, $fn)
179
+    {
180
+        // Check whether column exists
181
+        if (!array_key_exists($columnName, $this->tableDefinition)) 
182
+        {
183
+            throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
184
+        }
185
+
186
+        // Enforcing 1 hook per table column
187
+        if (array_key_exists($columnName, $this->registeredDeleteHooks)) {
188
+            $message = "Hook is trying to register on an already registered column \"$columnName\", ";
189
+            $message .= "do you have conflicting traits?";
190
+            throw new ActiveRecordException($message, 0);
191
+        }
192
+
193
+        if (is_string($fn) && is_callable([$this, $fn])) {
194
+            $this->registeredDeleteHooks[$columnName] = [$this, $fn];
195
+        } else if (is_callable($fn)) {
196
+            $this->registeredDeleteHooks[$columnName] = $fn;
197
+        } else {
198
+            throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
199
+        }
200
+    }
201
+
202
+    /**
203
+     * Register a new hook for a specific column that gets called before execution of the search() method
204
+     * Only one hook per column can be registered at a time
205
+     * @param string $columnName The name of the column that is registered.
206
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object. The callable is required to take one argument: an instance of miBadger\Query\Query; 
207
+     */
208
+    public function registerSearchHook($columnName, $fn)
209
+    {
210
+        // Check whether column exists
211
+        if (!array_key_exists($columnName, $this->tableDefinition)) 
212
+        {
213
+            throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
214
+        }
215
+
216
+        // Enforcing 1 hook per table column
217
+        if (array_key_exists($columnName, $this->registeredSearchHooks)) {
218
+            $message = "Hook is trying to register on an already registered column \"$columnName\", ";
219
+            $message .= "do you have conflicting traits?";
220
+            throw new ActiveRecordException($message, 0);
221
+        }
222
+
223
+        if (is_string($fn) && is_callable([$this, $fn])) {
224
+            $this->registeredSearchHooks[$columnName] = [$this, $fn];
225
+        } else if (is_callable($fn)) {
226
+            $this->registeredSearchHooks[$columnName] = $fn;
227
+        } else {
228
+            throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
229
+        }
230
+    }
231
+
232
+    /**
233
+     * Adds a new column definition to the table.
234
+     * @param string $columnName The name of the column that is registered.
235
+     * @param Array $definition The definition of that column.
236
+     */
237
+    public function extendTableDefinition($columnName, $definition)
238
+    {
239
+        if ($this->tableDefinition === null) {
240
+            throw new ActiveRecordException("tableDefinition is null, most likely due to parent class not having been initialized in constructor");
241
+        }
242
+
243
+        // Enforcing table can only be extended with new columns
244
+        if (array_key_exists($columnName, $this->tableDefinition)) {
245
+            $message = "Table is being extended with a column that already exists, ";
246
+            $message .= "\"$columnName\" conflicts with your table definition";
247
+            throw new ActiveRecordException($message, 0);
248
+        }
249
+
250
+        $this->tableDefinition[$columnName] = $definition;
251
+    }
252
+
253
+    /**
254
+     * Returns the type string as it should appear in the mysql create table statement for the given column
255
+     * @return string The type string
256
+     */
257
+    private function getDatabaseTypeString($colName, $type, $length)
258
+    {
259
+        if ($type === null) 
260
+        {
261
+            throw new ActiveRecordException(sprintf("Column %s has invalid type \"NULL\"", $colName));
262
+        }
263
+
264
+        switch (strtoupper($type)) {
265
+            case 'DATETIME':
266
+            case 'DATE':
267
+            case 'TIME':
268
+            case 'TEXT':
269
+            case 'INT UNSIGNED':
270
+                return $type;
271
+
272
+            case 'VARCHAR':
273
+                if ($length === null) {
274
+                    throw new ActiveRecordException(sprintf("field type %s requires specified column field \"LENGTH\"", $colName));
275
+                } else {
276
+                    return sprintf('%s(%d)', $type, $length);	
277
+                }
278
+
279
+            case 'INT':
280
+            case 'TINYINT':
281
+            case 'BIGINT':
282
+            default: 	
283
+            // @TODO(Default): throw exception, or implicitly assume that type is correct? (For when using SQL databases with different types)
284
+                if ($length === null) {
285
+                    return $type;
286
+                } else {
287
+                    return sprintf('%s(%d)', $type, $length);	
288
+                }
289
+        }
290
+    }
291
+
292
+    /**
293
+     * Builds the part of a MySQL create table statement that corresponds to the supplied column
294
+     * @param string $colName 	Name of the database column
295
+     * @param string $type 		The type of the string
296
+     * @param int $properties 	The set of Column properties that apply to this column (See ColumnProperty for options)
297
+     * @return string
298
+     */
299
+    private function buildCreateTableColumnEntry($colName, $type, $length, $properties, $default)
300
+    {
301
+
302
+        $stmnt = sprintf('`%s` %s ', $colName, $this->getDatabaseTypeString($colName, $type, $length));
303
+        if ($properties & ColumnProperty::NOT_NULL) {
304
+            $stmnt .= 'NOT NULL ';
305
+        } else {
306
+            $stmnt .= 'NULL ';
307
+        }
308
+
309
+        if ($default !== NULL) {
310
+            $stmnt .= ' DEFAULT ' . $default . ' ';
311
+        }
312
+
313
+        if ($properties & ColumnProperty::AUTO_INCREMENT) {
314
+            $stmnt .= 'AUTO_INCREMENT ';
315
+        }
316
+
317
+        if ($properties & ColumnProperty::UNIQUE) {
318
+            $stmnt .= 'UNIQUE ';
319
+        }
320
+
321
+        if ($properties & ColumnProperty::PRIMARY_KEY) {
322
+            $stmnt .= 'PRIMARY KEY ';
323
+        }
324
+
325
+        return $stmnt;
326
+    }
327
+
328
+    /**
329
+     * Sorts the column statement components in the order such that the id appears first, 
330
+     * 		followed by all other columns in alphabetical ascending order
331
+     * @param   Array $colStatements Array of column statements
332
+     * @return  Array
333
+     */
334
+    private function sortColumnStatements($colStatements)
335
+    {
336
+        // Find ID statement and put it first
337
+        $sortedStatements = [];
338
+
339
+        $sortedStatements[] = $colStatements[self::COLUMN_NAME_ID];
340
+        unset($colStatements[self::COLUMN_NAME_ID]);
341
+
342
+        // Sort remaining columns in alphabetical order
343
+        $columns = array_keys($colStatements);
344
+        sort($columns);
345
+        foreach ($columns as $colName) {
346
+            $sortedStatements[] = $colStatements[$colName];
347
+        }
348
+
349
+        return $sortedStatements;
350
+    }
351
+
352
+    /**
353
+     * Builds the MySQL Create Table statement for the internal table definition
354
+     * @return string
355
+     */
356
+    public function buildCreateTableSQL()
357
+    {
358
+        $columnStatements = [];
359
+        foreach ($this->tableDefinition as $colName => $definition) {
360
+            // Destructure column definition
361
+            $type    = $definition['type'] ?? null;
362
+            $default = $definition['default'] ?? null;
363
+            $length  = $definition['length'] ?? null;
364
+            $properties = $definition['properties'] ?? null;
365
+
366
+            if (isset($definition['relation']) && $type !== null) {
367
+                $msg = "Column \"$colName\": ";
368
+                $msg .= "Relationship columns have an automatically inferred type, so type should be omitted";
369
+                throw new ActiveRecordException($msg);
370
+            } else if (isset($definition['relation'])) {
371
+                $type = self::COLUMN_TYPE_ID;
372
+            }
373
+
374
+            $columnStatements[$colName] = $this->buildCreateTableColumnEntry($colName, $type, $length, $properties, $default);
375
+        }
376
+
377
+        // Sort table (first column is id, the remaining are alphabetically sorted)
378
+        $columnStatements = $this->sortColumnStatements($columnStatements);
379
+
380
+        $sql = 'CREATE TABLE ' . $this->getActiveRecordTable() . ' ';
381
+        $sql .= "(\n";
382
+        $sql .= join($columnStatements, ",\n");
383
+        $sql .= "\n);";
384
+
385
+        return $sql;
386
+    }
387
+
388
+    /**
389
+     * Creates the entity as a table in the database
390
+     */
391
+    public function createTable()
392
+    {
393
+        $this->pdo->query($this->buildCreateTableSQL());
394
+    }
395
+
396
+    /**
397
+     * builds a MySQL constraint statement for the given parameters
398
+     * @param string $parentTable
399
+     * @param string $parentColumn
400
+     * @param string $childTable
401
+     * @param string $childColumn
402
+     * @return string The MySQL table constraint string
403
+     */
404
+    protected function buildConstraint($parentTable, $parentColumn, $childTable, $childColumn)
405
+    {
406
+        $template = <<<SQL
407 407
 ALTER TABLE `%s`
408 408
 ADD CONSTRAINT
409 409
 FOREIGN KEY (`%s`)
410 410
 REFERENCES `%s`(`%s`)
411 411
 ON DELETE CASCADE;
412 412
 SQL;
413
-		return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
414
-	}
415
-
416
-	/**
417
-	 * Iterates over the specified constraints in the table definition, 
418
-	 * 		and applies these to the database.
419
-	 */
420
-	public function createTableConstraints()
421
-	{
422
-		// Iterate over columns, check whether "relation" field exists, if so create constraint
423
-		foreach ($this->tableDefinition as $colName => $definition) {
424
-			if (isset($definition['relation']) && $definition['relation'] instanceof AbstractActiveRecord) {
425
-				// Forge new relation
426
-				$target = $definition['relation'];
427
-				$constraintSql = $this->buildConstraint($target->getActiveRecordTable(), 'id', $this->getActiveRecordTable(), $colName);
428
-
429
-				$this->pdo->query($constraintSql);
430
-			}
431
-		}
432
-	}
433
-
434
-	/**
435
-	 * Returns the name -> variable mapping for the table definition.
436
-	 * @return Array The mapping
437
-	 */
438
-	protected function getActiveRecordColumns()
439
-	{
440
-		$bindings = [];
441
-		foreach ($this->tableDefinition as $colName => $definition) {
442
-
443
-			// Ignore the id column (key) when inserting or updating
444
-			if ($colName == self::COLUMN_NAME_ID) {
445
-				continue;
446
-			}
447
-
448
-			$bindings[$colName] = &$definition['value'];
449
-		}
450
-		return $bindings;
451
-	}
452
-
453
-	/**
454
-	 * {@inheritdoc}
455
-	 */
456
-	public function create()
457
-	{
458
-		foreach ($this->registeredCreateHooks as $colName => $fn) {
459
-			// @TODO: Would it be better to pass the Query to the function?
460
-			$fn();
461
-		}
462
-
463
-		try {
464
-			$q = (new Query($this->getPdo(), $this->getActiveRecordTable()))
465
-				->insert($this->getActiveRecordColumns())
466
-				->execute();
467
-
468
-			$this->setId(intval($this->getPdo()->lastInsertId()));
469
-		} catch (\PDOException $e) {
470
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
471
-		}
472
-
473
-		return $this;
474
-	}
475
-
476
-	/**
477
-	 * {@inheritdoc}
478
-	 */
479
-	public function read($id)
480
-	{
481
-		foreach ($this->registeredReadHooks as $colName => $fn) {
482
-			// @TODO: Would it be better to pass the Query to the function?
483
-			$fn();
484
-		}
485
-
486
-		try {
487
-			$row = (new Query($this->getPdo(), $this->getActiveRecordTable()))
488
-				->select()
489
-				->where('id', '=', $id)
490
-				->execute()
491
-				->fetch();
492
-
493
-			if ($row === false) {
494
-				throw new ActiveRecordException(sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getActiveRecordTable()));
495
-			}
496
-
497
-			$this->fill($row)->setId($id);
498
-		} catch (\PDOException $e) {
499
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
500
-		}
501
-
502
-		return $this;
503
-	}
504
-
505
-	/**
506
-	 * {@inheritdoc}
507
-	 */
508
-	public function update()
509
-	{
510
-		foreach ($this->registeredUpdateHooks as $colName => $fn) {
511
-			// @TODO: Would it be better to pass the Query to the function?
512
-			$fn();
513
-		}
514
-
515
-		try {
516
-			(new Query($this->getPdo(), $this->getActiveRecordTable()))
517
-				->update($this->getActiveRecordColumns())
518
-				->where('id', '=', $this->getId())
519
-				->execute();
520
-		} catch (\PDOException $e) {
521
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
522
-		}
523
-
524
-		return $this;
525
-	}
526
-
527
-	/**
528
-	 * {@inheritdoc}
529
-	 */
530
-	public function delete()
531
-	{
532
-		foreach ($this->registeredDeleteHooks as $colName => $fn) {
533
-			// @TODO: Would it be better to pass the Query to the function?
534
-			$fn();
535
-		}
536
-
537
-		try {
538
-			(new Query($this->getPdo(), $this->getActiveRecordTable()))
539
-				->delete()
540
-				->where('id', '=', $this->getId())
541
-				->execute();
542
-
543
-			$this->setId(null);
544
-		} catch (\PDOException $e) {
545
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
546
-		}
547
-
548
-		return $this;
549
-	}
550
-
551
-	/**
552
-	 * {@inheritdoc}
553
-	 */
554
-	public function sync()
555
-	{
556
-		if (!$this->exists()) {
557
-			return $this->create();
558
-		}
559
-
560
-		return $this->update();
561
-	}
562
-
563
-	/**
564
-	 * {@inheritdoc}
565
-	 */
566
-	public function exists()
567
-	{
568
-		return $this->getId() !== null;
569
-	}
570
-
571
-	/**
572
-	 * {@inheritdoc}
573
-	 */
574
-	public function fill(array $attributes)
575
-	{
576
-		$columns = $this->getActiveRecordColumns();
577
-		$columns['id'] = &$this->id;
578
-
579
-		foreach ($attributes as $key => $value) {
580
-			if (array_key_exists($key, $columns)) {
581
-				$columns[$key] = $value;
582
-			}
583
-		}
584
-
585
-		return $this;
586
-	}
587
-
588
-	/**
589
-	 * {@inheritdoc}
590
-	 */
591
-	public function searchOne(array $where = [], array $orderBy = [])
592
-	{
593
-		try {
594
-			$row = $this->getSearchQueryResult($where, $orderBy, 1)->fetch();
595
-
596
-			if ($row === false) {
597
-				throw new ActiveRecordException(sprintf('Can not search one non-existent entry from the `%s` table.', $this->getActiveRecordTable()));
598
-			}
599
-
600
-			return $this->fill($row)->setId($row['id']);
601
-		} catch (\PDOException $e) {
602
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
603
-		}
604
-	}
605
-
606
-	/**
607
-	 * {@inheritdoc}
608
-	 */
609
-	public function search(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
610
-	{
611
-		try {
612
-			$queryResult = $this->getSearchQueryResult($where, $orderBy, $limit, $offset);
613
-			$result = [];
614
-
615
-			foreach ($queryResult as $row) {
616
-				$new = clone $this;
617
-
618
-				$result[] = $new->fill($row)->setId($row['id']);
619
-			}
620
-
621
-			return $result;
622
-		} catch (\PDOException $e) {
623
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
624
-		}
625
-	}
626
-
627
-	/**
628
-	 * Returns the search query result with the given where, order by, limit and offset clauses.
629
-	 *
630
-	 * @param array $where = []
631
-	 * @param array $orderBy = []
632
-	 * @param int $limit = -1
633
-	 * @param int $offset = 0
634
-	 * @return \miBadger\Query\QueryResult the search query result with the given where, order by, limit and offset clauses.
635
-	 */
636
-	private function getSearchQueryResult(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
637
-	{
638
-		$query = (new Query($this->getPdo(), $this->getActiveRecordTable()))
639
-			->select();
640
-
641
-		$this->getSearchQueryWhere($query, $where);
642
-		$this->getSearchQueryOrderBy($query, $orderBy);
643
-		$this->getSearchQueryLimit($query, $limit, $offset);
644
-
645
-		// Ignore all trait modifiers for which a where clause was specified
646
-		$registeredSearchHooks = $this->registeredSearchHooks;
647
-		foreach ($where as $index => $clause) {
648
-			$colName = $clause[0];
649
-			unset($registeredSearchHooks[$colName]);
650
-		}
651
-
652
-		// Allow traits to modify the query
653
-		foreach ($registeredSearchHooks as $column => $searchFunction) {
654
-			$searchFunction($query);
655
-		}
656
-
657
-		return $query->execute();
658
-	}
659
-
660
-	/**
661
-	 * Returns the given query after adding the given where conditions.
662
-	 *
663
-	 * @param \miBadger\Query\Query $query
664
-	 * @param array $where
665
-	 * @return \miBadger\Query\Query the given query after adding the given where conditions.
666
-	 */
667
-	private function getSearchQueryWhere($query, $where)
668
-	{
669
-		foreach ($where as $key => $value) {
670
-			$query->where($value[0], $value[1], $value[2]);
671
-		}
672
-
673
-		return $query;
674
-	}
675
-
676
-	/**
677
-	 * Returns the given query after adding the given order by conditions.
678
-	 *
679
-	 * @param \miBadger\Query\Query $query
680
-	 * @param array $orderBy
681
-	 * @return \miBadger\Query\Query the given query after adding the given order by conditions.
682
-	 */
683
-	private function getSearchQueryOrderBy($query, $orderBy)
684
-	{
685
-		foreach ($orderBy as $key => $value) {
686
-			$query->orderBy($key, $value);
687
-		}
688
-
689
-		return $query;
690
-	}
691
-
692
-	/**
693
-	 * Returns the given query after adding the given limit and offset conditions.
694
-	 *
695
-	 * @param \miBadger\Query\Query $query
696
-	 * @param int $limit
697
-	 * @param int $offset
698
-	 * @return \miBadger\Query\Query the given query after adding the given limit and offset conditions.
699
-	 */
700
-	private function getSearchQueryLimit($query, $limit, $offset)
701
-	{
702
-		if ($limit > -1) {
703
-			$query->limit($limit);
704
-			$query->offset($offset);
705
-		}
706
-
707
-		return $query;
708
-	}
709
-
710
-	/**
711
-	 * Returns the PDO.
712
-	 *
713
-	 * @return \PDO the PDO.
714
-	 */
715
-	public function getPdo()
716
-	{
717
-		return $this->pdo;
718
-	}
719
-
720
-	/**
721
-	 * Set the PDO.
722
-	 *
723
-	 * @param \PDO $pdo
724
-	 * @return $this
725
-	 */
726
-	protected function setPdo($pdo)
727
-	{
728
-		$this->pdo = $pdo;
729
-
730
-		return $this;
731
-	}
732
-
733
-	/**
734
-	 * Returns the ID.
735
-	 *
736
-	 * @return null|int The ID.
737
-	 */
738
-	public function getId()
739
-	{
740
-		return $this->id;
741
-	}
742
-
743
-	/**
744
-	 * Set the ID.
745
-	 *
746
-	 * @param int $id
747
-	 * @return $this
748
-	 */
749
-	protected function setId($id)
750
-	{
751
-		$this->id = $id;
752
-
753
-		return $this;
754
-	}
755
-
756
-	/**
757
-	 * Returns the active record table.
758
-	 *
759
-	 * @return string the active record table.
760
-	 */
761
-	abstract protected function getActiveRecordTable();
762
-
763
-	/**
764
-	 * Returns the active record columns.
765
-	 *
766
-	 * @return array the active record columns.
767
-	 */
768
-	abstract protected function getActiveRecordTableDefinition();
413
+        return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
414
+    }
415
+
416
+    /**
417
+     * Iterates over the specified constraints in the table definition, 
418
+     * 		and applies these to the database.
419
+     */
420
+    public function createTableConstraints()
421
+    {
422
+        // Iterate over columns, check whether "relation" field exists, if so create constraint
423
+        foreach ($this->tableDefinition as $colName => $definition) {
424
+            if (isset($definition['relation']) && $definition['relation'] instanceof AbstractActiveRecord) {
425
+                // Forge new relation
426
+                $target = $definition['relation'];
427
+                $constraintSql = $this->buildConstraint($target->getActiveRecordTable(), 'id', $this->getActiveRecordTable(), $colName);
428
+
429
+                $this->pdo->query($constraintSql);
430
+            }
431
+        }
432
+    }
433
+
434
+    /**
435
+     * Returns the name -> variable mapping for the table definition.
436
+     * @return Array The mapping
437
+     */
438
+    protected function getActiveRecordColumns()
439
+    {
440
+        $bindings = [];
441
+        foreach ($this->tableDefinition as $colName => $definition) {
442
+
443
+            // Ignore the id column (key) when inserting or updating
444
+            if ($colName == self::COLUMN_NAME_ID) {
445
+                continue;
446
+            }
447
+
448
+            $bindings[$colName] = &$definition['value'];
449
+        }
450
+        return $bindings;
451
+    }
452
+
453
+    /**
454
+     * {@inheritdoc}
455
+     */
456
+    public function create()
457
+    {
458
+        foreach ($this->registeredCreateHooks as $colName => $fn) {
459
+            // @TODO: Would it be better to pass the Query to the function?
460
+            $fn();
461
+        }
462
+
463
+        try {
464
+            $q = (new Query($this->getPdo(), $this->getActiveRecordTable()))
465
+                ->insert($this->getActiveRecordColumns())
466
+                ->execute();
467
+
468
+            $this->setId(intval($this->getPdo()->lastInsertId()));
469
+        } catch (\PDOException $e) {
470
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
471
+        }
472
+
473
+        return $this;
474
+    }
475
+
476
+    /**
477
+     * {@inheritdoc}
478
+     */
479
+    public function read($id)
480
+    {
481
+        foreach ($this->registeredReadHooks as $colName => $fn) {
482
+            // @TODO: Would it be better to pass the Query to the function?
483
+            $fn();
484
+        }
485
+
486
+        try {
487
+            $row = (new Query($this->getPdo(), $this->getActiveRecordTable()))
488
+                ->select()
489
+                ->where('id', '=', $id)
490
+                ->execute()
491
+                ->fetch();
492
+
493
+            if ($row === false) {
494
+                throw new ActiveRecordException(sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getActiveRecordTable()));
495
+            }
496
+
497
+            $this->fill($row)->setId($id);
498
+        } catch (\PDOException $e) {
499
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
500
+        }
501
+
502
+        return $this;
503
+    }
504
+
505
+    /**
506
+     * {@inheritdoc}
507
+     */
508
+    public function update()
509
+    {
510
+        foreach ($this->registeredUpdateHooks as $colName => $fn) {
511
+            // @TODO: Would it be better to pass the Query to the function?
512
+            $fn();
513
+        }
514
+
515
+        try {
516
+            (new Query($this->getPdo(), $this->getActiveRecordTable()))
517
+                ->update($this->getActiveRecordColumns())
518
+                ->where('id', '=', $this->getId())
519
+                ->execute();
520
+        } catch (\PDOException $e) {
521
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
522
+        }
523
+
524
+        return $this;
525
+    }
526
+
527
+    /**
528
+     * {@inheritdoc}
529
+     */
530
+    public function delete()
531
+    {
532
+        foreach ($this->registeredDeleteHooks as $colName => $fn) {
533
+            // @TODO: Would it be better to pass the Query to the function?
534
+            $fn();
535
+        }
536
+
537
+        try {
538
+            (new Query($this->getPdo(), $this->getActiveRecordTable()))
539
+                ->delete()
540
+                ->where('id', '=', $this->getId())
541
+                ->execute();
542
+
543
+            $this->setId(null);
544
+        } catch (\PDOException $e) {
545
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
546
+        }
547
+
548
+        return $this;
549
+    }
550
+
551
+    /**
552
+     * {@inheritdoc}
553
+     */
554
+    public function sync()
555
+    {
556
+        if (!$this->exists()) {
557
+            return $this->create();
558
+        }
559
+
560
+        return $this->update();
561
+    }
562
+
563
+    /**
564
+     * {@inheritdoc}
565
+     */
566
+    public function exists()
567
+    {
568
+        return $this->getId() !== null;
569
+    }
570
+
571
+    /**
572
+     * {@inheritdoc}
573
+     */
574
+    public function fill(array $attributes)
575
+    {
576
+        $columns = $this->getActiveRecordColumns();
577
+        $columns['id'] = &$this->id;
578
+
579
+        foreach ($attributes as $key => $value) {
580
+            if (array_key_exists($key, $columns)) {
581
+                $columns[$key] = $value;
582
+            }
583
+        }
584
+
585
+        return $this;
586
+    }
587
+
588
+    /**
589
+     * {@inheritdoc}
590
+     */
591
+    public function searchOne(array $where = [], array $orderBy = [])
592
+    {
593
+        try {
594
+            $row = $this->getSearchQueryResult($where, $orderBy, 1)->fetch();
595
+
596
+            if ($row === false) {
597
+                throw new ActiveRecordException(sprintf('Can not search one non-existent entry from the `%s` table.', $this->getActiveRecordTable()));
598
+            }
599
+
600
+            return $this->fill($row)->setId($row['id']);
601
+        } catch (\PDOException $e) {
602
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
603
+        }
604
+    }
605
+
606
+    /**
607
+     * {@inheritdoc}
608
+     */
609
+    public function search(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
610
+    {
611
+        try {
612
+            $queryResult = $this->getSearchQueryResult($where, $orderBy, $limit, $offset);
613
+            $result = [];
614
+
615
+            foreach ($queryResult as $row) {
616
+                $new = clone $this;
617
+
618
+                $result[] = $new->fill($row)->setId($row['id']);
619
+            }
620
+
621
+            return $result;
622
+        } catch (\PDOException $e) {
623
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
624
+        }
625
+    }
626
+
627
+    /**
628
+     * Returns the search query result with the given where, order by, limit and offset clauses.
629
+     *
630
+     * @param array $where = []
631
+     * @param array $orderBy = []
632
+     * @param int $limit = -1
633
+     * @param int $offset = 0
634
+     * @return \miBadger\Query\QueryResult the search query result with the given where, order by, limit and offset clauses.
635
+     */
636
+    private function getSearchQueryResult(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
637
+    {
638
+        $query = (new Query($this->getPdo(), $this->getActiveRecordTable()))
639
+            ->select();
640
+
641
+        $this->getSearchQueryWhere($query, $where);
642
+        $this->getSearchQueryOrderBy($query, $orderBy);
643
+        $this->getSearchQueryLimit($query, $limit, $offset);
644
+
645
+        // Ignore all trait modifiers for which a where clause was specified
646
+        $registeredSearchHooks = $this->registeredSearchHooks;
647
+        foreach ($where as $index => $clause) {
648
+            $colName = $clause[0];
649
+            unset($registeredSearchHooks[$colName]);
650
+        }
651
+
652
+        // Allow traits to modify the query
653
+        foreach ($registeredSearchHooks as $column => $searchFunction) {
654
+            $searchFunction($query);
655
+        }
656
+
657
+        return $query->execute();
658
+    }
659
+
660
+    /**
661
+     * Returns the given query after adding the given where conditions.
662
+     *
663
+     * @param \miBadger\Query\Query $query
664
+     * @param array $where
665
+     * @return \miBadger\Query\Query the given query after adding the given where conditions.
666
+     */
667
+    private function getSearchQueryWhere($query, $where)
668
+    {
669
+        foreach ($where as $key => $value) {
670
+            $query->where($value[0], $value[1], $value[2]);
671
+        }
672
+
673
+        return $query;
674
+    }
675
+
676
+    /**
677
+     * Returns the given query after adding the given order by conditions.
678
+     *
679
+     * @param \miBadger\Query\Query $query
680
+     * @param array $orderBy
681
+     * @return \miBadger\Query\Query the given query after adding the given order by conditions.
682
+     */
683
+    private function getSearchQueryOrderBy($query, $orderBy)
684
+    {
685
+        foreach ($orderBy as $key => $value) {
686
+            $query->orderBy($key, $value);
687
+        }
688
+
689
+        return $query;
690
+    }
691
+
692
+    /**
693
+     * Returns the given query after adding the given limit and offset conditions.
694
+     *
695
+     * @param \miBadger\Query\Query $query
696
+     * @param int $limit
697
+     * @param int $offset
698
+     * @return \miBadger\Query\Query the given query after adding the given limit and offset conditions.
699
+     */
700
+    private function getSearchQueryLimit($query, $limit, $offset)
701
+    {
702
+        if ($limit > -1) {
703
+            $query->limit($limit);
704
+            $query->offset($offset);
705
+        }
706
+
707
+        return $query;
708
+    }
709
+
710
+    /**
711
+     * Returns the PDO.
712
+     *
713
+     * @return \PDO the PDO.
714
+     */
715
+    public function getPdo()
716
+    {
717
+        return $this->pdo;
718
+    }
719
+
720
+    /**
721
+     * Set the PDO.
722
+     *
723
+     * @param \PDO $pdo
724
+     * @return $this
725
+     */
726
+    protected function setPdo($pdo)
727
+    {
728
+        $this->pdo = $pdo;
729
+
730
+        return $this;
731
+    }
732
+
733
+    /**
734
+     * Returns the ID.
735
+     *
736
+     * @return null|int The ID.
737
+     */
738
+    public function getId()
739
+    {
740
+        return $this->id;
741
+    }
742
+
743
+    /**
744
+     * Set the ID.
745
+     *
746
+     * @param int $id
747
+     * @return $this
748
+     */
749
+    protected function setId($id)
750
+    {
751
+        $this->id = $id;
752
+
753
+        return $this;
754
+    }
755
+
756
+    /**
757
+     * Returns the active record table.
758
+     *
759
+     * @return string the active record table.
760
+     */
761
+    abstract protected function getActiveRecordTable();
762
+
763
+    /**
764
+     * Returns the active record columns.
765
+     *
766
+     * @return array the active record columns.
767
+     */
768
+    abstract protected function getActiveRecordTableDefinition();
769 769
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 		}
308 308
 
309 309
 		if ($default !== NULL) {
310
-			$stmnt .= ' DEFAULT ' . $default . ' ';
310
+			$stmnt .= ' DEFAULT '.$default.' ';
311 311
 		}
312 312
 
313 313
 		if ($properties & ColumnProperty::AUTO_INCREMENT) {
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 		// Sort table (first column is id, the remaining are alphabetically sorted)
378 378
 		$columnStatements = $this->sortColumnStatements($columnStatements);
379 379
 
380
-		$sql = 'CREATE TABLE ' . $this->getActiveRecordTable() . ' ';
380
+		$sql = 'CREATE TABLE '.$this->getActiveRecordTable().' ';
381 381
 		$sql .= "(\n";
382 382
 		$sql .= join($columnStatements, ",\n");
383 383
 		$sql .= "\n);";
Please login to merge, or discard this patch.