Passed
Push — v2 ( ede5d5...ff18b4 )
by Berend
05:08
created
src/ColumnProperty.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -6,10 +6,10 @@
 block discarded – undo
6 6
 
7 7
 class ColumnProperty extends Enum
8 8
 {
9
-	const NONE = 0;
10
-	const UNIQUE = 1;
11
-	const NOT_NULL = 2;
12
-	const IMMUTABLE = 4;
13
-	const AUTO_INCREMENT = 8;
14
-	const PRIMARY_KEY = 16;
9
+    const NONE = 0;
10
+    const UNIQUE = 1;
11
+    const NOT_NULL = 2;
12
+    const IMMUTABLE = 4;
13
+    const AUTO_INCREMENT = 8;
14
+    const PRIMARY_KEY = 16;
15 15
 }
16 16
\ No newline at end of file
Please login to merge, or discard this patch.
src/AbstractActiveRecord.php 1 patch
Indentation   +579 added lines, -579 removed lines patch added patch discarded remove patch
@@ -18,584 +18,584 @@
 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
-	const CREATE = 'CREATE';
25
-	const READ = 'READ';
26
-	const UPDATE = 'UPDATE';
27
-	const DELETE = 'DELETE';
28
-	const SEARCH = 'SEARCH';
29
-
30
-	/** @var \PDO The PDO object. */
31
-	protected $pdo;
32
-
33
-	/** @var null|int The ID. */
34
-	private $id;
35
-
36
-	/** @var array A map of column name to functions that hook the insert function */
37
-	protected $createHooks;
38
-
39
-	/** @var array A map of column name to functions that hook the read function */
40
-	protected $readHooks;
41
-
42
-	/** @var array A map of column name to functions that hook the update function */
43
-	protected $updateHooks;
44
-
45
-	/** @var array A map of column name to functions that hook the update function */
46
-	protected $deleteHooks;	
47
-
48
-	/** @var array A map of column name to functions that hook the search function */
49
-	protected $searchHooks;
50
-
51
-	/** @var array A list of table column definitions */
52
-	protected $tableDefinition;
53
-
54
-	/**
55
-	 * Construct an abstract active record with the given PDO.
56
-	 *
57
-	 * @param \PDO $pdo
58
-	 */
59
-	public function __construct(\PDO $pdo)
60
-	{
61
-		$pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
62
-		$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
63
-
64
-		$this->setPdo($pdo);
65
-
66
-		$this->createHooks = [];
67
-		$this->readHooks = [];
68
-		$this->updateHooks = [];
69
-		$this->deleteHooks = [];
70
-		$this->searchHooks = [];
71
-		$this->tableDefinition = $this->getTableDefinition();
72
-
73
-		// Extend table definition with default ID field, throw exception if field already exists
74
-		if (array_key_exists('id', $this->tableDefinition)) {
75
-			$message = "Table definition in record contains a field with name \"id\"";
76
-			$message .= ", which is a reserved name by ActiveRecord";
77
-			throw new ActiveRecordException($message, 0);
78
-		}
79
-
80
-		$this->tableDefinition[self::COLUMN_NAME_ID] =
81
-		[
82
-			'value' => &$this->id,
83
-			'validate' => null,
84
-			'type' => self::COLUMN_TYPE_ID,
85
-			'properties' =>
86
-				ColumnProperty::NOT_NULL
87
-				| ColumnProperty::IMMUTABLE
88
-				| ColumnProperty::AUTO_INCREMENT
89
-				| ColumnProperty::PRIMARY_KEY
90
-		];
91
-	}
92
-
93
-	private function checkHookConstraints($columnName, $hookMap)
94
-	{
95
-		// Check whether column exists
96
-		if (!array_key_exists($columnName, $this->tableDefinition)) 
97
-		{
98
-			throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
99
-		}
100
-
101
-		// Enforcing 1 hook per table column
102
-		if (array_key_exists($columnName, $hookMap)) {
103
-			$message = "Hook is trying to register on an already registered column \"$columnName\", ";
104
-			$message .= "do you have conflicting traits?";
105
-			throw new ActiveRecordException($message, 0);
106
-		}
107
-	}
108
-
109
-	public function registerHookOnAction($actionName, $columnName, $fn)
110
-	{
111
-		if (is_string($fn) && is_callable([$this, $fn])) {
112
-			$fn = [$this, $fn];
113
-		}
114
-
115
-		if (!is_callable($fn)) { 
116
-			throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
117
-		}
118
-
119
-		switch ($actionName) {
120
-			case self::CREATE:
121
-				$this->checkHookConstraints($columnName, $this->createHooks);
122
-				$this->createHooks[$columnName] = $fn;
123
-				break;
124
-			case self::READ:
125
-				$this->checkHookConstraints($columnName, $this->readHooks);
126
-				$this->readHooks[$columnName] = $fn;
127
-				break;
128
-			case self::UPDATE:
129
-				$this->checkHookConstraints($columnName, $this->updateHooks);
130
-				$this->updateHooks[$columnName] = $fn;
131
-				break;
132
-			case self::DELETE:
133
-				$this->checkHookConstraints($columnName, $this->deleteHooks);
134
-				$this->deleteHooks[$columnName] = $fn;
135
-				break;
136
-			case self::SEARCH:
137
-				$this->checkHookConstraints($columnName, $this->searchHooks);
138
-				$this->searchHooks[$columnName] = $fn;
139
-				break;
140
-			default:
141
-				throw new ActiveRecordException("Invalid action: Can not register hook on non-existing action");
142
-		}
143
-	}
144
-
145
-	/**
146
-	 * Register a new hook for a specific column that gets called before execution of the create() method
147
-	 * Only one hook per column can be registered at a time
148
-	 * @param string $columnName The name of the column that is registered.
149
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
150
-	 */
151
-	public function registerCreateHook($columnName, $fn)
152
-	{
153
-		$this->registerHookOnAction(self::CREATE, $columnName, $fn);
154
-	}
155
-
156
-	/**
157
-	 * Register a new hook for a specific column that gets called before execution of the read() method
158
-	 * Only one hook per column can be registered at a time
159
-	 * @param string $columnName The name of the column that is registered.
160
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
161
-	 */
162
-	public function registerReadHook($columnName, $fn)
163
-	{
164
-		$this->registerHookOnAction(self::READ, $columnName, $fn);
165
-	}
166
-
167
-	/**
168
-	 * Register a new hook for a specific column that gets called before execution of the update() method
169
-	 * Only one hook per column can be registered at a time
170
-	 * @param string $columnName The name of the column that is registered.
171
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
172
-	 */
173
-	public function registerUpdateHook($columnName, $fn)
174
-	{
175
-		$this->registerHookOnAction(self::UPDATE, $columnName, $fn);
176
-	}
177
-
178
-	/**
179
-	 * Register a new hook for a specific column that gets called before execution of the delete() method
180
-	 * Only one hook per column can be registered at a time
181
-	 * @param string $columnName The name of the column that is registered.
182
-	 * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
183
-	 */
184
-	public function registerDeleteHook($columnName, $fn)
185
-	{
186
-		$this->registerHookOnAction(self::DELETE, $columnName, $fn);
187
-	}
188
-
189
-	/**
190
-	 * Register a new hook for a specific column that gets called before execution of the search() method
191
-	 * Only one hook per column can be registered at a time
192
-	 * @param string $columnName The name of the column that is registered.
193
-	 * @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; 
194
-	 */
195
-	public function registerSearchHook($columnName, $fn)
196
-	{
197
-		$this->registerHookOnAction(self::SEARCH, $columnName, $fn);
198
-	}
199
-
200
-	/**
201
-	 * Adds a new column definition to the table.
202
-	 * @param string $columnName The name of the column that is registered.
203
-	 * @param Array $definition The definition of that column.
204
-	 */
205
-	protected function extendTableDefinition($columnName, $definition)
206
-	{
207
-		if ($this->tableDefinition === null) {
208
-			throw new ActiveRecordException("tableDefinition is null, has parent been initialized in constructor?");
209
-		}
210
-
211
-		// Enforcing table can only be extended with new columns
212
-		if (array_key_exists($columnName, $this->tableDefinition)) {
213
-			$message = "Table is being extended with a column that already exists, ";
214
-			$message .= "\"$columnName\" conflicts with your table definition";
215
-			throw new ActiveRecordException($message, 0);
216
-		}
217
-
218
-		$this->tableDefinition[$columnName] = $definition;
219
-	}
220
-
221
-	public function hasColumn(string $column) {
222
-		return array_key_exists($column, $this->tableDefinition);
223
-	}
224
-
225
-	public function hasRelation(string $column, AbstractActiveRecord $record) {
226
-		if (!$this->hasColumn($column)) {
227
-			throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
228
-		}
229
-
230
-		$relation = $this->tableDefinition[$column]['relation'] ?? null;
231
-		return $relation !== null && get_class($record) === get_class($relation);
232
-	}
233
-
234
-	public function hasProperty(string $column, $property) {
235
-		if (!$this->hasColumn($column)) {
236
-			throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
237
-		}
238
-
239
-		try {
240
-			$enumValue = ColumnProperty::valueOf($property);
241
-		} catch (\UnexpectedValueException $e) {
242
-			throw new ActiveRecordException("Provided property \"$property\" is not a valid property", 0, $e);
243
-		}
244
-
245
-		$properties = $this->tableDefinition[$column]['properties'] ?? null;
246
-
247
-		return $properties !== null && (($properties & $enumValue->getValue()) > 0);
248
-	}
249
-
250
-	public function getColumnType(string $column) {
251
-		if (!$this->hasColumn($column)) {
252
-			throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
253
-		}
254
-
255
-		return $this->tableDefinition[$column]['type'] ?? null;
256
-	}
257
-
258
-	public function getColumnLength(string $column) {
259
-		if (!$this->hasColumn($column)) {
260
-			throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
261
-		}
262
-
263
-		return $this->tableDefinition[$column]['length'] ?? null;
264
-	}
265
-
266
-	public function getDefault(string $column) {
267
-		if (!$this->hasColumn($column)) {
268
-			throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
269
-		}
270
-
271
-		return $this->tableDefinition[$column]['default'] ?? null;
272
-	}
273
-
274
-	public function validateColumn(string $column, $input) {
275
-		if (!$this->hasColumn($column)) {
276
-			throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
277
-		}
278
-
279
-		$fn = $this->tableDefinition[$column]['validate'] ?? null;
280
-
281
-		if ($fn === null) {
282
-			return [true, ''];
283
-		}
284
-
285
-		if (!is_callable($fn)) {
286
-			throw new ActiveRecordException("Provided validation function is not callable", 0);
287
-		}
288
-
289
-		return $fn($input);
290
-	}
291
-
292
-	/**
293
-	 * Creates the entity as a table in the database
294
-	 */
295
-	public function createTable()
296
-	{
297
-		$this->pdo->query(SchemaBuilder::buildCreateTableSQL($this->getTableName(), $this->tableDefinition));
298
-	}
299
-
300
-	/**
301
-	 * Iterates over the specified constraints in the table definition, 
302
-	 * 		and applies these to the database.
303
-	 */
304
-	public function createTableConstraints()
305
-	{
306
-		// Iterate over columns, check whether "relation" field exists, if so create constraint
307
-		foreach ($this->tableDefinition as $colName => $definition) {
308
-			if (isset($definition['relation']) && $definition['relation'] instanceof AbstractActiveRecord) {
309
-				// Forge new relation
310
-				$target = $definition['relation'];
311
-				$properties = $definition['properties'] ?? 0;
312
-
313
-				if ($properties & ColumnProperty::NOT_NULL) {
314
-					$constraintSql = SchemaBuilder::buildConstraintOnDeleteCascade($target->getTableName(), 'id', $this->getTableName(), $colName);
315
-				} else {
316
-					$constraintSql = SchemaBuilder::buildConstraintOnDeleteSetNull($target->getTableName(), 'id', $this->getTableName(), $colName);
317
-				}
318
-
319
-				$this->pdo->query($constraintSql);
320
-			} else if (isset($definition['relation'])) {
321
-				$msg = sprintf("Relation constraint on column \"%s\" of table \"%s\" does not contain a valid ActiveRecord instance", 
322
-					$colName,
323
-					$this->getTableName());
324
-				throw new ActiveRecordException($msg);
325
-			}
326
-		}
327
-	}
328
-
329
-	/**
330
-	 * Returns the name -> variable mapping for the table definition.
331
-	 * @return Array The mapping
332
-	 */
333
-	protected function getActiveRecordColumns()
334
-	{
335
-		$bindings = [];
336
-		foreach ($this->tableDefinition as $colName => $definition) {
337
-
338
-			// Ignore the id column (key) when inserting or updating
339
-			if ($colName == self::COLUMN_NAME_ID) {
340
-				continue;
341
-			}
342
-
343
-			$bindings[$colName] = &$definition['value'];
344
-		}
345
-		return $bindings;
346
-	}
347
-
348
-	protected function insertDefaults()
349
-	{
350
-		// Insert default values for not-null fields
351
-		foreach ($this->tableDefinition as $colName => $colDef) {
352
-			if ($colDef['value'] === null
353
-				&& ($colDef['properties'] ?? 0) & ColumnProperty::NOT_NULL
354
-				&& isset($colDef['default'])) {
355
-				$this->tableDefinition[$colName]['value'] = $colDef['default'];
356
-			}
357
-		}		
358
-	}
359
-
360
-	/**
361
-	 * {@inheritdoc}
362
-	 */
363
-	public function create()
364
-	{
365
-		foreach ($this->createHooks as $colName => $fn) {
366
-			$fn();
367
-		}
368
-
369
-		$this->insertDefaults();
370
-
371
-		try {
372
-			(new Query($this->getPdo(), $this->getTableName()))
373
-				->insert($this->getActiveRecordColumns())
374
-				->execute();
375
-
376
-			$this->setId(intval($this->getPdo()->lastInsertId()));
377
-		} catch (\PDOException $e) {
378
-			throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
379
-		}
380
-
381
-		return $this;
382
-	}
383
-
384
-	/**
385
-	 * {@inheritdoc}
386
-	 */
387
-	public function read($id)
388
-	{
389
-		$whereConditions = [
390
-			Query::Equal('id', $id)
391
-		];
392
-		foreach ($this->readHooks as $colName => $fn) {
393
-			$cond = $fn();
394
-			if ($cond !== null) {
395
-				$whereConditions[] = $cond;
396
-			}
397
-		}
398
-
399
-		try {
400
-			$row = (new Query($this->getPdo(), $this->getTableName()))
401
-				->select()
402
-				->where(Query::AndArray($whereConditions))
403
-				->execute()
404
-				->fetch();
21
+    const COLUMN_NAME_ID = 'id';
22
+    const COLUMN_TYPE_ID = 'INT UNSIGNED';
23
+
24
+    const CREATE = 'CREATE';
25
+    const READ = 'READ';
26
+    const UPDATE = 'UPDATE';
27
+    const DELETE = 'DELETE';
28
+    const SEARCH = 'SEARCH';
29
+
30
+    /** @var \PDO The PDO object. */
31
+    protected $pdo;
32
+
33
+    /** @var null|int The ID. */
34
+    private $id;
35
+
36
+    /** @var array A map of column name to functions that hook the insert function */
37
+    protected $createHooks;
38
+
39
+    /** @var array A map of column name to functions that hook the read function */
40
+    protected $readHooks;
41
+
42
+    /** @var array A map of column name to functions that hook the update function */
43
+    protected $updateHooks;
44
+
45
+    /** @var array A map of column name to functions that hook the update function */
46
+    protected $deleteHooks;	
47
+
48
+    /** @var array A map of column name to functions that hook the search function */
49
+    protected $searchHooks;
50
+
51
+    /** @var array A list of table column definitions */
52
+    protected $tableDefinition;
53
+
54
+    /**
55
+     * Construct an abstract active record with the given PDO.
56
+     *
57
+     * @param \PDO $pdo
58
+     */
59
+    public function __construct(\PDO $pdo)
60
+    {
61
+        $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
62
+        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
63
+
64
+        $this->setPdo($pdo);
65
+
66
+        $this->createHooks = [];
67
+        $this->readHooks = [];
68
+        $this->updateHooks = [];
69
+        $this->deleteHooks = [];
70
+        $this->searchHooks = [];
71
+        $this->tableDefinition = $this->getTableDefinition();
72
+
73
+        // Extend table definition with default ID field, throw exception if field already exists
74
+        if (array_key_exists('id', $this->tableDefinition)) {
75
+            $message = "Table definition in record contains a field with name \"id\"";
76
+            $message .= ", which is a reserved name by ActiveRecord";
77
+            throw new ActiveRecordException($message, 0);
78
+        }
79
+
80
+        $this->tableDefinition[self::COLUMN_NAME_ID] =
81
+        [
82
+            'value' => &$this->id,
83
+            'validate' => null,
84
+            'type' => self::COLUMN_TYPE_ID,
85
+            'properties' =>
86
+                ColumnProperty::NOT_NULL
87
+                | ColumnProperty::IMMUTABLE
88
+                | ColumnProperty::AUTO_INCREMENT
89
+                | ColumnProperty::PRIMARY_KEY
90
+        ];
91
+    }
92
+
93
+    private function checkHookConstraints($columnName, $hookMap)
94
+    {
95
+        // Check whether column exists
96
+        if (!array_key_exists($columnName, $this->tableDefinition)) 
97
+        {
98
+            throw new ActiveRecordException("Hook is trying to register on non-existing column \"$columnName\"", 0);
99
+        }
100
+
101
+        // Enforcing 1 hook per table column
102
+        if (array_key_exists($columnName, $hookMap)) {
103
+            $message = "Hook is trying to register on an already registered column \"$columnName\", ";
104
+            $message .= "do you have conflicting traits?";
105
+            throw new ActiveRecordException($message, 0);
106
+        }
107
+    }
108
+
109
+    public function registerHookOnAction($actionName, $columnName, $fn)
110
+    {
111
+        if (is_string($fn) && is_callable([$this, $fn])) {
112
+            $fn = [$this, $fn];
113
+        }
114
+
115
+        if (!is_callable($fn)) { 
116
+            throw new ActiveRecordException("Provided hook on column \"$columnName\" is not callable", 0);
117
+        }
118
+
119
+        switch ($actionName) {
120
+            case self::CREATE:
121
+                $this->checkHookConstraints($columnName, $this->createHooks);
122
+                $this->createHooks[$columnName] = $fn;
123
+                break;
124
+            case self::READ:
125
+                $this->checkHookConstraints($columnName, $this->readHooks);
126
+                $this->readHooks[$columnName] = $fn;
127
+                break;
128
+            case self::UPDATE:
129
+                $this->checkHookConstraints($columnName, $this->updateHooks);
130
+                $this->updateHooks[$columnName] = $fn;
131
+                break;
132
+            case self::DELETE:
133
+                $this->checkHookConstraints($columnName, $this->deleteHooks);
134
+                $this->deleteHooks[$columnName] = $fn;
135
+                break;
136
+            case self::SEARCH:
137
+                $this->checkHookConstraints($columnName, $this->searchHooks);
138
+                $this->searchHooks[$columnName] = $fn;
139
+                break;
140
+            default:
141
+                throw new ActiveRecordException("Invalid action: Can not register hook on non-existing action");
142
+        }
143
+    }
144
+
145
+    /**
146
+     * Register a new hook for a specific column that gets called before execution of the create() method
147
+     * Only one hook per column can be registered at a time
148
+     * @param string $columnName The name of the column that is registered.
149
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
150
+     */
151
+    public function registerCreateHook($columnName, $fn)
152
+    {
153
+        $this->registerHookOnAction(self::CREATE, $columnName, $fn);
154
+    }
155
+
156
+    /**
157
+     * Register a new hook for a specific column that gets called before execution of the read() method
158
+     * Only one hook per column can be registered at a time
159
+     * @param string $columnName The name of the column that is registered.
160
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
161
+     */
162
+    public function registerReadHook($columnName, $fn)
163
+    {
164
+        $this->registerHookOnAction(self::READ, $columnName, $fn);
165
+    }
166
+
167
+    /**
168
+     * Register a new hook for a specific column that gets called before execution of the update() method
169
+     * Only one hook per column can be registered at a time
170
+     * @param string $columnName The name of the column that is registered.
171
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
172
+     */
173
+    public function registerUpdateHook($columnName, $fn)
174
+    {
175
+        $this->registerHookOnAction(self::UPDATE, $columnName, $fn);
176
+    }
177
+
178
+    /**
179
+     * Register a new hook for a specific column that gets called before execution of the delete() method
180
+     * Only one hook per column can be registered at a time
181
+     * @param string $columnName The name of the column that is registered.
182
+     * @param string|callable $fn Either a callable, or the name of a method on the inheriting object.
183
+     */
184
+    public function registerDeleteHook($columnName, $fn)
185
+    {
186
+        $this->registerHookOnAction(self::DELETE, $columnName, $fn);
187
+    }
188
+
189
+    /**
190
+     * Register a new hook for a specific column that gets called before execution of the search() method
191
+     * Only one hook per column can be registered at a time
192
+     * @param string $columnName The name of the column that is registered.
193
+     * @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; 
194
+     */
195
+    public function registerSearchHook($columnName, $fn)
196
+    {
197
+        $this->registerHookOnAction(self::SEARCH, $columnName, $fn);
198
+    }
199
+
200
+    /**
201
+     * Adds a new column definition to the table.
202
+     * @param string $columnName The name of the column that is registered.
203
+     * @param Array $definition The definition of that column.
204
+     */
205
+    protected function extendTableDefinition($columnName, $definition)
206
+    {
207
+        if ($this->tableDefinition === null) {
208
+            throw new ActiveRecordException("tableDefinition is null, has parent been initialized in constructor?");
209
+        }
210
+
211
+        // Enforcing table can only be extended with new columns
212
+        if (array_key_exists($columnName, $this->tableDefinition)) {
213
+            $message = "Table is being extended with a column that already exists, ";
214
+            $message .= "\"$columnName\" conflicts with your table definition";
215
+            throw new ActiveRecordException($message, 0);
216
+        }
217
+
218
+        $this->tableDefinition[$columnName] = $definition;
219
+    }
220
+
221
+    public function hasColumn(string $column) {
222
+        return array_key_exists($column, $this->tableDefinition);
223
+    }
224
+
225
+    public function hasRelation(string $column, AbstractActiveRecord $record) {
226
+        if (!$this->hasColumn($column)) {
227
+            throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
228
+        }
229
+
230
+        $relation = $this->tableDefinition[$column]['relation'] ?? null;
231
+        return $relation !== null && get_class($record) === get_class($relation);
232
+    }
233
+
234
+    public function hasProperty(string $column, $property) {
235
+        if (!$this->hasColumn($column)) {
236
+            throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
237
+        }
238
+
239
+        try {
240
+            $enumValue = ColumnProperty::valueOf($property);
241
+        } catch (\UnexpectedValueException $e) {
242
+            throw new ActiveRecordException("Provided property \"$property\" is not a valid property", 0, $e);
243
+        }
244
+
245
+        $properties = $this->tableDefinition[$column]['properties'] ?? null;
246
+
247
+        return $properties !== null && (($properties & $enumValue->getValue()) > 0);
248
+    }
249
+
250
+    public function getColumnType(string $column) {
251
+        if (!$this->hasColumn($column)) {
252
+            throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
253
+        }
254
+
255
+        return $this->tableDefinition[$column]['type'] ?? null;
256
+    }
257
+
258
+    public function getColumnLength(string $column) {
259
+        if (!$this->hasColumn($column)) {
260
+            throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
261
+        }
262
+
263
+        return $this->tableDefinition[$column]['length'] ?? null;
264
+    }
265
+
266
+    public function getDefault(string $column) {
267
+        if (!$this->hasColumn($column)) {
268
+            throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
269
+        }
270
+
271
+        return $this->tableDefinition[$column]['default'] ?? null;
272
+    }
273
+
274
+    public function validateColumn(string $column, $input) {
275
+        if (!$this->hasColumn($column)) {
276
+            throw new ActiveRecordException("Provided column \"$column\" does not exist in table definition", 0);
277
+        }
278
+
279
+        $fn = $this->tableDefinition[$column]['validate'] ?? null;
280
+
281
+        if ($fn === null) {
282
+            return [true, ''];
283
+        }
284
+
285
+        if (!is_callable($fn)) {
286
+            throw new ActiveRecordException("Provided validation function is not callable", 0);
287
+        }
288
+
289
+        return $fn($input);
290
+    }
291
+
292
+    /**
293
+     * Creates the entity as a table in the database
294
+     */
295
+    public function createTable()
296
+    {
297
+        $this->pdo->query(SchemaBuilder::buildCreateTableSQL($this->getTableName(), $this->tableDefinition));
298
+    }
299
+
300
+    /**
301
+     * Iterates over the specified constraints in the table definition, 
302
+     * 		and applies these to the database.
303
+     */
304
+    public function createTableConstraints()
305
+    {
306
+        // Iterate over columns, check whether "relation" field exists, if so create constraint
307
+        foreach ($this->tableDefinition as $colName => $definition) {
308
+            if (isset($definition['relation']) && $definition['relation'] instanceof AbstractActiveRecord) {
309
+                // Forge new relation
310
+                $target = $definition['relation'];
311
+                $properties = $definition['properties'] ?? 0;
312
+
313
+                if ($properties & ColumnProperty::NOT_NULL) {
314
+                    $constraintSql = SchemaBuilder::buildConstraintOnDeleteCascade($target->getTableName(), 'id', $this->getTableName(), $colName);
315
+                } else {
316
+                    $constraintSql = SchemaBuilder::buildConstraintOnDeleteSetNull($target->getTableName(), 'id', $this->getTableName(), $colName);
317
+                }
318
+
319
+                $this->pdo->query($constraintSql);
320
+            } else if (isset($definition['relation'])) {
321
+                $msg = sprintf("Relation constraint on column \"%s\" of table \"%s\" does not contain a valid ActiveRecord instance", 
322
+                    $colName,
323
+                    $this->getTableName());
324
+                throw new ActiveRecordException($msg);
325
+            }
326
+        }
327
+    }
328
+
329
+    /**
330
+     * Returns the name -> variable mapping for the table definition.
331
+     * @return Array The mapping
332
+     */
333
+    protected function getActiveRecordColumns()
334
+    {
335
+        $bindings = [];
336
+        foreach ($this->tableDefinition as $colName => $definition) {
337
+
338
+            // Ignore the id column (key) when inserting or updating
339
+            if ($colName == self::COLUMN_NAME_ID) {
340
+                continue;
341
+            }
342
+
343
+            $bindings[$colName] = &$definition['value'];
344
+        }
345
+        return $bindings;
346
+    }
347
+
348
+    protected function insertDefaults()
349
+    {
350
+        // Insert default values for not-null fields
351
+        foreach ($this->tableDefinition as $colName => $colDef) {
352
+            if ($colDef['value'] === null
353
+                && ($colDef['properties'] ?? 0) & ColumnProperty::NOT_NULL
354
+                && isset($colDef['default'])) {
355
+                $this->tableDefinition[$colName]['value'] = $colDef['default'];
356
+            }
357
+        }		
358
+    }
359
+
360
+    /**
361
+     * {@inheritdoc}
362
+     */
363
+    public function create()
364
+    {
365
+        foreach ($this->createHooks as $colName => $fn) {
366
+            $fn();
367
+        }
368
+
369
+        $this->insertDefaults();
370
+
371
+        try {
372
+            (new Query($this->getPdo(), $this->getTableName()))
373
+                ->insert($this->getActiveRecordColumns())
374
+                ->execute();
375
+
376
+            $this->setId(intval($this->getPdo()->lastInsertId()));
377
+        } catch (\PDOException $e) {
378
+            throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
379
+        }
380
+
381
+        return $this;
382
+    }
383
+
384
+    /**
385
+     * {@inheritdoc}
386
+     */
387
+    public function read($id)
388
+    {
389
+        $whereConditions = [
390
+            Query::Equal('id', $id)
391
+        ];
392
+        foreach ($this->readHooks as $colName => $fn) {
393
+            $cond = $fn();
394
+            if ($cond !== null) {
395
+                $whereConditions[] = $cond;
396
+            }
397
+        }
398
+
399
+        try {
400
+            $row = (new Query($this->getPdo(), $this->getTableName()))
401
+                ->select()
402
+                ->where(Query::AndArray($whereConditions))
403
+                ->execute()
404
+                ->fetch();
405 405
 			
406
-			if ($row === false) {
407
-				$msg = sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getTableName());
408
-				throw new ActiveRecordException($msg, ActiveRecordException::NOT_FOUND);
409
-			}
410
-
411
-			$this->fill($row)->setId($id);
412
-		} catch (\PDOException $e) {
413
-			throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
414
-		}
415
-
416
-		return $this;
417
-	}
418
-
419
-	/**
420
-	 * {@inheritdoc}
421
-	 */
422
-	public function update()
423
-	{
424
-		foreach ($this->updateHooks as $colName => $fn) {
425
-			$fn();
426
-		}
427
-
428
-		try {
429
-			(new Query($this->getPdo(), $this->getTableName()))
430
-				->update($this->getActiveRecordColumns())
431
-				->where(Query::Equal('id', $this->getId()))
432
-				->execute();
433
-		} catch (\PDOException $e) {
434
-			throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
435
-		}
436
-
437
-		return $this;
438
-	}
439
-
440
-	/**
441
-	 * {@inheritdoc}
442
-	 */
443
-	public function delete()
444
-	{
445
-		foreach ($this->deleteHooks as $colName => $fn) {
446
-			$fn();
447
-		}
448
-
449
-		try {
450
-			(new Query($this->getPdo(), $this->getTableName()))
451
-				->delete()
452
-				->where(Query::Equal('id', $this->getId()))
453
-				->execute();
454
-
455
-			$this->setId(null);
456
-		} catch (\PDOException $e) {
457
-			throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
458
-		}
459
-
460
-		return $this;
461
-	}
462
-
463
-	/**
464
-	 * {@inheritdoc}
465
-	 */
466
-	public function sync()
467
-	{
468
-		if (!$this->exists()) {
469
-			return $this->create();
470
-		}
471
-
472
-		return $this->update();
473
-	}
474
-
475
-	/**
476
-	 * {@inheritdoc}
477
-	 */
478
-	public function exists()
479
-	{
480
-		return $this->getId() !== null;
481
-	}
482
-
483
-	/**
484
-	 * {@inheritdoc}
485
-	 */
486
-	public function fill(array $attributes)
487
-	{
488
-		$columns = $this->getActiveRecordColumns();
489
-		$columns['id'] = &$this->id;
490
-
491
-		foreach ($attributes as $key => $value) {
492
-			if (array_key_exists($key, $columns)) {
493
-				$columns[$key] = $value;
494
-			}
495
-		}
496
-
497
-		return $this;
498
-	}
499
-
500
-	/**
501
-	 * Returns the serialized form of the specified columns
502
-	 * 
503
-	 * @return Array
504
-	 */
505
-	public function toArray(Array $fieldWhitelist)
506
-	{
507
-		$output = [];
508
-		foreach ($this->tableDefinition as $colName => $definition) {
509
-			if (in_array($colName, $fieldWhitelist)) {
510
-				$output[$colName] = $definition['value'];
511
-			}
512
-		}
513
-
514
-		return $output;
515
-	}
516
-
517
-	/**
518
-	 * {@inheritdoc}
519
-	 */
520
-	public function search(array $ignoredTraits = [])
521
-	{
522
-		$clauses = [];
523
-		foreach ($this->searchHooks as $column => $fn) {
524
-			if (!in_array($column, $ignoredTraits)) {
525
-				$clauses[] = $fn();
526
-			}
527
-		}
528
-
529
-		return new ActiveRecordQuery($this, $clauses);
530
-	}
531
-
532
-	/**
533
-	 * Returns the PDO.
534
-	 *
535
-	 * @return \PDO the PDO.
536
-	 */
537
-	public function getPdo()
538
-	{
539
-		return $this->pdo;
540
-	}
541
-
542
-	/**
543
-	 * Set the PDO.
544
-	 *
545
-	 * @param \PDO $pdo
546
-	 * @return $this
547
-	 */
548
-	protected function setPdo($pdo)
549
-	{
550
-		$this->pdo = $pdo;
551
-
552
-		return $this;
553
-	}
554
-
555
-	/**
556
-	 * Returns the ID.
557
-	 *
558
-	 * @return null|int The ID.
559
-	 */
560
-	public function getId()
561
-	{
562
-		return $this->id;
563
-	}
564
-
565
-	/**
566
-	 * Set the ID.
567
-	 *
568
-	 * @param int $id
569
-	 * @return $this
570
-	 */
571
-	protected function setId($id)
572
-	{
573
-		$this->id = $id;
574
-
575
-		return $this;
576
-	}
577
-
578
-	public function getFinalTableDefinition()
579
-	{
580
-		return $this->tableDefinition;
581
-	}
582
-
583
-	public function newInstance()
584
-	{
585
-		return new static($this->pdo);
586
-	}
587
-
588
-	/**
589
-	 * Returns the active record table.
590
-	 *
591
-	 * @return string the active record table name.
592
-	 */
593
-	abstract public function getTableName(): string;
594
-
595
-	/**
596
-	 * Returns the active record columns.
597
-	 *
598
-	 * @return array the active record columns.
599
-	 */
600
-	abstract protected function getTableDefinition(): Array;
406
+            if ($row === false) {
407
+                $msg = sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getTableName());
408
+                throw new ActiveRecordException($msg, ActiveRecordException::NOT_FOUND);
409
+            }
410
+
411
+            $this->fill($row)->setId($id);
412
+        } catch (\PDOException $e) {
413
+            throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
414
+        }
415
+
416
+        return $this;
417
+    }
418
+
419
+    /**
420
+     * {@inheritdoc}
421
+     */
422
+    public function update()
423
+    {
424
+        foreach ($this->updateHooks as $colName => $fn) {
425
+            $fn();
426
+        }
427
+
428
+        try {
429
+            (new Query($this->getPdo(), $this->getTableName()))
430
+                ->update($this->getActiveRecordColumns())
431
+                ->where(Query::Equal('id', $this->getId()))
432
+                ->execute();
433
+        } catch (\PDOException $e) {
434
+            throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
435
+        }
436
+
437
+        return $this;
438
+    }
439
+
440
+    /**
441
+     * {@inheritdoc}
442
+     */
443
+    public function delete()
444
+    {
445
+        foreach ($this->deleteHooks as $colName => $fn) {
446
+            $fn();
447
+        }
448
+
449
+        try {
450
+            (new Query($this->getPdo(), $this->getTableName()))
451
+                ->delete()
452
+                ->where(Query::Equal('id', $this->getId()))
453
+                ->execute();
454
+
455
+            $this->setId(null);
456
+        } catch (\PDOException $e) {
457
+            throw new ActiveRecordException($e->getMessage(), ActiveRecordException::DB_ERROR, $e);
458
+        }
459
+
460
+        return $this;
461
+    }
462
+
463
+    /**
464
+     * {@inheritdoc}
465
+     */
466
+    public function sync()
467
+    {
468
+        if (!$this->exists()) {
469
+            return $this->create();
470
+        }
471
+
472
+        return $this->update();
473
+    }
474
+
475
+    /**
476
+     * {@inheritdoc}
477
+     */
478
+    public function exists()
479
+    {
480
+        return $this->getId() !== null;
481
+    }
482
+
483
+    /**
484
+     * {@inheritdoc}
485
+     */
486
+    public function fill(array $attributes)
487
+    {
488
+        $columns = $this->getActiveRecordColumns();
489
+        $columns['id'] = &$this->id;
490
+
491
+        foreach ($attributes as $key => $value) {
492
+            if (array_key_exists($key, $columns)) {
493
+                $columns[$key] = $value;
494
+            }
495
+        }
496
+
497
+        return $this;
498
+    }
499
+
500
+    /**
501
+     * Returns the serialized form of the specified columns
502
+     * 
503
+     * @return Array
504
+     */
505
+    public function toArray(Array $fieldWhitelist)
506
+    {
507
+        $output = [];
508
+        foreach ($this->tableDefinition as $colName => $definition) {
509
+            if (in_array($colName, $fieldWhitelist)) {
510
+                $output[$colName] = $definition['value'];
511
+            }
512
+        }
513
+
514
+        return $output;
515
+    }
516
+
517
+    /**
518
+     * {@inheritdoc}
519
+     */
520
+    public function search(array $ignoredTraits = [])
521
+    {
522
+        $clauses = [];
523
+        foreach ($this->searchHooks as $column => $fn) {
524
+            if (!in_array($column, $ignoredTraits)) {
525
+                $clauses[] = $fn();
526
+            }
527
+        }
528
+
529
+        return new ActiveRecordQuery($this, $clauses);
530
+    }
531
+
532
+    /**
533
+     * Returns the PDO.
534
+     *
535
+     * @return \PDO the PDO.
536
+     */
537
+    public function getPdo()
538
+    {
539
+        return $this->pdo;
540
+    }
541
+
542
+    /**
543
+     * Set the PDO.
544
+     *
545
+     * @param \PDO $pdo
546
+     * @return $this
547
+     */
548
+    protected function setPdo($pdo)
549
+    {
550
+        $this->pdo = $pdo;
551
+
552
+        return $this;
553
+    }
554
+
555
+    /**
556
+     * Returns the ID.
557
+     *
558
+     * @return null|int The ID.
559
+     */
560
+    public function getId()
561
+    {
562
+        return $this->id;
563
+    }
564
+
565
+    /**
566
+     * Set the ID.
567
+     *
568
+     * @param int $id
569
+     * @return $this
570
+     */
571
+    protected function setId($id)
572
+    {
573
+        $this->id = $id;
574
+
575
+        return $this;
576
+    }
577
+
578
+    public function getFinalTableDefinition()
579
+    {
580
+        return $this->tableDefinition;
581
+    }
582
+
583
+    public function newInstance()
584
+    {
585
+        return new static($this->pdo);
586
+    }
587
+
588
+    /**
589
+     * Returns the active record table.
590
+     *
591
+     * @return string the active record table name.
592
+     */
593
+    abstract public function getTableName(): string;
594
+
595
+    /**
596
+     * Returns the active record columns.
597
+     *
598
+     * @return array the active record columns.
599
+     */
600
+    abstract protected function getTableDefinition(): Array;
601 601
 }
Please login to merge, or discard this patch.
src/Traits/AutoApi.php 1 patch
Indentation   +411 added lines, -411 removed lines patch added patch discarded remove patch
@@ -9,431 +9,431 @@
 block discarded – undo
9 9
 
10 10
 trait AutoApi
11 11
 {
12
-	/* =======================================================================
12
+    /* =======================================================================
13 13
 	 * ===================== Automatic API Support ===========================
14 14
 	 * ======================================================================= */
15 15
 
16
-	/** @var array A map of column name to functions that hook the insert function */
17
-	protected $createHooks;
16
+    /** @var array A map of column name to functions that hook the insert function */
17
+    protected $createHooks;
18 18
 
19
-	/** @var array A map of column name to functions that hook the read function */
20
-	protected $readHooks;
19
+    /** @var array A map of column name to functions that hook the read function */
20
+    protected $readHooks;
21 21
 
22
-	/** @var array A map of column name to functions that hook the update function */
23
-	protected $updateHooks;
22
+    /** @var array A map of column name to functions that hook the update function */
23
+    protected $updateHooks;
24 24
 
25
-	/** @var array A map of column name to functions that hook the update function */
26
-	protected $deleteHooks;	
25
+    /** @var array A map of column name to functions that hook the update function */
26
+    protected $deleteHooks;	
27 27
 
28
-	/** @var array A map of column name to functions that hook the search function */
29
-	protected $searchHooks;
28
+    /** @var array A map of column name to functions that hook the search function */
29
+    protected $searchHooks;
30 30
 
31
-	/** @var array A list of table column definitions */
32
-	protected $tableDefinition;
31
+    /** @var array A list of table column definitions */
32
+    protected $tableDefinition;
33 33
 
34 34
 
35
-	/**
36
-	 * @param Array $queryparams associative array of query params. Reserved options are
37
-	 *                             "search_order_by", "search_order_direction", "search_limit", "search_offset"
38
-	 *                             or column names corresponding to an instance of miBadger\Query\QueryExpression
39
-	 * @param Array $fieldWhitelist names of the columns that will appear in the output results
40
-	 * 
41
-	 * @return Array an associative array containing the query parameters, and a data field containing an array of search results (associative arrays indexed by the keys in $fieldWhitelist)
42
-	 */
43
-	public function apiSearch(Array $queryParams, Array $fieldWhitelist, ?QueryExpression $whereClause = null, int $maxResultLimit = 100): Array
44
-	{
45
-		$query = $this->search();
35
+    /**
36
+     * @param Array $queryparams associative array of query params. Reserved options are
37
+     *                             "search_order_by", "search_order_direction", "search_limit", "search_offset"
38
+     *                             or column names corresponding to an instance of miBadger\Query\QueryExpression
39
+     * @param Array $fieldWhitelist names of the columns that will appear in the output results
40
+     * 
41
+     * @return Array an associative array containing the query parameters, and a data field containing an array of search results (associative arrays indexed by the keys in $fieldWhitelist)
42
+     */
43
+    public function apiSearch(Array $queryParams, Array $fieldWhitelist, ?QueryExpression $whereClause = null, int $maxResultLimit = 100): Array
44
+    {
45
+        $query = $this->search();
46 46
 
47
-		// Build query
48
-		$orderColumn = $queryParams['search_order_by'] ?? null;
49
-		if (!in_array($orderColumn, $fieldWhitelist)) {
50
-			$orderColumn = null;
51
-		}
47
+        // Build query
48
+        $orderColumn = $queryParams['search_order_by'] ?? null;
49
+        if (!in_array($orderColumn, $fieldWhitelist)) {
50
+            $orderColumn = null;
51
+        }
52 52
 
53
-		$orderDirection = $queryParams['search_order_direction'] ?? null;
54
-		if ($orderColumn !== null) {
55
-			$query->orderBy($orderColumn, $orderDirection);
56
-		}
53
+        $orderDirection = $queryParams['search_order_direction'] ?? null;
54
+        if ($orderColumn !== null) {
55
+            $query->orderBy($orderColumn, $orderDirection);
56
+        }
57 57
 		
58
-		if ($whereClause !== null) {
59
-			$query->where($whereClause);
60
-		}
61
-
62
-		$limit = min((int) ($queryParams['search_limit'] ?? $maxResultLimit), $maxResultLimit);
63
-		$query->limit($limit);
64
-
65
-		$offset = $queryParams['search_offset'] ?? 0;
66
-		$query->offset($offset);
67
-
68
-		$numPages = $query->getNumberOfPages();
69
-		$currentPage = $query->getCurrentPage();
70
-
71
-		// Fetch results
72
-		$results = $query->fetchAll();
73
-		$resultsArray = [];
74
-		foreach ($results as $result) {
75
-			$resultsArray[] = $result->toArray($fieldWhitelist);
76
-		}
77
-
78
-		return [
79
-			'search_offset' => $offset,
80
-			'search_limit' => $limit,
81
-			'search_order_by' => $orderColumn,
82
-			'search_order_direction' => $orderDirection,
83
-			'search_pages' => $numPages,
84
-			'search_current' => $currentPage,
85
-			'data' => $resultsArray
86
-		];
87
-	}
88
-
89
-	/**
90
-	 * Performs a read call on the entity (modifying the current object) 
91
-	 * 	and returns a result array ($error, $data), with an optional error, and the results array (as filtered by the whitelist)
92
-	 * 	containing the loaded data.
93
-	 * 
94
-	 * @param string|int $id the id of the current entity
95
-	 * @param Array $fieldWhitelist an array of fields that are allowed to appear in the output
96
-	 * 
97
-	 * @param Array [$error, $result]
98
-	 * 				Where $error contains the error message (@TODO: & Error type?)
99
-	 * 				Where result is an associative array containing the data for this record, and the keys are a subset of $fieldWhitelist
100
-	 * 				
101
-	 */
102
-	public function apiRead($id, Array $fieldWhitelist = []): Array
103
-	{
104
-		try {
105
-			$this->read($id);	
106
-		} catch (ActiveRecordException $e) {
107
-			if ($e->getCode() === ActiveRecordException::NOT_FOUND) {
108
-				$err = [
109
-					'type' => 'invalid',
110
-					'message' => $e->getMessage()
111
-				];
112
-				return [$err, null];
113
-			}
114
-			throw $e;
115
-		}
116
-		return [null, $this->toArray($fieldWhitelist)];
117
-	}
118
-
119
-	/* =============================================================
58
+        if ($whereClause !== null) {
59
+            $query->where($whereClause);
60
+        }
61
+
62
+        $limit = min((int) ($queryParams['search_limit'] ?? $maxResultLimit), $maxResultLimit);
63
+        $query->limit($limit);
64
+
65
+        $offset = $queryParams['search_offset'] ?? 0;
66
+        $query->offset($offset);
67
+
68
+        $numPages = $query->getNumberOfPages();
69
+        $currentPage = $query->getCurrentPage();
70
+
71
+        // Fetch results
72
+        $results = $query->fetchAll();
73
+        $resultsArray = [];
74
+        foreach ($results as $result) {
75
+            $resultsArray[] = $result->toArray($fieldWhitelist);
76
+        }
77
+
78
+        return [
79
+            'search_offset' => $offset,
80
+            'search_limit' => $limit,
81
+            'search_order_by' => $orderColumn,
82
+            'search_order_direction' => $orderDirection,
83
+            'search_pages' => $numPages,
84
+            'search_current' => $currentPage,
85
+            'data' => $resultsArray
86
+        ];
87
+    }
88
+
89
+    /**
90
+     * Performs a read call on the entity (modifying the current object) 
91
+     * 	and returns a result array ($error, $data), with an optional error, and the results array (as filtered by the whitelist)
92
+     * 	containing the loaded data.
93
+     * 
94
+     * @param string|int $id the id of the current entity
95
+     * @param Array $fieldWhitelist an array of fields that are allowed to appear in the output
96
+     * 
97
+     * @param Array [$error, $result]
98
+     * 				Where $error contains the error message (@TODO: & Error type?)
99
+     * 				Where result is an associative array containing the data for this record, and the keys are a subset of $fieldWhitelist
100
+     * 				
101
+     */
102
+    public function apiRead($id, Array $fieldWhitelist = []): Array
103
+    {
104
+        try {
105
+            $this->read($id);	
106
+        } catch (ActiveRecordException $e) {
107
+            if ($e->getCode() === ActiveRecordException::NOT_FOUND) {
108
+                $err = [
109
+                    'type' => 'invalid',
110
+                    'message' => $e->getMessage()
111
+                ];
112
+                return [$err, null];
113
+            }
114
+            throw $e;
115
+        }
116
+        return [null, $this->toArray($fieldWhitelist)];
117
+    }
118
+
119
+    /* =============================================================
120 120
 	 * ===================== Constraint validation =================
121 121
 	 * ============================================================= */
122 122
 
123
-	/**
124
-	 * Copy all table variables between two instances
125
-	 */
126
-	public function syncInstanceFrom($from)
127
-	{
128
-		foreach ($this->tableDefinition as $colName => $definition) {
129
-			$this->tableDefinition[$colName]['value'] = $from->tableDefinition[$colName]['value'];
130
-		}
131
-	}
132
-
133
-	private function filterInputColumns($input, $whitelist)
134
-	{
135
-		$filteredInput = $input;
136
-		foreach ($input as $colName => $value) {
137
-			if (!in_array($colName, $whitelist)) {
138
-				unset($filteredInput[$colName]);
139
-			}
140
-		}
141
-		return $filteredInput;
142
-	}
143
-
144
-	private function validateExcessKeys($input)
145
-	{
146
-		$errors = [];
147
-		foreach ($input as $colName => $value) {
148
-			if (!array_key_exists($colName, $this->tableDefinition)) {
149
-				$errors[$colName] = [
150
-					'type' => 'unknown_field',
151
-					'message' => 'Unknown input field'
152
-				];
153
-				continue;
154
-			}
155
-		}
156
-		return $errors;
157
-	}
158
-
159
-	private function validateImmutableColumns($input)
160
-	{
161
-		$errors = [];
162
-		foreach ($this->tableDefinition as $colName => $definition) {
163
-			$property = $definition['properties'] ?? null;
164
-			if (array_key_exists($colName, $input)
165
-				&& $property & ColumnProperty::IMMUTABLE) {
166
-				$errors[$colName] = [
167
-					'type' => 'immutable',
168
-					'message' => 'Value cannot be changed'
169
-				];
170
-			}
171
-		}
172
-		return $errors;
173
-	}
174
-
175
-	/**
176
-	 * Checks whether input values are correct:
177
-	 * 1. Checks whether a value passes the validation function for that column
178
-	 * 2. Checks whether a value supplied to a relationship column is a valid value
179
-	 */
180
-	private function validateInputValues($input)
181
-	{
182
-		$errors = [];
183
-		foreach ($this->tableDefinition as $colName => $definition) {
184
-			// Validation check 1: If validate function is present
185
-			if (array_key_exists($colName, $input) 
186
-				&& is_callable($definition['validate'] ?? null)) {
187
-				$inputValue = $input[$colName];
188
-
189
-				// If validation function fails
190
-				[$status, $message] = $definition['validate']($inputValue);
191
-				if (!$status) {
192
-					$errors[$colName] = [
193
-						'type' => 'invalid',
194
-						'message' => $message
195
-					];
196
-				}	
197
-			}
198
-
199
-			// Validation check 2: If relation column, check whether entity exists
200
-			$properties = $definition['properties'] ?? null;
201
-			if (isset($definition['relation'])
202
-				&& ($properties & ColumnProperty::NOT_NULL)) {
203
-				$instance = clone $definition['relation'];
204
-				try {
205
-					$instance->read($input[$colName] ?? $definition['value'] ?? null);
206
-				} catch (ActiveRecordException $e) {
207
-					$errors[$colName] = [
208
-						'type' => 'invalid',
209
-						'message' => 'Entry for this value does not exist'
210
-					];
211
-				}
212
-			}
213
-		}
214
-		return $errors;
215
-	}
216
-
217
-	/**
218
-	 * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
219
-	 * Determines whether there are required columns for which no data is provided
220
-	 */
221
-	private function validateMissingKeys($input)
222
-	{
223
-		$errors = [];
224
-
225
-		foreach ($this->tableDefinition as $colName => $colDefinition) {
226
-			$default = $colDefinition['default'] ?? null;
227
-			$properties = $colDefinition['properties'] ?? null;
228
-			$value = $colDefinition['value'];
229
-
230
-			// If nullable and default not set => null
231
-			// If nullable and default null => default (null)
232
-			// If nullable and default set => default (value)
233
-
234
-			// if not nullable and default not set => error
235
-			// if not nullable and default null => error
236
-			// if not nullable and default st => default (value)
237
-			// => if not nullable and default null and value not set (or null) => error message in this method
238
-			if ($properties & ColumnProperty::NOT_NULL
239
-				&& $default === null
240
-				&& !($properties & ColumnProperty::AUTO_INCREMENT)
241
-				&& (!array_key_exists($colName, $input) 
242
-					|| $input[$colName] === null 
243
-					|| (is_string($input[$colName]) && $input[$colName] === '') )
244
-				&& ($value === null
245
-					|| (is_string($value) && $value === ''))) {
246
-				$errors[$colName] = [
247
-					'type' => 'missing',
248
-					'message' => sprintf("The required field \"%s\" is missing", $colName)
249
-				];
250
-			} 
251
-		}
252
-
253
-		return $errors;
254
-	}
255
-
256
-	/**
257
-	 * Copies the values for entries in the input with matching variable names in the record definition
258
-	 * @param Array $input The input data to be loaded into $this record
259
-	 */
260
-	private function loadData($input)
261
-	{
262
-		foreach ($this->tableDefinition as $colName => $definition) {
263
-			// Skip if this table column does not appear in the input
264
-			if (!array_key_exists($colName, $input)) {
265
-				continue;
266
-			}
267
-
268
-			// Use setter if known, otherwise set value directly
269
-			$fn = $definition['setter'] ?? null;
270
-			if (is_callable($fn)) {
271
-				$fn($input[$colName]);
272
-			} else {
273
-				$definition['value'] = $input[$colName];
274
-			}
275
-		}
276
-	}
277
-
278
-	/**
279
-	 * @param Array $input Associative array of input values
280
-	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
281
-	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
282
-	 * 					of the modified data.
283
-	 */
284
-	public function apiCreate(Array $input, Array $createWhitelist, Array $readWhitelist)
285
-	{
286
-		// Clone $this to new instance (for restoring if validation goes wrong)
287
-		$transaction = $this->newInstance();
288
-		$errors = [];
289
-
290
-		// Filter out all non-whitelisted input values
291
-		$input = $this->filterInputColumns($input, $createWhitelist);
292
-
293
-		// Validate excess keys
294
-		$errors += $transaction->validateExcessKeys($input);
295
-
296
-		// Validate input values (using validation function)
297
-		$errors += $transaction->validateInputValues($input);
298
-
299
-		// "Copy" data into transaction
300
-		$transaction->loadData($input);
301
-
302
-		// Run create hooks
303
-		foreach ($transaction->createHooks as $colName => $fn) {
304
-			$fn();
305
-		}
306
-
307
-		// Validate missing keys
308
-		$errors += $transaction->validateMissingKeys($input);
309
-
310
-		// If no errors, commit the pending data
311
-		if (empty($errors)) {
312
-			$this->syncInstanceFrom($transaction);
313
-
314
-			// Insert default values for not-null fields
315
-			$this->insertDefaults();
316
-
317
-			try {
318
-				(new Query($this->getPdo(), $this->getTableName()))
319
-					->insert($this->getActiveRecordColumns())
320
-					->execute();
321
-
322
-				$this->setId(intval($this->getPdo()->lastInsertId()));
323
-			} catch (\PDOException $e) {
324
-				// @TODO: Potentially filter and store mysql messages (where possible) in error messages
325
-				throw new ActiveRecordException($e->getMessage(), 0, $e);
326
-			}
327
-
328
-			return [null, $this->toArray($readWhitelist)];
329
-		} else {
330
-			return [$errors, null];
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * @param Array $input Associative array of input values
336
-	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
337
-	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
338
-	 * 					of the modified data.
339
-	 */
340
-	public function apiUpdate(Array $input, Array $updateWhitelist, Array $readWhitelist)
341
-	{
342
-		$transaction = $this->newInstance();
343
-		$transaction->syncInstanceFrom($this);
344
-		$errors = [];
345
-
346
-		// Filter out all non-whitelisted input values
347
-		$input = $this->filterInputColumns($input, $updateWhitelist);
348
-
349
-		// Check for excess keys
350
-		$errors += $transaction->validateExcessKeys($input);
351
-
352
-		// Check for immutable keys
353
-		$errors += $transaction->validateImmutableColumns($input);
354
-
355
-		// Validate input values (using validation function)
356
-		$errors += $transaction->validateInputValues($input);
357
-
358
-		// "Copy" data into transaction
359
-		$transaction->loadData($input);
360
-
361
-		// Run create hooks
362
-		foreach ($transaction->updateHooks as $colName => $fn) {
363
-			$fn();
364
-		}
365
-
366
-		// Validate missing keys
367
-		$errors += $transaction->validateMissingKeys($input);
368
-
369
-		// Update database
370
-		if (empty($errors)) {
371
-			$this->syncInstanceFrom($transaction);
372
-
373
-			try {
374
-				(new Query($this->getPdo(), $this->getTableName()))
375
-					->update($this->getActiveRecordColumns())
376
-					->where(Query::Equal('id', $this->getId()))
377
-					->execute();
378
-			} catch (\PDOException $e) {
379
-				throw new ActiveRecordException($e->getMessage(), 0, $e);
380
-			}
381
-
382
-			return [null, $this->toArray($readWhitelist)];
383
-		} else {
384
-			return [$errors, null];
385
-		}
386
-	}
387
-
388
-	/**
389
-	 * Returns this active record after reading the attributes from the entry with the given identifier.
390
-	 *
391
-	 * @param mixed $id
392
-	 * @return $this
393
-	 * @throws ActiveRecordException on failure.
394
-	 */
395
-	abstract public function read($id);
396
-
397
-	/**
398
-	 * Returns the PDO.
399
-	 *
400
-	 * @return \PDO the PDO.
401
-	 */
402
-	abstract public function getPdo();
403
-
404
-	/**
405
-	 * Set the ID.
406
-	 *
407
-	 * @param int $id
408
-	 * @return $this
409
-	 */
410
-	abstract protected function setId($id);
411
-
412
-	/**
413
-	 * Returns the ID.
414
-	 *
415
-	 * @return null|int The ID.
416
-	 */
417
-	abstract protected function getId();
418
-
419
-
420
-	/**
421
-	 * Returns the serialized form of the specified columns
422
-	 * 
423
-	 * @return Array
424
-	 */
425
-	abstract public function toArray(Array $fieldWhitelist);
426
-
427
-	/**
428
-	 * Returns the active record table.
429
-	 *
430
-	 * @return string the active record table name.
431
-	 */
432
-	abstract public function getTableName();
433
-
434
-	/**
435
-	 * Returns the name -> variable mapping for the table definition.
436
-	 * @return Array The mapping
437
-	 */
438
-	abstract protected function getActiveRecordColumns();
123
+    /**
124
+     * Copy all table variables between two instances
125
+     */
126
+    public function syncInstanceFrom($from)
127
+    {
128
+        foreach ($this->tableDefinition as $colName => $definition) {
129
+            $this->tableDefinition[$colName]['value'] = $from->tableDefinition[$colName]['value'];
130
+        }
131
+    }
132
+
133
+    private function filterInputColumns($input, $whitelist)
134
+    {
135
+        $filteredInput = $input;
136
+        foreach ($input as $colName => $value) {
137
+            if (!in_array($colName, $whitelist)) {
138
+                unset($filteredInput[$colName]);
139
+            }
140
+        }
141
+        return $filteredInput;
142
+    }
143
+
144
+    private function validateExcessKeys($input)
145
+    {
146
+        $errors = [];
147
+        foreach ($input as $colName => $value) {
148
+            if (!array_key_exists($colName, $this->tableDefinition)) {
149
+                $errors[$colName] = [
150
+                    'type' => 'unknown_field',
151
+                    'message' => 'Unknown input field'
152
+                ];
153
+                continue;
154
+            }
155
+        }
156
+        return $errors;
157
+    }
158
+
159
+    private function validateImmutableColumns($input)
160
+    {
161
+        $errors = [];
162
+        foreach ($this->tableDefinition as $colName => $definition) {
163
+            $property = $definition['properties'] ?? null;
164
+            if (array_key_exists($colName, $input)
165
+                && $property & ColumnProperty::IMMUTABLE) {
166
+                $errors[$colName] = [
167
+                    'type' => 'immutable',
168
+                    'message' => 'Value cannot be changed'
169
+                ];
170
+            }
171
+        }
172
+        return $errors;
173
+    }
174
+
175
+    /**
176
+     * Checks whether input values are correct:
177
+     * 1. Checks whether a value passes the validation function for that column
178
+     * 2. Checks whether a value supplied to a relationship column is a valid value
179
+     */
180
+    private function validateInputValues($input)
181
+    {
182
+        $errors = [];
183
+        foreach ($this->tableDefinition as $colName => $definition) {
184
+            // Validation check 1: If validate function is present
185
+            if (array_key_exists($colName, $input) 
186
+                && is_callable($definition['validate'] ?? null)) {
187
+                $inputValue = $input[$colName];
188
+
189
+                // If validation function fails
190
+                [$status, $message] = $definition['validate']($inputValue);
191
+                if (!$status) {
192
+                    $errors[$colName] = [
193
+                        'type' => 'invalid',
194
+                        'message' => $message
195
+                    ];
196
+                }	
197
+            }
198
+
199
+            // Validation check 2: If relation column, check whether entity exists
200
+            $properties = $definition['properties'] ?? null;
201
+            if (isset($definition['relation'])
202
+                && ($properties & ColumnProperty::NOT_NULL)) {
203
+                $instance = clone $definition['relation'];
204
+                try {
205
+                    $instance->read($input[$colName] ?? $definition['value'] ?? null);
206
+                } catch (ActiveRecordException $e) {
207
+                    $errors[$colName] = [
208
+                        'type' => 'invalid',
209
+                        'message' => 'Entry for this value does not exist'
210
+                    ];
211
+                }
212
+            }
213
+        }
214
+        return $errors;
215
+    }
216
+
217
+    /**
218
+     * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
219
+     * Determines whether there are required columns for which no data is provided
220
+     */
221
+    private function validateMissingKeys($input)
222
+    {
223
+        $errors = [];
224
+
225
+        foreach ($this->tableDefinition as $colName => $colDefinition) {
226
+            $default = $colDefinition['default'] ?? null;
227
+            $properties = $colDefinition['properties'] ?? null;
228
+            $value = $colDefinition['value'];
229
+
230
+            // If nullable and default not set => null
231
+            // If nullable and default null => default (null)
232
+            // If nullable and default set => default (value)
233
+
234
+            // if not nullable and default not set => error
235
+            // if not nullable and default null => error
236
+            // if not nullable and default st => default (value)
237
+            // => if not nullable and default null and value not set (or null) => error message in this method
238
+            if ($properties & ColumnProperty::NOT_NULL
239
+                && $default === null
240
+                && !($properties & ColumnProperty::AUTO_INCREMENT)
241
+                && (!array_key_exists($colName, $input) 
242
+                    || $input[$colName] === null 
243
+                    || (is_string($input[$colName]) && $input[$colName] === '') )
244
+                && ($value === null
245
+                    || (is_string($value) && $value === ''))) {
246
+                $errors[$colName] = [
247
+                    'type' => 'missing',
248
+                    'message' => sprintf("The required field \"%s\" is missing", $colName)
249
+                ];
250
+            } 
251
+        }
252
+
253
+        return $errors;
254
+    }
255
+
256
+    /**
257
+     * Copies the values for entries in the input with matching variable names in the record definition
258
+     * @param Array $input The input data to be loaded into $this record
259
+     */
260
+    private function loadData($input)
261
+    {
262
+        foreach ($this->tableDefinition as $colName => $definition) {
263
+            // Skip if this table column does not appear in the input
264
+            if (!array_key_exists($colName, $input)) {
265
+                continue;
266
+            }
267
+
268
+            // Use setter if known, otherwise set value directly
269
+            $fn = $definition['setter'] ?? null;
270
+            if (is_callable($fn)) {
271
+                $fn($input[$colName]);
272
+            } else {
273
+                $definition['value'] = $input[$colName];
274
+            }
275
+        }
276
+    }
277
+
278
+    /**
279
+     * @param Array $input Associative array of input values
280
+     * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
281
+     * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
282
+     * 					of the modified data.
283
+     */
284
+    public function apiCreate(Array $input, Array $createWhitelist, Array $readWhitelist)
285
+    {
286
+        // Clone $this to new instance (for restoring if validation goes wrong)
287
+        $transaction = $this->newInstance();
288
+        $errors = [];
289
+
290
+        // Filter out all non-whitelisted input values
291
+        $input = $this->filterInputColumns($input, $createWhitelist);
292
+
293
+        // Validate excess keys
294
+        $errors += $transaction->validateExcessKeys($input);
295
+
296
+        // Validate input values (using validation function)
297
+        $errors += $transaction->validateInputValues($input);
298
+
299
+        // "Copy" data into transaction
300
+        $transaction->loadData($input);
301
+
302
+        // Run create hooks
303
+        foreach ($transaction->createHooks as $colName => $fn) {
304
+            $fn();
305
+        }
306
+
307
+        // Validate missing keys
308
+        $errors += $transaction->validateMissingKeys($input);
309
+
310
+        // If no errors, commit the pending data
311
+        if (empty($errors)) {
312
+            $this->syncInstanceFrom($transaction);
313
+
314
+            // Insert default values for not-null fields
315
+            $this->insertDefaults();
316
+
317
+            try {
318
+                (new Query($this->getPdo(), $this->getTableName()))
319
+                    ->insert($this->getActiveRecordColumns())
320
+                    ->execute();
321
+
322
+                $this->setId(intval($this->getPdo()->lastInsertId()));
323
+            } catch (\PDOException $e) {
324
+                // @TODO: Potentially filter and store mysql messages (where possible) in error messages
325
+                throw new ActiveRecordException($e->getMessage(), 0, $e);
326
+            }
327
+
328
+            return [null, $this->toArray($readWhitelist)];
329
+        } else {
330
+            return [$errors, null];
331
+        }
332
+    }
333
+
334
+    /**
335
+     * @param Array $input Associative array of input values
336
+     * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
337
+     * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
338
+     * 					of the modified data.
339
+     */
340
+    public function apiUpdate(Array $input, Array $updateWhitelist, Array $readWhitelist)
341
+    {
342
+        $transaction = $this->newInstance();
343
+        $transaction->syncInstanceFrom($this);
344
+        $errors = [];
345
+
346
+        // Filter out all non-whitelisted input values
347
+        $input = $this->filterInputColumns($input, $updateWhitelist);
348
+
349
+        // Check for excess keys
350
+        $errors += $transaction->validateExcessKeys($input);
351
+
352
+        // Check for immutable keys
353
+        $errors += $transaction->validateImmutableColumns($input);
354
+
355
+        // Validate input values (using validation function)
356
+        $errors += $transaction->validateInputValues($input);
357
+
358
+        // "Copy" data into transaction
359
+        $transaction->loadData($input);
360
+
361
+        // Run create hooks
362
+        foreach ($transaction->updateHooks as $colName => $fn) {
363
+            $fn();
364
+        }
365
+
366
+        // Validate missing keys
367
+        $errors += $transaction->validateMissingKeys($input);
368
+
369
+        // Update database
370
+        if (empty($errors)) {
371
+            $this->syncInstanceFrom($transaction);
372
+
373
+            try {
374
+                (new Query($this->getPdo(), $this->getTableName()))
375
+                    ->update($this->getActiveRecordColumns())
376
+                    ->where(Query::Equal('id', $this->getId()))
377
+                    ->execute();
378
+            } catch (\PDOException $e) {
379
+                throw new ActiveRecordException($e->getMessage(), 0, $e);
380
+            }
381
+
382
+            return [null, $this->toArray($readWhitelist)];
383
+        } else {
384
+            return [$errors, null];
385
+        }
386
+    }
387
+
388
+    /**
389
+     * Returns this active record after reading the attributes from the entry with the given identifier.
390
+     *
391
+     * @param mixed $id
392
+     * @return $this
393
+     * @throws ActiveRecordException on failure.
394
+     */
395
+    abstract public function read($id);
396
+
397
+    /**
398
+     * Returns the PDO.
399
+     *
400
+     * @return \PDO the PDO.
401
+     */
402
+    abstract public function getPdo();
403
+
404
+    /**
405
+     * Set the ID.
406
+     *
407
+     * @param int $id
408
+     * @return $this
409
+     */
410
+    abstract protected function setId($id);
411
+
412
+    /**
413
+     * Returns the ID.
414
+     *
415
+     * @return null|int The ID.
416
+     */
417
+    abstract protected function getId();
418
+
419
+
420
+    /**
421
+     * Returns the serialized form of the specified columns
422
+     * 
423
+     * @return Array
424
+     */
425
+    abstract public function toArray(Array $fieldWhitelist);
426
+
427
+    /**
428
+     * Returns the active record table.
429
+     *
430
+     * @return string the active record table name.
431
+     */
432
+    abstract public function getTableName();
433
+
434
+    /**
435
+     * Returns the name -> variable mapping for the table definition.
436
+     * @return Array The mapping
437
+     */
438
+    abstract protected function getActiveRecordColumns();
439 439
 }
Please login to merge, or discard this patch.