Test Failed
Push — v2 ( 00665d...c532d8 )
by Berend
04:26
created
src/SchemaBuilder.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -18,157 +18,157 @@
 block discarded – undo
18 18
  */
19 19
 class SchemaBuilder
20 20
 {
21
-	/**
22
-	 * builds a MySQL constraint statement for the given parameters
23
-	 * @param string $parentTable
24
-	 * @param string $parentColumn
25
-	 * @param string $childTable
26
-	 * @param string $childColumn
27
-	 * @return string The MySQL table constraint string
28
-	 */
29
-	public static function buildConstraint($parentTable, $parentColumn, $childTable, $childColumn)
30
-	{
31
-		$template = <<<SQL
21
+    /**
22
+     * builds a MySQL constraint statement for the given parameters
23
+     * @param string $parentTable
24
+     * @param string $parentColumn
25
+     * @param string $childTable
26
+     * @param string $childColumn
27
+     * @return string The MySQL table constraint string
28
+     */
29
+    public static function buildConstraint($parentTable, $parentColumn, $childTable, $childColumn)
30
+    {
31
+        $template = <<<SQL
32 32
 ALTER TABLE `%s`
33 33
 ADD CONSTRAINT
34 34
 FOREIGN KEY (`%s`)
35 35
 REFERENCES `%s`(`%s`)
36 36
 ON DELETE CASCADE;
37 37
 SQL;
38
-		return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
39
-	}
40
-
41
-	/**
42
-	 * Returns the type string as it should appear in the mysql create table statement for the given column
43
-	 * @return string The type string
44
-	 */
45
-	public static function getDatabaseTypeString($colName, $type, $length)
46
-	{
47
-		switch (strtoupper($type)) {
48
-			case '':
49
-				throw new ActiveRecordException(sprintf("Column %s has invalid type \"NULL\"", $colName));
38
+        return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
39
+    }
40
+
41
+    /**
42
+     * Returns the type string as it should appear in the mysql create table statement for the given column
43
+     * @return string The type string
44
+     */
45
+    public static function getDatabaseTypeString($colName, $type, $length)
46
+    {
47
+        switch (strtoupper($type)) {
48
+            case '':
49
+                throw new ActiveRecordException(sprintf("Column %s has invalid type \"NULL\"", $colName));
50 50
 			
51
-			case 'BOOL';
52
-			case 'BOOLEAN':
53
-			case 'DATETIME':
54
-			case 'DATE':
55
-			case 'TIME':
56
-			case 'TEXT':
57
-			case 'INT UNSIGNED':
58
-				return $type;
59
-
60
-			case 'VARCHAR':
61
-				if ($length === null) {
62
-					throw new ActiveRecordException(sprintf("field type %s requires specified column field \"LENGTH\"", $colName));
63
-				} else {
64
-					return sprintf('%s(%d)', $type, $length);	
65
-				}
66
-
67
-			case 'INT':
68
-			case 'TINYINT':
69
-			case 'BIGINT':
70
-			default: 	
71
-				// Implicitly assuming that non-specified cases are correct without a length parameter
72
-				if ($length === null) {
73
-					return $type;
74
-				} else {
75
-					return sprintf('%s(%d)', $type, $length);	
76
-				}
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Builds the part of a MySQL create table statement that corresponds to the supplied column
82
-	 * @param string $colName 	Name of the database column
83
-	 * @param string $type 		The type of the string
84
-	 * @param int $properties 	The set of Column properties that apply to this column (See ColumnProperty for options)
85
-	 * @return string
86
-	 */
87
-	public static function buildCreateTableColumnEntry($colName, $type, $length, $properties, $default)
88
-	{
89
-		$stmnt = sprintf('`%s` %s ', $colName, self::getDatabaseTypeString($colName, $type, $length));
90
-		if ($properties & ColumnProperty::NOT_NULL) {
91
-			$stmnt .= 'NOT NULL ';
92
-		} else {
93
-			$stmnt .= 'NULL ';
94
-		}
95
-
96
-		if ($default !== NULL) {
97
-			$stmnt .= 'DEFAULT ' . var_export($default, true) . ' ';
98
-		}
99
-
100
-		if ($properties & ColumnProperty::AUTO_INCREMENT) {
101
-			$stmnt .= 'AUTO_INCREMENT ';
102
-		}
103
-
104
-		if ($properties & ColumnProperty::UNIQUE) {
105
-			$stmnt .= 'UNIQUE ';
106
-		}
107
-
108
-		if ($properties & ColumnProperty::PRIMARY_KEY) {
109
-			$stmnt .= 'PRIMARY KEY ';
110
-		}
111
-
112
-		return $stmnt;
113
-	}
114
-
115
-	/**
116
-	 * Sorts the column statement components in the order such that the id appears first, 
117
-	 * 		followed by all other columns in alphabetical ascending order
118
-	 * @param   Array $colStatements Array of column statements
119
-	 * @return  Array
120
-	 */
121
-	private static function sortColumnStatements($colStatements)
122
-	{
123
-		// Find ID statement and put it first
124
-		$sortedStatements = [];
125
-
126
-		$sortedStatements[] = $colStatements[AbstractActiveRecord::COLUMN_NAME_ID];
127
-		unset($colStatements[AbstractActiveRecord::COLUMN_NAME_ID]);
128
-
129
-		// Sort remaining columns in alphabetical order
130
-		$columns = array_keys($colStatements);
131
-		sort($columns);
132
-		foreach ($columns as $colName) {
133
-			$sortedStatements[] = $colStatements[$colName];
134
-		}
135
-
136
-		return $sortedStatements;
137
-	}
138
-
139
-	/**
140
-	 * Builds the MySQL Create Table statement for the internal table definition
141
-	 * @return string
142
-	 */
143
-	public static function buildCreateTableSQL($tableName, $tableDefinition)
144
-	{
145
-		$columnStatements = [];
146
-		foreach ($tableDefinition as $colName => $definition) {
147
-			// Destructure column definition
148
-			$type    = $definition['type'] ?? null;
149
-			$default = $definition['default'] ?? null;
150
-			$length  = $definition['length'] ?? null;
151
-			$properties = $definition['properties'] ?? null;
152
-
153
-			if (isset($definition['relation']) && $type !== null) {
154
-				$msg = sprintf("Column \"%s\" on table \"%s\": ", $colName, $tableName);
155
-				$msg .= "Relationship columns have an automatically inferred type, so type should be omitted";
156
-				throw new ActiveRecordException($msg);
157
-			} else if (isset($definition['relation'])) {
158
-				$type = AbstractActiveRecord::COLUMN_TYPE_ID;
159
-			}
160
-
161
-			$columnStatements[$colName] = self::buildCreateTableColumnEntry($colName, $type, $length, $properties, $default);
162
-		}
163
-
164
-		// Sort table (first column is id, the remaining are alphabetically sorted)
165
-		$columnStatements = self::sortColumnStatements($columnStatements);
166
-
167
-		$sql = sprintf("CREATE TABLE %s (\n%s\n);", 
168
-			$tableName, 
169
-			implode(",\n", $columnStatements));
170
-
171
-		return $sql;
172
-	}
51
+            case 'BOOL';
52
+            case 'BOOLEAN':
53
+            case 'DATETIME':
54
+            case 'DATE':
55
+            case 'TIME':
56
+            case 'TEXT':
57
+            case 'INT UNSIGNED':
58
+                return $type;
59
+
60
+            case 'VARCHAR':
61
+                if ($length === null) {
62
+                    throw new ActiveRecordException(sprintf("field type %s requires specified column field \"LENGTH\"", $colName));
63
+                } else {
64
+                    return sprintf('%s(%d)', $type, $length);	
65
+                }
66
+
67
+            case 'INT':
68
+            case 'TINYINT':
69
+            case 'BIGINT':
70
+            default: 	
71
+                // Implicitly assuming that non-specified cases are correct without a length parameter
72
+                if ($length === null) {
73
+                    return $type;
74
+                } else {
75
+                    return sprintf('%s(%d)', $type, $length);	
76
+                }
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Builds the part of a MySQL create table statement that corresponds to the supplied column
82
+     * @param string $colName 	Name of the database column
83
+     * @param string $type 		The type of the string
84
+     * @param int $properties 	The set of Column properties that apply to this column (See ColumnProperty for options)
85
+     * @return string
86
+     */
87
+    public static function buildCreateTableColumnEntry($colName, $type, $length, $properties, $default)
88
+    {
89
+        $stmnt = sprintf('`%s` %s ', $colName, self::getDatabaseTypeString($colName, $type, $length));
90
+        if ($properties & ColumnProperty::NOT_NULL) {
91
+            $stmnt .= 'NOT NULL ';
92
+        } else {
93
+            $stmnt .= 'NULL ';
94
+        }
95
+
96
+        if ($default !== NULL) {
97
+            $stmnt .= 'DEFAULT ' . var_export($default, true) . ' ';
98
+        }
99
+
100
+        if ($properties & ColumnProperty::AUTO_INCREMENT) {
101
+            $stmnt .= 'AUTO_INCREMENT ';
102
+        }
103
+
104
+        if ($properties & ColumnProperty::UNIQUE) {
105
+            $stmnt .= 'UNIQUE ';
106
+        }
107
+
108
+        if ($properties & ColumnProperty::PRIMARY_KEY) {
109
+            $stmnt .= 'PRIMARY KEY ';
110
+        }
111
+
112
+        return $stmnt;
113
+    }
114
+
115
+    /**
116
+     * Sorts the column statement components in the order such that the id appears first, 
117
+     * 		followed by all other columns in alphabetical ascending order
118
+     * @param   Array $colStatements Array of column statements
119
+     * @return  Array
120
+     */
121
+    private static function sortColumnStatements($colStatements)
122
+    {
123
+        // Find ID statement and put it first
124
+        $sortedStatements = [];
125
+
126
+        $sortedStatements[] = $colStatements[AbstractActiveRecord::COLUMN_NAME_ID];
127
+        unset($colStatements[AbstractActiveRecord::COLUMN_NAME_ID]);
128
+
129
+        // Sort remaining columns in alphabetical order
130
+        $columns = array_keys($colStatements);
131
+        sort($columns);
132
+        foreach ($columns as $colName) {
133
+            $sortedStatements[] = $colStatements[$colName];
134
+        }
135
+
136
+        return $sortedStatements;
137
+    }
138
+
139
+    /**
140
+     * Builds the MySQL Create Table statement for the internal table definition
141
+     * @return string
142
+     */
143
+    public static function buildCreateTableSQL($tableName, $tableDefinition)
144
+    {
145
+        $columnStatements = [];
146
+        foreach ($tableDefinition as $colName => $definition) {
147
+            // Destructure column definition
148
+            $type    = $definition['type'] ?? null;
149
+            $default = $definition['default'] ?? null;
150
+            $length  = $definition['length'] ?? null;
151
+            $properties = $definition['properties'] ?? null;
152
+
153
+            if (isset($definition['relation']) && $type !== null) {
154
+                $msg = sprintf("Column \"%s\" on table \"%s\": ", $colName, $tableName);
155
+                $msg .= "Relationship columns have an automatically inferred type, so type should be omitted";
156
+                throw new ActiveRecordException($msg);
157
+            } else if (isset($definition['relation'])) {
158
+                $type = AbstractActiveRecord::COLUMN_TYPE_ID;
159
+            }
160
+
161
+            $columnStatements[$colName] = self::buildCreateTableColumnEntry($colName, $type, $length, $properties, $default);
162
+        }
163
+
164
+        // Sort table (first column is id, the remaining are alphabetically sorted)
165
+        $columnStatements = self::sortColumnStatements($columnStatements);
166
+
167
+        $sql = sprintf("CREATE TABLE %s (\n%s\n);", 
168
+            $tableName, 
169
+            implode(",\n", $columnStatements));
170
+
171
+        return $sql;
172
+    }
173 173
 
174 174
 }
Please login to merge, or discard this patch.
src/Traits/AutoApi.php 2 patches
Indentation   +366 added lines, -366 removed lines patch added patch discarded remove patch
@@ -9,386 +9,386 @@
 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
-	public function apiSearch(Array $queryParams, Array $fieldWhitelist, ?QueryExpression $whereClause = null, int $maxResultLimit = 100)
42
-	{
43
-		$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
+    public function apiSearch(Array $queryParams, Array $fieldWhitelist, ?QueryExpression $whereClause = null, int $maxResultLimit = 100)
42
+    {
43
+        $query = $this->search();
44 44
 
45
-		// Build query
46
-		$orderColumn = $queryParams['search_order_by'] ?? null;
47
-		if (!in_array($orderColumn, $fieldWhitelist)) {
48
-			$orderColumn = null;
49
-		}
45
+        // Build query
46
+        $orderColumn = $queryParams['search_order_by'] ?? null;
47
+        if (!in_array($orderColumn, $fieldWhitelist)) {
48
+            $orderColumn = null;
49
+        }
50 50
 
51
-		$orderDirection = $queryParams['search_order_direction'] ?? null;
52
-		if ($orderColumn !== null) {
53
-			$query->orderBy($orderColumn, $orderDirection);
54
-		}
51
+        $orderDirection = $queryParams['search_order_direction'] ?? null;
52
+        if ($orderColumn !== null) {
53
+            $query->orderBy($orderColumn, $orderDirection);
54
+        }
55 55
 		
56
-		if ($whereClause !== null) {
57
-			$query->where($whereClause);
58
-		}
59
-
60
-		$limit = min((int) ($queryParams['search_limit'] ?? $maxResultLimit), $maxResultLimit);
61
-		$query->limit($limit);
62
-
63
-		$offset = $queryParams['search_offset'] ?? 0;
64
-		$query->offset($offset);
65
-
66
-		$numPages = $query->getNumberOfPages();
67
-		$currentPage = $query->getCurrentPage();
68
-
69
-		// Fetch results
70
-		$results = $query->fetchAll();
71
-		$resultsArray = [];
72
-		foreach ($results as $result) {
73
-			$resultsArray[] = $result->toArray($fieldWhitelist);
74
-		}
75
-
76
-		return [
77
-			'search_offset' => $offset,
78
-			'search_limit' => $limit,
79
-			'search_order_by' => $orderColumn,
80
-			'search_order_direction' => $orderDirection,
81
-			'search_pages' => $numPages,
82
-			'search_current' => $currentPage,
83
-			'data' => $resultsArray
84
-		];
85
-	}
86
-
87
-	public function toArray($fieldWhitelist)
88
-	{
89
-		$output = [];
90
-		foreach ($this->tableDefinition as $colName => $definition) {
91
-			if (in_array($colName, $fieldWhitelist)) {
92
-				$output[$colName] = $definition['value'];
93
-			}
94
-		}
95
-
96
-		return $output;
97
-	}
98
-
99
-	public function apiRead($id, Array $fieldWhitelist)
100
-	{
101
-		// @TODO: Should apiRead throw exception or return null on fail?
102
-		$this->read($id);
103
-		return $this->toArray($fieldWhitelist);
104
-	}
105
-
106
-	/* =============================================================
56
+        if ($whereClause !== null) {
57
+            $query->where($whereClause);
58
+        }
59
+
60
+        $limit = min((int) ($queryParams['search_limit'] ?? $maxResultLimit), $maxResultLimit);
61
+        $query->limit($limit);
62
+
63
+        $offset = $queryParams['search_offset'] ?? 0;
64
+        $query->offset($offset);
65
+
66
+        $numPages = $query->getNumberOfPages();
67
+        $currentPage = $query->getCurrentPage();
68
+
69
+        // Fetch results
70
+        $results = $query->fetchAll();
71
+        $resultsArray = [];
72
+        foreach ($results as $result) {
73
+            $resultsArray[] = $result->toArray($fieldWhitelist);
74
+        }
75
+
76
+        return [
77
+            'search_offset' => $offset,
78
+            'search_limit' => $limit,
79
+            'search_order_by' => $orderColumn,
80
+            'search_order_direction' => $orderDirection,
81
+            'search_pages' => $numPages,
82
+            'search_current' => $currentPage,
83
+            'data' => $resultsArray
84
+        ];
85
+    }
86
+
87
+    public function toArray($fieldWhitelist)
88
+    {
89
+        $output = [];
90
+        foreach ($this->tableDefinition as $colName => $definition) {
91
+            if (in_array($colName, $fieldWhitelist)) {
92
+                $output[$colName] = $definition['value'];
93
+            }
94
+        }
95
+
96
+        return $output;
97
+    }
98
+
99
+    public function apiRead($id, Array $fieldWhitelist)
100
+    {
101
+        // @TODO: Should apiRead throw exception or return null on fail?
102
+        $this->read($id);
103
+        return $this->toArray($fieldWhitelist);
104
+    }
105
+
106
+    /* =============================================================
107 107
 	 * ===================== Constraint validation =================
108 108
 	 * ============================================================= */
109 109
 
110
-	/**
111
-	 * Copy all table variables between two instances
112
-	 */
113
-	public function syncInstanceFrom($from)
114
-	{
115
-		foreach ($this->tableDefinition as $colName => $definition) {
116
-			$this->tableDefinition[$colName]['value'] = $from->tableDefinition[$colName]['value'];
117
-		}
118
-	}
119
-
120
-	private function filterInputColumns($input, $whitelist)
121
-	{
122
-		$filteredInput = $input;
123
-		foreach ($input as $colName => $value) {
124
-			if (!in_array($colName, $whitelist)) {
125
-				unset($filteredInput[$colName]);
126
-			}
127
-		}
128
-		return $filteredInput;
129
-	}
130
-
131
-	private function validateExcessKeys($input)
132
-	{
133
-		$errors = [];
134
-		foreach ($input as $colName => $value) {
135
-			if (!array_key_exists($colName, $this->tableDefinition)) {
136
-				$errors[$colName] = "Unknown input field";
137
-				continue;
138
-			}
139
-		}
140
-		return $errors;
141
-	}
142
-
143
-	private function validateImmutableColumns($input)
144
-	{
145
-		$errors = [];
146
-		foreach ($this->tableDefinition as $colName => $definition) {
147
-			$property = $definition['properties'] ?? null;
148
-			if (array_key_exists($colName, $input)
149
-				&& $property & ColumnProperty::IMMUTABLE) {
150
-				$errors[$colName] = "Field cannot be changed";
151
-			}
152
-		}
153
-		return $errors;
154
-	}
155
-
156
-	/**
157
-	 * Checks whether input values are correct:
158
-	 * 1. Checks whether a value passes the validation function for that column
159
-	 * 2. Checks whether a value supplied to a relationship column is a valid value
160
-	 */
161
-	private function validateInputValues($input)
162
-	{
163
-		$errors = [];
164
-		foreach ($this->tableDefinition as $colName => $definition) {
165
-			// Validation check 1: If validate function is present
166
-			if (array_key_exists($colName, $input) 
167
-				&& is_callable($definition['validate'] ?? null)) {
168
-				$inputValue = $input[$colName];
169
-
170
-				// If validation function fails
171
-				[$status, $message] = $definition['validate']($inputValue);
172
-				if (!$status) {
173
-					$errors[$colName] = $message;
174
-				}	
175
-			}
176
-
177
-			// Validation check 2: If relation column, check whether entity exists
178
-			$properties = $definition['properties'] ?? null;
179
-			if (isset($definition['relation'])
180
-				&& ($properties & ColumnProperty::NOT_NULL)) {
181
-				$instance = clone $definition['relation'];
182
-				try {
183
-					$instance->read($input[$colName] ?? $definition['value'] ?? null);
184
-				} catch (ActiveRecordException $e) {
185
-					$errors[$colName] = "Entity for this value doesn't exist";
186
-				}
187
-			}
188
-		}
189
-		return $errors;
190
-	}
191
-
192
-	/**
193
-	 * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
194
-	 * Determines whether there are required columns for which no data is provided
195
-	 */
196
-	private function validateMissingKeys($input)
197
-	{
198
-		$errors = [];
199
-
200
-		foreach ($this->tableDefinition as $colName => $colDefinition) {
201
-			$default = $colDefinition['default'] ?? null;
202
-			$properties = $colDefinition['properties'] ?? null;
203
-			$value = $colDefinition['value'];
204
-
205
-			// If nullable and default not set => null
206
-			// If nullable and default null => default (null)
207
-			// If nullable and default set => default (value)
208
-
209
-			// if not nullable and default not set => error
210
-			// if not nullable and default null => error
211
-			// if not nullable and default st => default (value)
212
-			// => if not nullable and default null and value not set (or null) => error message in this method
213
-			if ($properties & ColumnProperty::NOT_NULL
214
-				&& $default === null
215
-				&& !($properties & ColumnProperty::AUTO_INCREMENT)
216
-				&& (!array_key_exists($colName, $input) 
217
-					|| $input[$colName] === null 
218
-					|| (is_string($input[$colName]) && $input[$colName] === '') )
219
-				&& ($value === null
220
-					|| (is_string($value) && $value === ''))) {
221
-				$errors[$colName] = sprintf("The required field \"%s\" is missing", $colName);
222
-			} 
223
-		}
224
-
225
-		return $errors;
226
-	}
227
-
228
-	/**
229
-	 * Copies the values for entries in the input with matching variable names in the record definition
230
-	 * @param Array $input The input data to be loaded into $this record
231
-	 */
232
-	private function loadData($input)
233
-	{
234
-		foreach ($this->tableDefinition as $colName => $definition) {
235
-			if (array_key_exists($colName, $input)) {
236
-				$definition['value'] = $input[$colName];
237
-			}
238
-		}
239
-	}
240
-
241
-	/**
242
-	 * @param Array $input Associative array of input values
243
-	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
244
-	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
245
-	 * 					of the modified data.
246
-	 */
247
-	public function apiCreate(Array $input, Array $createWhitelist, Array $readWhitelist)
248
-	{
249
-		// Clone $this to new instance (for restoring if validation goes wrong)
250
-		$transaction = $this->newInstance();
251
-		$errors = [];
252
-
253
-		// Filter out all non-whitelisted input values
254
-		$input = $this->filterInputColumns($input, $createWhitelist);
255
-
256
-		// Validate excess keys
257
-		$errors += $transaction->validateExcessKeys($input);
258
-
259
-		// Validate input values (using validation function)
260
-		$errors += $transaction->validateInputValues($input);
261
-
262
-		// "Copy" data into transaction
263
-		$transaction->loadData($input);
264
-
265
-		// Run create hooks
266
-		foreach ($transaction->createHooks as $colName => $fn) {
267
-			$fn();
268
-		}
269
-
270
-		// Validate missing keys
271
-		$errors += $transaction->validateMissingKeys($input);
272
-
273
-		// If no errors, commit the pending data
274
-		if (empty($errors)) {
275
-			$this->syncInstanceFrom($transaction);
276
-
277
-			// Insert default values for not-null fields
278
-			$this->insertDefaults();
279
-
280
-			try {
281
-				(new Query($this->getPdo(), $this->getTableName()))
282
-					->insert($this->getActiveRecordColumns())
283
-					->execute();
284
-
285
-				$this->setId(intval($this->getPdo()->lastInsertId()));
286
-			} catch (\PDOException $e) {
287
-				// @TODO: Potentially filter and store mysql messages (where possible) in error messages
288
-				throw new ActiveRecordException($e->getMessage(), 0, $e);
289
-			}
290
-
291
-			return [null, $this->toArray($readWhitelist)];
292
-		} else {
293
-			return [$errors, null];
294
-		}
295
-	}
296
-
297
-	/**
298
-	 * @param Array $input Associative array of input values
299
-	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
300
-	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
301
-	 * 					of the modified data.
302
-	 */
303
-	public function apiUpdate(Array $input, Array $updateWhitelist, Array $readWhitelist)
304
-	{
305
-		$transaction = $this->newInstance();
306
-		$transaction->syncInstanceFrom($this);
307
-		$errors = [];
308
-
309
-		// Filter out all non-whitelisted input values
310
-		$input = $this->filterInputColumns($input, $updateWhitelist);
311
-
312
-		// Check for excess keys
313
-		$errors += $transaction->validateExcessKeys($input);
314
-
315
-		// Check for immutable keys
316
-		$errors += $transaction->validateImmutableColumns($input);
317
-
318
-		// Validate input values (using validation function)
319
-		$errors += $transaction->validateInputValues($input);
320
-
321
-		// "Copy" data into transaction
322
-		$transaction->loadData($input);
323
-
324
-		// Run create hooks
325
-		foreach ($transaction->updateHooks as $colName => $fn) {
326
-			$fn();
327
-		}
328
-
329
-		// Validate missing keys
330
-		$errors += $transaction->validateMissingKeys($input);
331
-
332
-		// Update database
333
-		if (empty($errors)) {
334
-			$this->syncInstanceFrom($transaction);
335
-
336
-			try {
337
-				(new Query($this->getPdo(), $this->getTableName()))
338
-					->update($this->getActiveRecordColumns())
339
-					->where(Query::Equal('id', $this->getId()))
340
-					->execute();
341
-			} catch (\PDOException $e) {
342
-				throw new ActiveRecordException($e->getMessage(), 0, $e);
343
-			}
344
-
345
-			return [null, $this->toArray($readWhitelist)];
346
-		} else {
347
-			return [$errors, null];
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * Returns this active record after reading the attributes from the entry with the given identifier.
353
-	 *
354
-	 * @param mixed $id
355
-	 * @return $this
356
-	 * @throws ActiveRecordException on failure.
357
-	 */
358
-	abstract public function read($id);
359
-
360
-	/**
361
-	 * Returns the PDO.
362
-	 *
363
-	 * @return \PDO the PDO.
364
-	 */
365
-	abstract public function getPdo();
366
-
367
-	/**
368
-	 * Set the ID.
369
-	 *
370
-	 * @param int $id
371
-	 * @return $this
372
-	 */
373
-	abstract protected function setId($id);
374
-
375
-	/**
376
-	 * Returns the ID.
377
-	 *
378
-	 * @return null|int The ID.
379
-	 */
380
-	abstract protected function getId();
381
-
382
-	/**
383
-	 * Returns the active record table.
384
-	 *
385
-	 * @return string the active record table name.
386
-	 */
387
-	abstract public function getTableName();
388
-
389
-	/**
390
-	 * Returns the name -> variable mapping for the table definition.
391
-	 * @return Array The mapping
392
-	 */
393
-	abstract protected function getActiveRecordColumns();
110
+    /**
111
+     * Copy all table variables between two instances
112
+     */
113
+    public function syncInstanceFrom($from)
114
+    {
115
+        foreach ($this->tableDefinition as $colName => $definition) {
116
+            $this->tableDefinition[$colName]['value'] = $from->tableDefinition[$colName]['value'];
117
+        }
118
+    }
119
+
120
+    private function filterInputColumns($input, $whitelist)
121
+    {
122
+        $filteredInput = $input;
123
+        foreach ($input as $colName => $value) {
124
+            if (!in_array($colName, $whitelist)) {
125
+                unset($filteredInput[$colName]);
126
+            }
127
+        }
128
+        return $filteredInput;
129
+    }
130
+
131
+    private function validateExcessKeys($input)
132
+    {
133
+        $errors = [];
134
+        foreach ($input as $colName => $value) {
135
+            if (!array_key_exists($colName, $this->tableDefinition)) {
136
+                $errors[$colName] = "Unknown input field";
137
+                continue;
138
+            }
139
+        }
140
+        return $errors;
141
+    }
142
+
143
+    private function validateImmutableColumns($input)
144
+    {
145
+        $errors = [];
146
+        foreach ($this->tableDefinition as $colName => $definition) {
147
+            $property = $definition['properties'] ?? null;
148
+            if (array_key_exists($colName, $input)
149
+                && $property & ColumnProperty::IMMUTABLE) {
150
+                $errors[$colName] = "Field cannot be changed";
151
+            }
152
+        }
153
+        return $errors;
154
+    }
155
+
156
+    /**
157
+     * Checks whether input values are correct:
158
+     * 1. Checks whether a value passes the validation function for that column
159
+     * 2. Checks whether a value supplied to a relationship column is a valid value
160
+     */
161
+    private function validateInputValues($input)
162
+    {
163
+        $errors = [];
164
+        foreach ($this->tableDefinition as $colName => $definition) {
165
+            // Validation check 1: If validate function is present
166
+            if (array_key_exists($colName, $input) 
167
+                && is_callable($definition['validate'] ?? null)) {
168
+                $inputValue = $input[$colName];
169
+
170
+                // If validation function fails
171
+                [$status, $message] = $definition['validate']($inputValue);
172
+                if (!$status) {
173
+                    $errors[$colName] = $message;
174
+                }	
175
+            }
176
+
177
+            // Validation check 2: If relation column, check whether entity exists
178
+            $properties = $definition['properties'] ?? null;
179
+            if (isset($definition['relation'])
180
+                && ($properties & ColumnProperty::NOT_NULL)) {
181
+                $instance = clone $definition['relation'];
182
+                try {
183
+                    $instance->read($input[$colName] ?? $definition['value'] ?? null);
184
+                } catch (ActiveRecordException $e) {
185
+                    $errors[$colName] = "Entity for this value doesn't exist";
186
+                }
187
+            }
188
+        }
189
+        return $errors;
190
+    }
191
+
192
+    /**
193
+     * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
194
+     * Determines whether there are required columns for which no data is provided
195
+     */
196
+    private function validateMissingKeys($input)
197
+    {
198
+        $errors = [];
199
+
200
+        foreach ($this->tableDefinition as $colName => $colDefinition) {
201
+            $default = $colDefinition['default'] ?? null;
202
+            $properties = $colDefinition['properties'] ?? null;
203
+            $value = $colDefinition['value'];
204
+
205
+            // If nullable and default not set => null
206
+            // If nullable and default null => default (null)
207
+            // If nullable and default set => default (value)
208
+
209
+            // if not nullable and default not set => error
210
+            // if not nullable and default null => error
211
+            // if not nullable and default st => default (value)
212
+            // => if not nullable and default null and value not set (or null) => error message in this method
213
+            if ($properties & ColumnProperty::NOT_NULL
214
+                && $default === null
215
+                && !($properties & ColumnProperty::AUTO_INCREMENT)
216
+                && (!array_key_exists($colName, $input) 
217
+                    || $input[$colName] === null 
218
+                    || (is_string($input[$colName]) && $input[$colName] === '') )
219
+                && ($value === null
220
+                    || (is_string($value) && $value === ''))) {
221
+                $errors[$colName] = sprintf("The required field \"%s\" is missing", $colName);
222
+            } 
223
+        }
224
+
225
+        return $errors;
226
+    }
227
+
228
+    /**
229
+     * Copies the values for entries in the input with matching variable names in the record definition
230
+     * @param Array $input The input data to be loaded into $this record
231
+     */
232
+    private function loadData($input)
233
+    {
234
+        foreach ($this->tableDefinition as $colName => $definition) {
235
+            if (array_key_exists($colName, $input)) {
236
+                $definition['value'] = $input[$colName];
237
+            }
238
+        }
239
+    }
240
+
241
+    /**
242
+     * @param Array $input Associative array of input values
243
+     * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
244
+     * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
245
+     * 					of the modified data.
246
+     */
247
+    public function apiCreate(Array $input, Array $createWhitelist, Array $readWhitelist)
248
+    {
249
+        // Clone $this to new instance (for restoring if validation goes wrong)
250
+        $transaction = $this->newInstance();
251
+        $errors = [];
252
+
253
+        // Filter out all non-whitelisted input values
254
+        $input = $this->filterInputColumns($input, $createWhitelist);
255
+
256
+        // Validate excess keys
257
+        $errors += $transaction->validateExcessKeys($input);
258
+
259
+        // Validate input values (using validation function)
260
+        $errors += $transaction->validateInputValues($input);
261
+
262
+        // "Copy" data into transaction
263
+        $transaction->loadData($input);
264
+
265
+        // Run create hooks
266
+        foreach ($transaction->createHooks as $colName => $fn) {
267
+            $fn();
268
+        }
269
+
270
+        // Validate missing keys
271
+        $errors += $transaction->validateMissingKeys($input);
272
+
273
+        // If no errors, commit the pending data
274
+        if (empty($errors)) {
275
+            $this->syncInstanceFrom($transaction);
276
+
277
+            // Insert default values for not-null fields
278
+            $this->insertDefaults();
279
+
280
+            try {
281
+                (new Query($this->getPdo(), $this->getTableName()))
282
+                    ->insert($this->getActiveRecordColumns())
283
+                    ->execute();
284
+
285
+                $this->setId(intval($this->getPdo()->lastInsertId()));
286
+            } catch (\PDOException $e) {
287
+                // @TODO: Potentially filter and store mysql messages (where possible) in error messages
288
+                throw new ActiveRecordException($e->getMessage(), 0, $e);
289
+            }
290
+
291
+            return [null, $this->toArray($readWhitelist)];
292
+        } else {
293
+            return [$errors, null];
294
+        }
295
+    }
296
+
297
+    /**
298
+     * @param Array $input Associative array of input values
299
+     * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
300
+     * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
301
+     * 					of the modified data.
302
+     */
303
+    public function apiUpdate(Array $input, Array $updateWhitelist, Array $readWhitelist)
304
+    {
305
+        $transaction = $this->newInstance();
306
+        $transaction->syncInstanceFrom($this);
307
+        $errors = [];
308
+
309
+        // Filter out all non-whitelisted input values
310
+        $input = $this->filterInputColumns($input, $updateWhitelist);
311
+
312
+        // Check for excess keys
313
+        $errors += $transaction->validateExcessKeys($input);
314
+
315
+        // Check for immutable keys
316
+        $errors += $transaction->validateImmutableColumns($input);
317
+
318
+        // Validate input values (using validation function)
319
+        $errors += $transaction->validateInputValues($input);
320
+
321
+        // "Copy" data into transaction
322
+        $transaction->loadData($input);
323
+
324
+        // Run create hooks
325
+        foreach ($transaction->updateHooks as $colName => $fn) {
326
+            $fn();
327
+        }
328
+
329
+        // Validate missing keys
330
+        $errors += $transaction->validateMissingKeys($input);
331
+
332
+        // Update database
333
+        if (empty($errors)) {
334
+            $this->syncInstanceFrom($transaction);
335
+
336
+            try {
337
+                (new Query($this->getPdo(), $this->getTableName()))
338
+                    ->update($this->getActiveRecordColumns())
339
+                    ->where(Query::Equal('id', $this->getId()))
340
+                    ->execute();
341
+            } catch (\PDOException $e) {
342
+                throw new ActiveRecordException($e->getMessage(), 0, $e);
343
+            }
344
+
345
+            return [null, $this->toArray($readWhitelist)];
346
+        } else {
347
+            return [$errors, null];
348
+        }
349
+    }
350
+
351
+    /**
352
+     * Returns this active record after reading the attributes from the entry with the given identifier.
353
+     *
354
+     * @param mixed $id
355
+     * @return $this
356
+     * @throws ActiveRecordException on failure.
357
+     */
358
+    abstract public function read($id);
359
+
360
+    /**
361
+     * Returns the PDO.
362
+     *
363
+     * @return \PDO the PDO.
364
+     */
365
+    abstract public function getPdo();
366
+
367
+    /**
368
+     * Set the ID.
369
+     *
370
+     * @param int $id
371
+     * @return $this
372
+     */
373
+    abstract protected function setId($id);
374
+
375
+    /**
376
+     * Returns the ID.
377
+     *
378
+     * @return null|int The ID.
379
+     */
380
+    abstract protected function getId();
381
+
382
+    /**
383
+     * Returns the active record table.
384
+     *
385
+     * @return string the active record table name.
386
+     */
387
+    abstract public function getTableName();
388
+
389
+    /**
390
+     * Returns the name -> variable mapping for the table definition.
391
+     * @return Array The mapping
392
+     */
393
+    abstract protected function getActiveRecordColumns();
394 394
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -215,7 +215,7 @@
 block discarded – undo
215 215
 				&& !($properties & ColumnProperty::AUTO_INCREMENT)
216 216
 				&& (!array_key_exists($colName, $input) 
217 217
 					|| $input[$colName] === null 
218
-					|| (is_string($input[$colName]) && $input[$colName] === '') )
218
+					|| (is_string($input[$colName]) && $input[$colName] === ''))
219 219
 				&& ($value === null
220 220
 					|| (is_string($value) && $value === ''))) {
221 221
 				$errors[$colName] = sprintf("The required field \"%s\" is missing", $colName);
Please login to merge, or discard this patch.
src/Traits/Password.php 1 patch
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -13,165 +13,165 @@
 block discarded – undo
13 13
 
14 14
 trait Password
15 15
 {
16
-	/** @var string The password hash. */
17
-	protected $password;
18
-
19
-	/** @var string|null The password reset token. */
20
-	protected $passwordResetToken;
21
-
22
-	/**
23
-	 * this method is required to be called in the constructor for each class that uses this trait. 
24
-	 * It adds the fields necessary for the passwords struct to the table definition
25
-	 */
26
-	protected function initPassword()
27
-	{
28
-		$this->extendTableDefinition(TRAIT_PASSWORD_FIELD_PASSWORD, [
29
-			'value' => &$this->password,
30
-			'validate' => [$this, 'validatePassword'],
31
-			'type' => 'VARCHAR',
32
-			'length' => 1024,
33
-			'properties' => null
34
-		]);
35
-
36
-		$this->extendTableDefinition(TRAIT_PASSWORD_FIELD_PASSWORD_RESET_TOKEN, [
37
-			'value' => &$this->passwordResetToken,
38
-			'validate' => null,
39
-			'default' => 0,
40
-			'type' => 'VARCHAR',
41
-			'length' => 1024
42
-		]);
43
-	}
44
-
45
-
46
-	/**
47
-	 * Returns whether the users password has been set
48
-	 * @return boolean true if the user has a password
49
-	 */
50
-	public function hasPasswordBeenSet()
51
-	{
52
-		return $this->password !== null;
53
-	}
54
-
55
-	/**
56
-	 * Returns true if the credentials are correct.
57
-	 *
58
-	 * @param string $password
59
-	 * @return boolean true if the credentials are correct
60
-	 */
61
-	public function isPassword($password)
62
-	{ 
63
-		if (!$this->hasPasswordBeenSet())
64
-		{
65
-			throw new ActiveRecordTraitException("Password field has not been set");
66
-		}
67
-
68
-		if (!password_verify($password, $this->password)) {
69
-			return false;
70
-		}
71
-
72
-		if (password_needs_rehash($this->password, TRAIT_PASSWORD_ENCRYPTION, ['cost' => TRAIT_PASSWORD_STRENTH])) {
73
-			$this->setPassword($password)->sync();
74
-		}
75
-
76
-		return true;
77
-	}
78
-
79
-	public function validatePassword($password) {
80
-		if (strlen($password) < TRAIT_PASSWORD_MIN_LENGTH) {
81
-			$message = sprintf('\'Password\' must be atleast %s characters long. %s characters provied.', TRAIT_PASSWORD_MIN_LENGTH, strlen($password));
82
-			return [false, $message];
83
-		}
84
-		return [true, ''];
85
-	}
86
-
87
-	/**
88
-	 * Set the password.
89
-	 *
90
-	 * @param string $password
91
-	 * @return $this
92
-	 * @throws \Exception
93
-	 */
94
-	public function setPassword($password)
95
-	{
96
-		[$status, $error] = $this->validatePassword($password);
97
-		if (!$status) {
98
-			throw new ActiveRecordTraitException($error);
99
-		}
100
-
101
-		$passwordHash = \password_hash($password, TRAIT_PASSWORD_ENCRYPTION, ['cost' => TRAIT_PASSWORD_STRENTH]);
102
-
103
-		if ($passwordHash === false) {
104
-			throw new ActiveRecordTraitException('\'Password\' hash failed.');
105
-		}
106
-
107
-		$this->password = $passwordHash;
108
-
109
-		return $this;
110
-	}
111
-
112
-	/**
113
-	 * @return string The Hash of the password
114
-	 */
115
-	public function getPasswordHash()
116
-	{
117
-		return $this->password;
118
-	}
119
-
120
-	/**
121
-	 * Returns the currently set password token for the entity, or null if not set
122
-	 * @return string|null The password reset token
123
-	 */
124
-	public function getPasswordResetToken()
125
-	{
126
-		return $this->passwordResetToken;
127
-	}
128
-
129
-	/**
130
-	 * Generates a new password reset token for the user
131
-	 */
132
-	public function generatePasswordResetToken()
133
-	{
134
-		$this->passwordResetToken = md5(uniqid(mt_rand(), true));
135
-		return $this;
136
-	}
137
-
138
-	/**
139
-	 * Clears the current password reset token
140
-	 */
141
-	public function clearPasswordResetToken()
142
-	{
143
-		$this->passwordResetToken = null;
144
-		return $this;
145
-	}
16
+    /** @var string The password hash. */
17
+    protected $password;
18
+
19
+    /** @var string|null The password reset token. */
20
+    protected $passwordResetToken;
21
+
22
+    /**
23
+     * this method is required to be called in the constructor for each class that uses this trait. 
24
+     * It adds the fields necessary for the passwords struct to the table definition
25
+     */
26
+    protected function initPassword()
27
+    {
28
+        $this->extendTableDefinition(TRAIT_PASSWORD_FIELD_PASSWORD, [
29
+            'value' => &$this->password,
30
+            'validate' => [$this, 'validatePassword'],
31
+            'type' => 'VARCHAR',
32
+            'length' => 1024,
33
+            'properties' => null
34
+        ]);
35
+
36
+        $this->extendTableDefinition(TRAIT_PASSWORD_FIELD_PASSWORD_RESET_TOKEN, [
37
+            'value' => &$this->passwordResetToken,
38
+            'validate' => null,
39
+            'default' => 0,
40
+            'type' => 'VARCHAR',
41
+            'length' => 1024
42
+        ]);
43
+    }
44
+
45
+
46
+    /**
47
+     * Returns whether the users password has been set
48
+     * @return boolean true if the user has a password
49
+     */
50
+    public function hasPasswordBeenSet()
51
+    {
52
+        return $this->password !== null;
53
+    }
54
+
55
+    /**
56
+     * Returns true if the credentials are correct.
57
+     *
58
+     * @param string $password
59
+     * @return boolean true if the credentials are correct
60
+     */
61
+    public function isPassword($password)
62
+    { 
63
+        if (!$this->hasPasswordBeenSet())
64
+        {
65
+            throw new ActiveRecordTraitException("Password field has not been set");
66
+        }
67
+
68
+        if (!password_verify($password, $this->password)) {
69
+            return false;
70
+        }
71
+
72
+        if (password_needs_rehash($this->password, TRAIT_PASSWORD_ENCRYPTION, ['cost' => TRAIT_PASSWORD_STRENTH])) {
73
+            $this->setPassword($password)->sync();
74
+        }
75
+
76
+        return true;
77
+    }
78
+
79
+    public function validatePassword($password) {
80
+        if (strlen($password) < TRAIT_PASSWORD_MIN_LENGTH) {
81
+            $message = sprintf('\'Password\' must be atleast %s characters long. %s characters provied.', TRAIT_PASSWORD_MIN_LENGTH, strlen($password));
82
+            return [false, $message];
83
+        }
84
+        return [true, ''];
85
+    }
86
+
87
+    /**
88
+     * Set the password.
89
+     *
90
+     * @param string $password
91
+     * @return $this
92
+     * @throws \Exception
93
+     */
94
+    public function setPassword($password)
95
+    {
96
+        [$status, $error] = $this->validatePassword($password);
97
+        if (!$status) {
98
+            throw new ActiveRecordTraitException($error);
99
+        }
100
+
101
+        $passwordHash = \password_hash($password, TRAIT_PASSWORD_ENCRYPTION, ['cost' => TRAIT_PASSWORD_STRENTH]);
102
+
103
+        if ($passwordHash === false) {
104
+            throw new ActiveRecordTraitException('\'Password\' hash failed.');
105
+        }
106
+
107
+        $this->password = $passwordHash;
108
+
109
+        return $this;
110
+    }
111
+
112
+    /**
113
+     * @return string The Hash of the password
114
+     */
115
+    public function getPasswordHash()
116
+    {
117
+        return $this->password;
118
+    }
119
+
120
+    /**
121
+     * Returns the currently set password token for the entity, or null if not set
122
+     * @return string|null The password reset token
123
+     */
124
+    public function getPasswordResetToken()
125
+    {
126
+        return $this->passwordResetToken;
127
+    }
128
+
129
+    /**
130
+     * Generates a new password reset token for the user
131
+     */
132
+    public function generatePasswordResetToken()
133
+    {
134
+        $this->passwordResetToken = md5(uniqid(mt_rand(), true));
135
+        return $this;
136
+    }
137
+
138
+    /**
139
+     * Clears the current password reset token
140
+     */
141
+    public function clearPasswordResetToken()
142
+    {
143
+        $this->passwordResetToken = null;
144
+        return $this;
145
+    }
146 146
 	
147
-	/**
148
-	 * @return void
149
-	 */
150
-	abstract protected function extendTableDefinition($columnName, $definition);
147
+    /**
148
+     * @return void
149
+     */
150
+    abstract protected function extendTableDefinition($columnName, $definition);
151 151
 	
152
-	/**
153
-	 * @return void
154
-	 */
155
-	abstract protected function registerSearchHook($columnName, $fn);
156
-
157
-	/**
158
-	 * @return void
159
-	 */
160
-	abstract protected function registerDeleteHook($columnName, $fn);
161
-
162
-	/**
163
-	 * @return void
164
-	 */
165
-	abstract protected function registerUpdateHook($columnName, $fn);
166
-
167
-	/**
168
-	 * @return void
169
-	 */
170
-	abstract protected function registerReadHook($columnName, $fn);
171
-
172
-	/**
173
-	 * @return void
174
-	 */
175
-	abstract protected function registerCreateHook($columnName, $fn);
152
+    /**
153
+     * @return void
154
+     */
155
+    abstract protected function registerSearchHook($columnName, $fn);
156
+
157
+    /**
158
+     * @return void
159
+     */
160
+    abstract protected function registerDeleteHook($columnName, $fn);
161
+
162
+    /**
163
+     * @return void
164
+     */
165
+    abstract protected function registerUpdateHook($columnName, $fn);
166
+
167
+    /**
168
+     * @return void
169
+     */
170
+    abstract protected function registerReadHook($columnName, $fn);
171
+
172
+    /**
173
+     * @return void
174
+     */
175
+    abstract protected function registerCreateHook($columnName, $fn);
176 176
 
177 177
 }
178 178
\ No newline at end of file
Please login to merge, or discard this patch.
src/Traits/Address.php 1 patch
Indentation   +170 added lines, -170 removed lines patch added patch discarded remove patch
@@ -12,181 +12,181 @@
 block discarded – undo
12 12
 
13 13
 trait Address
14 14
 {
15
-	/** @var string the address line */
16
-	protected $address;
17
-
18
-	/** @var string the zipcode */
19
-	protected $zipcode;
20
-
21
-	/** @var string the city */
22
-	protected $city;
23
-
24
-	/** @var string the country */
25
-	protected $country;
26
-
27
-	/** @var string the state */
28
-	protected $state;
29
-
30
-	/**
31
-	 * Registers the Address trait on the including class
32
-	 * @return void
33
-	 */
34
-	protected function initAddress() 
35
-	{
36
-		$this->extendTableDefinition(TRAIT_ADDRESS_FIELD_ADDRESS, [
37
-			'value' => &$this->address,
38
-			'validate' => null,
39
-			'type' => 'VARCHAR',
40
-			'length' => 1024,
41
-			'properties' => null
42
-		]);
43
-
44
-		$this->extendTableDefinition(TRAIT_ADDRESS_FIELD_ZIPCODE, [
45
-			'value' => &$this->zipcode,
46
-			'validate' => null,
47
-			'type' => 'VARCHAR',
48
-			'length' => 1024,
49
-			'properties' => null
50
-		]);
51
-
52
-		$this->extendTableDefinition(TRAIT_ADDRESS_FIELD_CITY, [
53
-			'value' => &$this->city,
54
-			'validate' => null,
55
-			'type' => 'VARCHAR',
56
-			'length' => 1024,
57
-			'properties' => null
58
-		]);
59
-
60
-		$this->extendTableDefinition(TRAIT_ADDRESS_FIELD_COUNTRY, [
61
-			'value' => &$this->country,
62
-			'validate' => null,
63
-			'type' => 'VARCHAR',
64
-			'length' => 1024,
65
-			'properties' => null
66
-		]);
67
-
68
-		$this->extendTableDefinition(TRAIT_ADDRESS_FIELD_STATE, [
69
-			'value' => &$this->state,
70
-			'validate' => null,
71
-			'type' => 'VARCHAR',
72
-			'length' => 1024,
73
-			'properties' => null
74
-		]);
75
-
76
-		$this->address = null;
77
-		$this->zipcode = null;
78
-		$this->city = null;
79
-		$this->country = null;
80
-		$this->state = null;
81
-	}
82
-
83
-	/**
84
-	 * @return string
85
-	 */
86
-	public function getAddress()
87
-	{
88
-		return $this->address;
89
-	}
15
+    /** @var string the address line */
16
+    protected $address;
17
+
18
+    /** @var string the zipcode */
19
+    protected $zipcode;
20
+
21
+    /** @var string the city */
22
+    protected $city;
23
+
24
+    /** @var string the country */
25
+    protected $country;
26
+
27
+    /** @var string the state */
28
+    protected $state;
29
+
30
+    /**
31
+     * Registers the Address trait on the including class
32
+     * @return void
33
+     */
34
+    protected function initAddress() 
35
+    {
36
+        $this->extendTableDefinition(TRAIT_ADDRESS_FIELD_ADDRESS, [
37
+            'value' => &$this->address,
38
+            'validate' => null,
39
+            'type' => 'VARCHAR',
40
+            'length' => 1024,
41
+            'properties' => null
42
+        ]);
43
+
44
+        $this->extendTableDefinition(TRAIT_ADDRESS_FIELD_ZIPCODE, [
45
+            'value' => &$this->zipcode,
46
+            'validate' => null,
47
+            'type' => 'VARCHAR',
48
+            'length' => 1024,
49
+            'properties' => null
50
+        ]);
51
+
52
+        $this->extendTableDefinition(TRAIT_ADDRESS_FIELD_CITY, [
53
+            'value' => &$this->city,
54
+            'validate' => null,
55
+            'type' => 'VARCHAR',
56
+            'length' => 1024,
57
+            'properties' => null
58
+        ]);
59
+
60
+        $this->extendTableDefinition(TRAIT_ADDRESS_FIELD_COUNTRY, [
61
+            'value' => &$this->country,
62
+            'validate' => null,
63
+            'type' => 'VARCHAR',
64
+            'length' => 1024,
65
+            'properties' => null
66
+        ]);
67
+
68
+        $this->extendTableDefinition(TRAIT_ADDRESS_FIELD_STATE, [
69
+            'value' => &$this->state,
70
+            'validate' => null,
71
+            'type' => 'VARCHAR',
72
+            'length' => 1024,
73
+            'properties' => null
74
+        ]);
75
+
76
+        $this->address = null;
77
+        $this->zipcode = null;
78
+        $this->city = null;
79
+        $this->country = null;
80
+        $this->state = null;
81
+    }
82
+
83
+    /**
84
+     * @return string
85
+     */
86
+    public function getAddress()
87
+    {
88
+        return $this->address;
89
+    }
90 90
 	
91
-	/**
92
-	 * @param string $address
93
-	 */
94
-	public function setAddress($address)
95
-	{
96
-		$this->address = $address;
97
-		return $this;
98
-	}
99
-
100
-	/**
101
-	 * @return string
102
-	 */
103
-	public function getZipcode()
104
-	{
105
-		return $this->zipcode;
106
-	}
91
+    /**
92
+     * @param string $address
93
+     */
94
+    public function setAddress($address)
95
+    {
96
+        $this->address = $address;
97
+        return $this;
98
+    }
99
+
100
+    /**
101
+     * @return string
102
+     */
103
+    public function getZipcode()
104
+    {
105
+        return $this->zipcode;
106
+    }
107 107
 	
108
-	/**
109
-	 * @param string $zipcode
110
-	 */
111
-	public function setZipcode($zipcode)
112
-	{
113
-		$this->zipcode = $zipcode;
114
-		return $this;
115
-	}
116
-
117
-	/**
118
-	 * @return string
119
-	 */
120
-	public function getCity()
121
-	{
122
-		return $this->city;
123
-	}
108
+    /**
109
+     * @param string $zipcode
110
+     */
111
+    public function setZipcode($zipcode)
112
+    {
113
+        $this->zipcode = $zipcode;
114
+        return $this;
115
+    }
116
+
117
+    /**
118
+     * @return string
119
+     */
120
+    public function getCity()
121
+    {
122
+        return $this->city;
123
+    }
124 124
 	
125
-	/**
126
-	 * @param string $city
127
-	 */
128
-	public function setCity($city)
129
-	{
130
-		$this->city = $city;
131
-		return $this;
132
-	}
133
-
134
-	/**
135
-	 * @return string
136
-	 */
137
-	public function getCountry()
138
-	{
139
-		return $this->country;
140
-	}
125
+    /**
126
+     * @param string $city
127
+     */
128
+    public function setCity($city)
129
+    {
130
+        $this->city = $city;
131
+        return $this;
132
+    }
133
+
134
+    /**
135
+     * @return string
136
+     */
137
+    public function getCountry()
138
+    {
139
+        return $this->country;
140
+    }
141 141
 	
142
-	/**
143
-	 * @param string $country
144
-	 */
145
-	public function setCountry($country)
146
-	{
147
-		$this->country = $country;
148
-		return $this;
149
-	}
150
-
151
-	public function getState()
152
-	{
153
-		return $this->state;
154
-	}
142
+    /**
143
+     * @param string $country
144
+     */
145
+    public function setCountry($country)
146
+    {
147
+        $this->country = $country;
148
+        return $this;
149
+    }
150
+
151
+    public function getState()
152
+    {
153
+        return $this->state;
154
+    }
155 155
 	
156
-	public function setState($state)
157
-	{
158
-		$this->state = $state;
159
-		return $this;
160
-	}
161
-
162
-	/**
163
-	 * @return void
164
-	 */
165
-	abstract protected function extendTableDefinition($columnName, $definition);
156
+    public function setState($state)
157
+    {
158
+        $this->state = $state;
159
+        return $this;
160
+    }
161
+
162
+    /**
163
+     * @return void
164
+     */
165
+    abstract protected function extendTableDefinition($columnName, $definition);
166 166
 	
167
-	/**
168
-	 * @return void
169
-	 */
170
-	abstract protected function registerSearchHook($columnName, $fn);
171
-
172
-	/**
173
-	 * @return void
174
-	 */
175
-	abstract protected function registerDeleteHook($columnName, $fn);
176
-
177
-	/**
178
-	 * @return void
179
-	 */
180
-	abstract protected function registerUpdateHook($columnName, $fn);
181
-
182
-	/**
183
-	 * @return void
184
-	 */
185
-	abstract protected function registerReadHook($columnName, $fn);
186
-
187
-	/**
188
-	 * @return void
189
-	 */
190
-	abstract protected function registerCreateHook($columnName, $fn);
167
+    /**
168
+     * @return void
169
+     */
170
+    abstract protected function registerSearchHook($columnName, $fn);
171
+
172
+    /**
173
+     * @return void
174
+     */
175
+    abstract protected function registerDeleteHook($columnName, $fn);
176
+
177
+    /**
178
+     * @return void
179
+     */
180
+    abstract protected function registerUpdateHook($columnName, $fn);
181
+
182
+    /**
183
+     * @return void
184
+     */
185
+    abstract protected function registerReadHook($columnName, $fn);
186
+
187
+    /**
188
+     * @return void
189
+     */
190
+    abstract protected function registerCreateHook($columnName, $fn);
191 191
 	
192 192
 }
193 193
\ No newline at end of file
Please login to merge, or discard this patch.
src/Traits/ManyToManyRelation.php 1 patch
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -9,110 +9,110 @@
 block discarded – undo
9 9
 
10 10
 Trait ManyToManyRelation
11 11
 {
12
-	// These variables are relevant for internal bookkeeping (constraint generation etc)
13
-
14
-	/** @var string The name of the left column of the relation. */
15
-	private $_leftColumnName;
16
-
17
-	/** @var string The name of the right column of the relation. */
18
-	private $_rightColumnName;
19
-
20
-	/** @var string The name of the left table of the relation. */
21
-	private $_leftEntityTable;
22
-
23
-	/** @var string The name of the right table of the relation. */
24
-	private $_rightEntityTable;
25
-
26
-	/** @var \PDO The PDO object. */
27
-	protected $pdo;
28
-	/**
29
-	 * Initializes the the ManyToManyRelation trait on the included object
30
-	 * 
31
-	 * @param AbstractActiveRecord $leftEntity The left entity of the relation
32
-	 * @param int $leftVariable The reference to the variable where the id for the left entity will be stored
33
-	 * @param AbstractActiveRecord $rightEntity The left entity of the relation
34
-	 * @param int $leftVariable The reference to the variable where the id for the right entity will be stored
35
-	 * @return void
36
-	 */
37
-	protected function initManyToManyRelation(AbstractActiveRecord $leftEntity, &$leftVariable, AbstractActiveRecord $rightEntity, &$rightVariable)
38
-	{
39
-		$this->_leftEntityTable = $leftEntity->getTableName();
40
-		$this->_rightEntityTable = $rightEntity->getTableName();
41
-
42
-		if (get_class($leftEntity) === get_class($rightEntity)) {
43
-			$this->_leftColumnName = sprintf("id_%s_left", $leftEntity->getTableName());
44
-			$this->_rightColumnName = sprintf("id_%s_right", $rightEntity->getTableName());
45
-		} else {
46
-			$this->_leftColumnName = sprintf("id_%s", $leftEntity->getTableName());
47
-			$this->_rightColumnName = sprintf("id_%s", $rightEntity->getTableName());
48
-		}
49
-
50
-		$this->extendTableDefinition($this->_leftColumnName, [
51
-			'value' => &$leftVariable,
52
-			'validate' => null,
53
-			'type' => AbstractActiveRecord::COLUMN_TYPE_ID,
54
-			'properties' => ColumnProperty::NOT_NULL
55
-		]);
56
-
57
-		$this->extendTableDefinition($this->_rightColumnName, [
58
-			'value' => &$rightVariable,
59
-			'validate' => null,
60
-			'type' => AbstractActiveRecord::COLUMN_TYPE_ID,
61
-			'properties' => ColumnProperty::NOT_NULL
62
-		]);
63
-	}
64
-
65
-	/**
66
-	 * Build the constraints for the many-to-many relation table
67
-	 * @return void
68
-	 */
69
-	public function createTableConstraints()
70
-	{
71
-		$childTable = $this->getTableName();
72
-
73
-		$leftParentTable = $this->_leftEntityTable;
74
-		$rightParentTable = $this->_rightEntityTable;
75
-
76
-		$leftConstraint = SchemaBuilder::buildConstraint($leftParentTable, 'id', $childTable, $this->_leftColumnName);
77
-		$rightConstraint = SchemaBuilder::buildConstraint($rightParentTable, 'id', $childTable, $this->_rightColumnName);
78
-
79
-		$this->pdo->query($leftConstraint);
80
-		$this->pdo->query($rightConstraint);
81
-	}
82
-
83
-	/**
84
-	 * @return void
85
-	 */	
86
-	abstract public function getTableName();
87
-
88
-	/**
89
-	 * @return void
90
-	 */
91
-	abstract protected function extendTableDefinition($columnName, $definition);
12
+    // These variables are relevant for internal bookkeeping (constraint generation etc)
13
+
14
+    /** @var string The name of the left column of the relation. */
15
+    private $_leftColumnName;
16
+
17
+    /** @var string The name of the right column of the relation. */
18
+    private $_rightColumnName;
19
+
20
+    /** @var string The name of the left table of the relation. */
21
+    private $_leftEntityTable;
22
+
23
+    /** @var string The name of the right table of the relation. */
24
+    private $_rightEntityTable;
25
+
26
+    /** @var \PDO The PDO object. */
27
+    protected $pdo;
28
+    /**
29
+     * Initializes the the ManyToManyRelation trait on the included object
30
+     * 
31
+     * @param AbstractActiveRecord $leftEntity The left entity of the relation
32
+     * @param int $leftVariable The reference to the variable where the id for the left entity will be stored
33
+     * @param AbstractActiveRecord $rightEntity The left entity of the relation
34
+     * @param int $leftVariable The reference to the variable where the id for the right entity will be stored
35
+     * @return void
36
+     */
37
+    protected function initManyToManyRelation(AbstractActiveRecord $leftEntity, &$leftVariable, AbstractActiveRecord $rightEntity, &$rightVariable)
38
+    {
39
+        $this->_leftEntityTable = $leftEntity->getTableName();
40
+        $this->_rightEntityTable = $rightEntity->getTableName();
41
+
42
+        if (get_class($leftEntity) === get_class($rightEntity)) {
43
+            $this->_leftColumnName = sprintf("id_%s_left", $leftEntity->getTableName());
44
+            $this->_rightColumnName = sprintf("id_%s_right", $rightEntity->getTableName());
45
+        } else {
46
+            $this->_leftColumnName = sprintf("id_%s", $leftEntity->getTableName());
47
+            $this->_rightColumnName = sprintf("id_%s", $rightEntity->getTableName());
48
+        }
49
+
50
+        $this->extendTableDefinition($this->_leftColumnName, [
51
+            'value' => &$leftVariable,
52
+            'validate' => null,
53
+            'type' => AbstractActiveRecord::COLUMN_TYPE_ID,
54
+            'properties' => ColumnProperty::NOT_NULL
55
+        ]);
56
+
57
+        $this->extendTableDefinition($this->_rightColumnName, [
58
+            'value' => &$rightVariable,
59
+            'validate' => null,
60
+            'type' => AbstractActiveRecord::COLUMN_TYPE_ID,
61
+            'properties' => ColumnProperty::NOT_NULL
62
+        ]);
63
+    }
64
+
65
+    /**
66
+     * Build the constraints for the many-to-many relation table
67
+     * @return void
68
+     */
69
+    public function createTableConstraints()
70
+    {
71
+        $childTable = $this->getTableName();
72
+
73
+        $leftParentTable = $this->_leftEntityTable;
74
+        $rightParentTable = $this->_rightEntityTable;
75
+
76
+        $leftConstraint = SchemaBuilder::buildConstraint($leftParentTable, 'id', $childTable, $this->_leftColumnName);
77
+        $rightConstraint = SchemaBuilder::buildConstraint($rightParentTable, 'id', $childTable, $this->_rightColumnName);
78
+
79
+        $this->pdo->query($leftConstraint);
80
+        $this->pdo->query($rightConstraint);
81
+    }
82
+
83
+    /**
84
+     * @return void
85
+     */	
86
+    abstract public function getTableName();
87
+
88
+    /**
89
+     * @return void
90
+     */
91
+    abstract protected function extendTableDefinition($columnName, $definition);
92 92
 	
93
-	/**
94
-	 * @return void
95
-	 */
96
-	abstract protected function registerSearchHook($columnName, $fn);
97
-
98
-	/**
99
-	 * @return void
100
-	 */
101
-	abstract protected function registerDeleteHook($columnName, $fn);
102
-
103
-	/**
104
-	 * @return void
105
-	 */
106
-	abstract protected function registerUpdateHook($columnName, $fn);
107
-
108
-	/**
109
-	 * @return void
110
-	 */
111
-	abstract protected function registerReadHook($columnName, $fn);
112
-
113
-	/**
114
-	 * @return void
115
-	 */
116
-	abstract protected function registerCreateHook($columnName, $fn);
93
+    /**
94
+     * @return void
95
+     */
96
+    abstract protected function registerSearchHook($columnName, $fn);
97
+
98
+    /**
99
+     * @return void
100
+     */
101
+    abstract protected function registerDeleteHook($columnName, $fn);
102
+
103
+    /**
104
+     * @return void
105
+     */
106
+    abstract protected function registerUpdateHook($columnName, $fn);
107
+
108
+    /**
109
+     * @return void
110
+     */
111
+    abstract protected function registerReadHook($columnName, $fn);
112
+
113
+    /**
114
+     * @return void
115
+     */
116
+    abstract protected function registerCreateHook($columnName, $fn);
117 117
 
118 118
 }
Please login to merge, or discard this patch.
src/AbstractActiveRecord.php 1 patch
Indentation   +484 added lines, -484 removed lines patch added patch discarded remove patch
@@ -18,489 +18,489 @@
 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
-	public 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
-	/**
222
-	 * Creates the entity as a table in the database
223
-	 */
224
-	public function createTable()
225
-	{
226
-		$this->pdo->query(SchemaBuilder::buildCreateTableSQL($this->getTableName(), $this->tableDefinition));
227
-	}
228
-
229
-	/**
230
-	 * Iterates over the specified constraints in the table definition, 
231
-	 * 		and applies these to the database.
232
-	 */
233
-	public function createTableConstraints()
234
-	{
235
-		// Iterate over columns, check whether "relation" field exists, if so create constraint
236
-		foreach ($this->tableDefinition as $colName => $definition) {
237
-			if (isset($definition['relation']) && $definition['relation'] instanceof AbstractActiveRecord) {
238
-				// Forge new relation
239
-				$target = $definition['relation'];
240
-				$constraintSql = SchemaBuilder::buildConstraint($target->getTableName(), 'id', $this->getTableName(), $colName);
241
-
242
-				$this->pdo->query($constraintSql);
243
-			} else if (isset($definition['relation'])) {
244
-				$msg = sprintf("Relation constraint on column \"%s\" of table \"%s\" does not contain a valid ActiveRecord instance", 
245
-					$colName,
246
-					$this->getTableName());
247
-				throw new ActiveRecordException($msg);
248
-			}
249
-		}
250
-	}
251
-
252
-	/**
253
-	 * Returns the name -> variable mapping for the table definition.
254
-	 * @return Array The mapping
255
-	 */
256
-	protected function getActiveRecordColumns()
257
-	{
258
-		$bindings = [];
259
-		foreach ($this->tableDefinition as $colName => $definition) {
260
-
261
-			// Ignore the id column (key) when inserting or updating
262
-			if ($colName == self::COLUMN_NAME_ID) {
263
-				continue;
264
-			}
265
-
266
-			$bindings[$colName] = &$definition['value'];
267
-		}
268
-		return $bindings;
269
-	}
270
-
271
-	protected function insertDefaults()
272
-	{
273
-		// Insert default values for not-null fields
274
-		foreach ($this->tableDefinition as $colName => $colDef) {
275
-			if ($colDef['value'] === null
276
-				&& ($colDef['properties'] ?? 0) & ColumnProperty::NOT_NULL
277
-				&& isset($colDef['default'])) {
278
-				$this->tableDefinition[$colName]['value'] = $colDef['default'];
279
-			}
280
-		}		
281
-	}
282
-
283
-	/**
284
-	 * {@inheritdoc}
285
-	 */
286
-	public function create()
287
-	{
288
-		foreach ($this->createHooks as $colName => $fn) {
289
-			$fn();
290
-		}
291
-
292
-		$this->insertDefaults();
293
-
294
-		try {
295
-			(new Query($this->getPdo(), $this->getTableName()))
296
-				->insert($this->getActiveRecordColumns())
297
-				->execute();
298
-
299
-			$this->setId(intval($this->getPdo()->lastInsertId()));
300
-		} catch (\PDOException $e) {
301
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
302
-		}
303
-
304
-		return $this;
305
-	}
306
-
307
-	/**
308
-	 * {@inheritdoc}
309
-	 */
310
-	public function read($id)
311
-	{
312
-		$whereConditions = [
313
-			Query::Equal('id', $id)
314
-		];
315
-		foreach ($this->readHooks as $colName => $fn) {
316
-			$cond = $fn();
317
-			if ($cond !== null) {
318
-				$whereConditions[] = $cond;
319
-			}
320
-		}
321
-
322
-		try {
323
-			$row = (new Query($this->getPdo(), $this->getTableName()))
324
-				->select()
325
-				->where(Query::AndArray($whereConditions))
326
-				->execute()
327
-				->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
+    public 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
+    /**
222
+     * Creates the entity as a table in the database
223
+     */
224
+    public function createTable()
225
+    {
226
+        $this->pdo->query(SchemaBuilder::buildCreateTableSQL($this->getTableName(), $this->tableDefinition));
227
+    }
228
+
229
+    /**
230
+     * Iterates over the specified constraints in the table definition, 
231
+     * 		and applies these to the database.
232
+     */
233
+    public function createTableConstraints()
234
+    {
235
+        // Iterate over columns, check whether "relation" field exists, if so create constraint
236
+        foreach ($this->tableDefinition as $colName => $definition) {
237
+            if (isset($definition['relation']) && $definition['relation'] instanceof AbstractActiveRecord) {
238
+                // Forge new relation
239
+                $target = $definition['relation'];
240
+                $constraintSql = SchemaBuilder::buildConstraint($target->getTableName(), 'id', $this->getTableName(), $colName);
241
+
242
+                $this->pdo->query($constraintSql);
243
+            } else if (isset($definition['relation'])) {
244
+                $msg = sprintf("Relation constraint on column \"%s\" of table \"%s\" does not contain a valid ActiveRecord instance", 
245
+                    $colName,
246
+                    $this->getTableName());
247
+                throw new ActiveRecordException($msg);
248
+            }
249
+        }
250
+    }
251
+
252
+    /**
253
+     * Returns the name -> variable mapping for the table definition.
254
+     * @return Array The mapping
255
+     */
256
+    protected function getActiveRecordColumns()
257
+    {
258
+        $bindings = [];
259
+        foreach ($this->tableDefinition as $colName => $definition) {
260
+
261
+            // Ignore the id column (key) when inserting or updating
262
+            if ($colName == self::COLUMN_NAME_ID) {
263
+                continue;
264
+            }
265
+
266
+            $bindings[$colName] = &$definition['value'];
267
+        }
268
+        return $bindings;
269
+    }
270
+
271
+    protected function insertDefaults()
272
+    {
273
+        // Insert default values for not-null fields
274
+        foreach ($this->tableDefinition as $colName => $colDef) {
275
+            if ($colDef['value'] === null
276
+                && ($colDef['properties'] ?? 0) & ColumnProperty::NOT_NULL
277
+                && isset($colDef['default'])) {
278
+                $this->tableDefinition[$colName]['value'] = $colDef['default'];
279
+            }
280
+        }		
281
+    }
282
+
283
+    /**
284
+     * {@inheritdoc}
285
+     */
286
+    public function create()
287
+    {
288
+        foreach ($this->createHooks as $colName => $fn) {
289
+            $fn();
290
+        }
291
+
292
+        $this->insertDefaults();
293
+
294
+        try {
295
+            (new Query($this->getPdo(), $this->getTableName()))
296
+                ->insert($this->getActiveRecordColumns())
297
+                ->execute();
298
+
299
+            $this->setId(intval($this->getPdo()->lastInsertId()));
300
+        } catch (\PDOException $e) {
301
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
302
+        }
303
+
304
+        return $this;
305
+    }
306
+
307
+    /**
308
+     * {@inheritdoc}
309
+     */
310
+    public function read($id)
311
+    {
312
+        $whereConditions = [
313
+            Query::Equal('id', $id)
314
+        ];
315
+        foreach ($this->readHooks as $colName => $fn) {
316
+            $cond = $fn();
317
+            if ($cond !== null) {
318
+                $whereConditions[] = $cond;
319
+            }
320
+        }
321
+
322
+        try {
323
+            $row = (new Query($this->getPdo(), $this->getTableName()))
324
+                ->select()
325
+                ->where(Query::AndArray($whereConditions))
326
+                ->execute()
327
+                ->fetch();
328 328
 			
329
-			if ($row === false) {
330
-				throw new ActiveRecordException(sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getTableName()));	
331
-			}
332
-
333
-			$this->fill($row)->setId($id);
334
-		} catch (\PDOException $e) {
335
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
336
-		}
337
-
338
-		return $this;
339
-	}
340
-
341
-	/**
342
-	 * {@inheritdoc}
343
-	 */
344
-	public function update()
345
-	{
346
-		foreach ($this->updateHooks as $colName => $fn) {
347
-			$fn();
348
-		}
349
-
350
-		try {
351
-			(new Query($this->getPdo(), $this->getTableName()))
352
-				->update($this->getActiveRecordColumns())
353
-				->where(Query::Equal('id', $this->getId()))
354
-				->execute();
355
-		} catch (\PDOException $e) {
356
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
357
-		}
358
-
359
-		return $this;
360
-	}
361
-
362
-	/**
363
-	 * {@inheritdoc}
364
-	 */
365
-	public function delete()
366
-	{
367
-		foreach ($this->deleteHooks as $colName => $fn) {
368
-			$fn();
369
-		}
370
-
371
-		try {
372
-			(new Query($this->getPdo(), $this->getTableName()))
373
-				->delete()
374
-				->where(Query::Equal('id', $this->getId()))
375
-				->execute();
376
-
377
-			$this->setId(null);
378
-		} catch (\PDOException $e) {
379
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
380
-		}
381
-
382
-		return $this;
383
-	}
384
-
385
-	/**
386
-	 * {@inheritdoc}
387
-	 */
388
-	public function sync()
389
-	{
390
-		if (!$this->exists()) {
391
-			return $this->create();
392
-		}
393
-
394
-		return $this->update();
395
-	}
396
-
397
-	/**
398
-	 * {@inheritdoc}
399
-	 */
400
-	public function exists()
401
-	{
402
-		return $this->getId() !== null;
403
-	}
404
-
405
-	/**
406
-	 * {@inheritdoc}
407
-	 */
408
-	public function fill(array $attributes)
409
-	{
410
-		$columns = $this->getActiveRecordColumns();
411
-		$columns['id'] = &$this->id;
412
-
413
-		foreach ($attributes as $key => $value) {
414
-			if (array_key_exists($key, $columns)) {
415
-				$columns[$key] = $value;
416
-			}
417
-		}
418
-
419
-		return $this;
420
-	}
421
-
422
-	/**
423
-	 * {@inheritdoc}
424
-	 */
425
-	public function search(array $ignoredTraits = [])
426
-	{
427
-		$clauses = [];
428
-		foreach ($this->searchHooks as $column => $fn) {
429
-			if (!in_array($column, $ignoredTraits)) {
430
-				$clauses[] = $fn();
431
-			}
432
-		}
433
-
434
-		return new ActiveRecordQuery($this, $clauses);
435
-	}
436
-
437
-	/**
438
-	 * Returns the PDO.
439
-	 *
440
-	 * @return \PDO the PDO.
441
-	 */
442
-	public function getPdo()
443
-	{
444
-		return $this->pdo;
445
-	}
446
-
447
-	/**
448
-	 * Set the PDO.
449
-	 *
450
-	 * @param \PDO $pdo
451
-	 * @return $this
452
-	 */
453
-	protected function setPdo($pdo)
454
-	{
455
-		$this->pdo = $pdo;
456
-
457
-		return $this;
458
-	}
459
-
460
-	/**
461
-	 * Returns the ID.
462
-	 *
463
-	 * @return null|int The ID.
464
-	 */
465
-	public function getId()
466
-	{
467
-		return $this->id;
468
-	}
469
-
470
-	/**
471
-	 * Set the ID.
472
-	 *
473
-	 * @param int $id
474
-	 * @return $this
475
-	 */
476
-	protected function setId($id)
477
-	{
478
-		$this->id = $id;
479
-
480
-		return $this;
481
-	}
482
-
483
-	public function getFinalTableDefinition()
484
-	{
485
-		return $this->tableDefinition;
486
-	}
487
-
488
-	public function newInstance()
489
-	{
490
-		return new static($this->pdo);
491
-	}
492
-
493
-	/**
494
-	 * Returns the active record table.
495
-	 *
496
-	 * @return string the active record table name.
497
-	 */
498
-	abstract public function getTableName();
499
-
500
-	/**
501
-	 * Returns the active record columns.
502
-	 *
503
-	 * @return array the active record columns.
504
-	 */
505
-	abstract protected function getTableDefinition();
329
+            if ($row === false) {
330
+                throw new ActiveRecordException(sprintf('Can not read the non-existent active record entry %d from the `%s` table.', $id, $this->getTableName()));	
331
+            }
332
+
333
+            $this->fill($row)->setId($id);
334
+        } catch (\PDOException $e) {
335
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
336
+        }
337
+
338
+        return $this;
339
+    }
340
+
341
+    /**
342
+     * {@inheritdoc}
343
+     */
344
+    public function update()
345
+    {
346
+        foreach ($this->updateHooks as $colName => $fn) {
347
+            $fn();
348
+        }
349
+
350
+        try {
351
+            (new Query($this->getPdo(), $this->getTableName()))
352
+                ->update($this->getActiveRecordColumns())
353
+                ->where(Query::Equal('id', $this->getId()))
354
+                ->execute();
355
+        } catch (\PDOException $e) {
356
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
357
+        }
358
+
359
+        return $this;
360
+    }
361
+
362
+    /**
363
+     * {@inheritdoc}
364
+     */
365
+    public function delete()
366
+    {
367
+        foreach ($this->deleteHooks as $colName => $fn) {
368
+            $fn();
369
+        }
370
+
371
+        try {
372
+            (new Query($this->getPdo(), $this->getTableName()))
373
+                ->delete()
374
+                ->where(Query::Equal('id', $this->getId()))
375
+                ->execute();
376
+
377
+            $this->setId(null);
378
+        } catch (\PDOException $e) {
379
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
380
+        }
381
+
382
+        return $this;
383
+    }
384
+
385
+    /**
386
+     * {@inheritdoc}
387
+     */
388
+    public function sync()
389
+    {
390
+        if (!$this->exists()) {
391
+            return $this->create();
392
+        }
393
+
394
+        return $this->update();
395
+    }
396
+
397
+    /**
398
+     * {@inheritdoc}
399
+     */
400
+    public function exists()
401
+    {
402
+        return $this->getId() !== null;
403
+    }
404
+
405
+    /**
406
+     * {@inheritdoc}
407
+     */
408
+    public function fill(array $attributes)
409
+    {
410
+        $columns = $this->getActiveRecordColumns();
411
+        $columns['id'] = &$this->id;
412
+
413
+        foreach ($attributes as $key => $value) {
414
+            if (array_key_exists($key, $columns)) {
415
+                $columns[$key] = $value;
416
+            }
417
+        }
418
+
419
+        return $this;
420
+    }
421
+
422
+    /**
423
+     * {@inheritdoc}
424
+     */
425
+    public function search(array $ignoredTraits = [])
426
+    {
427
+        $clauses = [];
428
+        foreach ($this->searchHooks as $column => $fn) {
429
+            if (!in_array($column, $ignoredTraits)) {
430
+                $clauses[] = $fn();
431
+            }
432
+        }
433
+
434
+        return new ActiveRecordQuery($this, $clauses);
435
+    }
436
+
437
+    /**
438
+     * Returns the PDO.
439
+     *
440
+     * @return \PDO the PDO.
441
+     */
442
+    public function getPdo()
443
+    {
444
+        return $this->pdo;
445
+    }
446
+
447
+    /**
448
+     * Set the PDO.
449
+     *
450
+     * @param \PDO $pdo
451
+     * @return $this
452
+     */
453
+    protected function setPdo($pdo)
454
+    {
455
+        $this->pdo = $pdo;
456
+
457
+        return $this;
458
+    }
459
+
460
+    /**
461
+     * Returns the ID.
462
+     *
463
+     * @return null|int The ID.
464
+     */
465
+    public function getId()
466
+    {
467
+        return $this->id;
468
+    }
469
+
470
+    /**
471
+     * Set the ID.
472
+     *
473
+     * @param int $id
474
+     * @return $this
475
+     */
476
+    protected function setId($id)
477
+    {
478
+        $this->id = $id;
479
+
480
+        return $this;
481
+    }
482
+
483
+    public function getFinalTableDefinition()
484
+    {
485
+        return $this->tableDefinition;
486
+    }
487
+
488
+    public function newInstance()
489
+    {
490
+        return new static($this->pdo);
491
+    }
492
+
493
+    /**
494
+     * Returns the active record table.
495
+     *
496
+     * @return string the active record table name.
497
+     */
498
+    abstract public function getTableName();
499
+
500
+    /**
501
+     * Returns the active record columns.
502
+     *
503
+     * @return array the active record columns.
504
+     */
505
+    abstract protected function getTableDefinition();
506 506
 }
Please login to merge, or discard this patch.