Completed
Push — v2 ( 4d3385...e36f84 )
by Berend
04:08
created
src/ColumnProperty.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -5,10 +5,10 @@
 block discarded – undo
5 5
 
6 6
 class ColumnProperty
7 7
 {
8
-	const NONE = 0;
9
-	const UNIQUE = 1;
10
-	const NOT_NULL = 2;
11
-	const IMMUTABLE = 4;
12
-	const AUTO_INCREMENT = 8;
13
-	const PRIMARY_KEY = 16;
8
+    const NONE = 0;
9
+    const UNIQUE = 1;
10
+    const NOT_NULL = 2;
11
+    const IMMUTABLE = 4;
12
+    const AUTO_INCREMENT = 8;
13
+    const PRIMARY_KEY = 16;
14 14
 }
15 15
\ No newline at end of file
Please login to merge, or discard this patch.
test-bootstrap.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 // Cleanup SQL
10 10
 $user_delete = "DROP USER IF EXISTS $dbuser@'localhost'; ";
11 11
 $database_delete = "DROP DATABASE IF EXISTS $dbname; ";
12
-$sql_cleanup = $user_delete . $database_delete;
12
+$sql_cleanup = $user_delete.$database_delete;
13 13
 
14 14
 // Setup SQL
15 15
 $db_create = "CREATE DATABASE $dbname; ";
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 $user_alter = "ALTER USER '$dbuser'@'localhost' IDENTIFIED with mysql_native_password BY '$dbpass'; ";
18 18
 $user_grant = "GRANT ALL PRIVILEGES ON *.* TO '$dbuser'@'localhost';";
19 19
 
20
-$sql_setup = $sql_cleanup . $db_create . $user_create . $user_alter . $user_grant;
20
+$sql_setup = $sql_cleanup.$db_create.$user_create.$user_alter.$user_grant;
21 21
 print $sql_setup;
22 22
 echo "Please enter mysql root password to set up a database environment for testing\n";
23 23
 exec("echo \"$sql_setup\" | mysql -u root -p");
Please login to merge, or discard this patch.
src/ActiveRecordInterface.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -19,72 +19,72 @@
 block discarded – undo
19 19
 interface ActiveRecordInterface
20 20
 {
21 21
 
22
-	public function __construct(\PDO $pdo);
22
+    public function __construct(\PDO $pdo);
23 23
 	
24
-	/**
25
-	 * Returns this active record after creating an entry with the records attributes.
26
-	 *
27
-	 * @return $this
28
-	 * @throws ActiveRecordException on failure.
29
-	 */
30
-	public function create();
24
+    /**
25
+     * Returns this active record after creating an entry with the records attributes.
26
+     *
27
+     * @return $this
28
+     * @throws ActiveRecordException on failure.
29
+     */
30
+    public function create();
31 31
 
32
-	/**
33
-	 * Returns this active record after reading the attributes from the entry with the given identifier.
34
-	 *
35
-	 * @param mixed $id
36
-	 * @return $this
37
-	 * @throws ActiveRecordException on failure.
38
-	 */
39
-	public function read($id);
32
+    /**
33
+     * Returns this active record after reading the attributes from the entry with the given identifier.
34
+     *
35
+     * @param mixed $id
36
+     * @return $this
37
+     * @throws ActiveRecordException on failure.
38
+     */
39
+    public function read($id);
40 40
 
41
-	/**
42
-	 * Returns this active record after updating the attributes to the corresponding entry.
43
-	 *
44
-	 * @return $this
45
-	 * @throws ActiveRecordException on failure.
46
-	 */
47
-	public function update();
41
+    /**
42
+     * Returns this active record after updating the attributes to the corresponding entry.
43
+     *
44
+     * @return $this
45
+     * @throws ActiveRecordException on failure.
46
+     */
47
+    public function update();
48 48
 
49
-	/**
50
-	 * Returns this record after deleting the corresponding entry.
51
-	 *
52
-	 * @return $this
53
-	 * @throws ActiveRecordException on failure.
54
-	 */
55
-	public function delete();
49
+    /**
50
+     * Returns this record after deleting the corresponding entry.
51
+     *
52
+     * @return $this
53
+     * @throws ActiveRecordException on failure.
54
+     */
55
+    public function delete();
56 56
 
57
-	/**
58
-	 * Returns this record after synchronizing it with the corresponding entry.
59
-	 * A new entry is created if this active record does not have a corresponding entry.
60
-	 *
61
-	 * @return $this
62
-	 * @throws ActiveRecordException on failure.
63
-	 */
64
-	public function sync();
57
+    /**
58
+     * Returns this record after synchronizing it with the corresponding entry.
59
+     * A new entry is created if this active record does not have a corresponding entry.
60
+     *
61
+     * @return $this
62
+     * @throws ActiveRecordException on failure.
63
+     */
64
+    public function sync();
65 65
 
66
-	/**
67
-	 * Returns true if this active record has a corresponding entry.
68
-	 *
69
-	 * @return bool true if this active record has a corresponding entry.
70
-	 */
71
-	public function exists();
66
+    /**
67
+     * Returns true if this active record has a corresponding entry.
68
+     *
69
+     * @return bool true if this active record has a corresponding entry.
70
+     */
71
+    public function exists();
72 72
 
73
-	/**
74
-	 * Returns this record after filling it with the given attributes.
75
-	 *
76
-	 * @param array $attributes = []
77
-	 * @return $this
78
-	 * @throws ActiveRecordException on failure.
79
-	 */
80
-	public function fill(array $attributes);
73
+    /**
74
+     * Returns this record after filling it with the given attributes.
75
+     *
76
+     * @param array $attributes = []
77
+     * @return $this
78
+     * @throws ActiveRecordException on failure.
79
+     */
80
+    public function fill(array $attributes);
81 81
 
82
-	/**
83
-	 * Returns the records with the given where, order by, limit and offset clauses.
84
-	 *
85
-	 * @param array $excludedTraits
86
-	 * @return ActiveRecordQuery the query representing the current search.
87
-	 * @throws ActiveRecordException on failure.
88
-	 */
89
-	public function search(Array $excludedTraits);
82
+    /**
83
+     * Returns the records with the given where, order by, limit and offset clauses.
84
+     *
85
+     * @param array $excludedTraits
86
+     * @return ActiveRecordQuery the query representing the current search.
87
+     * @throws ActiveRecordException on failure.
88
+     */
89
+    public function search(Array $excludedTraits);
90 90
 }
Please login to merge, or discard this patch.
src/Traits/SoftDelete.php 1 patch
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -9,111 +9,111 @@
 block discarded – undo
9 9
 
10 10
 trait SoftDelete
11 11
 {
12
-	/** @var boolean the soft delete status for the entity this trait is embedded into. */
13
-	protected $softDelete;
14
-
15
-	/**
16
-	 * this method is required to be called in the constructor for each class that uses this trait. 
17
-	 * It adds the required fields to the table definition and registers hooks
18
-	 */
19
-	protected function initSoftDelete()
20
-	{
21
-		$this->softDelete = false;
22
-
23
-		$this->extendTableDefinition(TRAIT_SOFT_DELETE_FIELD_KEY, [
24
-			'value' => &$this->softDelete,
25
-			'validate' => null,
26
-			'default' => 0,
27
-			'type' => 'INT',
28
-			'length' => 1,
29
-			'properties' => ColumnProperty::NOT_NULL
30
-		]);
31
-
32
-		$this->registerSearchHook(TRAIT_SOFT_DELETE_FIELD_KEY, 'softDeleteSearchHook');
33
-		$this->registerReadHook(TRAIT_SOFT_DELETE_FIELD_KEY, 'softDeleteReadHook');
34
-	}
35
-
36
-	/**
37
-	 * The hook that gets called whenever a query is made
38
-	 */
39
-	protected function softDeleteSearchHook()
40
-	{
41
-		return Query::Equal(TRAIT_SOFT_DELETE_FIELD_KEY, 0);
42
-	}
43
-
44
-	protected function softDeleteReadHook()
45
-	{
46
-		return Query::Equal(TRAIT_SOFT_DELETE_FIELD_KEY, 0);
47
-	}
48
-
49
-	/**
50
-	 * returns the name for the soft delete field in the database
51
-	 * @return string
52
-	 */
53
-	public function getSoftDeleteFieldName()
54
-	{
55
-		return TRAIT_SOFT_DELETE_FIELD_KEY;
56
-	}
12
+    /** @var boolean the soft delete status for the entity this trait is embedded into. */
13
+    protected $softDelete;
14
+
15
+    /**
16
+     * this method is required to be called in the constructor for each class that uses this trait. 
17
+     * It adds the required fields to the table definition and registers hooks
18
+     */
19
+    protected function initSoftDelete()
20
+    {
21
+        $this->softDelete = false;
22
+
23
+        $this->extendTableDefinition(TRAIT_SOFT_DELETE_FIELD_KEY, [
24
+            'value' => &$this->softDelete,
25
+            'validate' => null,
26
+            'default' => 0,
27
+            'type' => 'INT',
28
+            'length' => 1,
29
+            'properties' => ColumnProperty::NOT_NULL
30
+        ]);
31
+
32
+        $this->registerSearchHook(TRAIT_SOFT_DELETE_FIELD_KEY, 'softDeleteSearchHook');
33
+        $this->registerReadHook(TRAIT_SOFT_DELETE_FIELD_KEY, 'softDeleteReadHook');
34
+    }
35
+
36
+    /**
37
+     * The hook that gets called whenever a query is made
38
+     */
39
+    protected function softDeleteSearchHook()
40
+    {
41
+        return Query::Equal(TRAIT_SOFT_DELETE_FIELD_KEY, 0);
42
+    }
43
+
44
+    protected function softDeleteReadHook()
45
+    {
46
+        return Query::Equal(TRAIT_SOFT_DELETE_FIELD_KEY, 0);
47
+    }
48
+
49
+    /**
50
+     * returns the name for the soft delete field in the database
51
+     * @return string
52
+     */
53
+    public function getSoftDeleteFieldName()
54
+    {
55
+        return TRAIT_SOFT_DELETE_FIELD_KEY;
56
+    }
57 57
 	
58
-	/**
59
-	 * Mark the current record as soft deleted
60
-	 * @return $this
61
-	 */
62
-	public function softDelete()
63
-	{
64
-		$this->softDelete = true;
65
-		$this->update();
66
-		return $this;
67
-	}
68
-
69
-	/**
70
-	 * Undo the current soft deletion status (mark it as non-soft deleted)
71
-	 * @return $this
72
-	 */
73
-	public function softRestore()
74
-	{
75
-		$this->softDelete = false;
76
-		$this->update();
77
-		return $this;
78
-	}
79
-
80
-	/**
81
-	 * returns the current soft deletion status
82
-	 * @return $this
83
-	 */
84
-	public function getDeletionStatus() 
85
-	{
86
-		return $this->softDelete;
87
-	}
88
-
89
-	/**
90
-	 * @return void
91
-	 */
92
-	abstract protected function extendTableDefinition($columnName, $definition);
58
+    /**
59
+     * Mark the current record as soft deleted
60
+     * @return $this
61
+     */
62
+    public function softDelete()
63
+    {
64
+        $this->softDelete = true;
65
+        $this->update();
66
+        return $this;
67
+    }
68
+
69
+    /**
70
+     * Undo the current soft deletion status (mark it as non-soft deleted)
71
+     * @return $this
72
+     */
73
+    public function softRestore()
74
+    {
75
+        $this->softDelete = false;
76
+        $this->update();
77
+        return $this;
78
+    }
79
+
80
+    /**
81
+     * returns the current soft deletion status
82
+     * @return $this
83
+     */
84
+    public function getDeletionStatus() 
85
+    {
86
+        return $this->softDelete;
87
+    }
88
+
89
+    /**
90
+     * @return void
91
+     */
92
+    abstract protected function extendTableDefinition($columnName, $definition);
93 93
 	
94
-	/**
95
-	 * @return void
96
-	 */
97
-	abstract protected function registerSearchHook($columnName, $fn);
98
-
99
-	/**
100
-	 * @return void
101
-	 */
102
-	abstract protected function registerDeleteHook($columnName, $fn);
103
-
104
-	/**
105
-	 * @return void
106
-	 */
107
-	abstract protected function registerUpdateHook($columnName, $fn);
108
-
109
-	/**
110
-	 * @return void
111
-	 */
112
-	abstract protected function registerReadHook($columnName, $fn);
113
-
114
-	/**
115
-	 * @return void
116
-	 */
117
-	abstract protected function registerCreateHook($columnName, $fn);
94
+    /**
95
+     * @return void
96
+     */
97
+    abstract protected function registerSearchHook($columnName, $fn);
98
+
99
+    /**
100
+     * @return void
101
+     */
102
+    abstract protected function registerDeleteHook($columnName, $fn);
103
+
104
+    /**
105
+     * @return void
106
+     */
107
+    abstract protected function registerUpdateHook($columnName, $fn);
108
+
109
+    /**
110
+     * @return void
111
+     */
112
+    abstract protected function registerReadHook($columnName, $fn);
113
+
114
+    /**
115
+     * @return void
116
+     */
117
+    abstract protected function registerCreateHook($columnName, $fn);
118 118
 	
119 119
 }
120 120
\ No newline at end of file
Please login to merge, or discard this patch.
src/SchemaBuilder.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -268,7 +268,7 @@
 block discarded – undo
268 268
 		}
269 269
 
270 270
 		if ($default !== NULL) {
271
-			$stmnt .= 'DEFAULT ' . var_export($default, true) . ' ';
271
+			$stmnt .= 'DEFAULT '.var_export($default, true).' ';
272 272
 		}
273 273
 
274 274
 		if ($properties & ColumnProperty::AUTO_INCREMENT) {
Please login to merge, or discard this 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) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 
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) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 
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
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.
Indentation   +375 added lines, -375 removed lines patch added patch discarded remove patch
@@ -9,395 +9,395 @@
 block discarded – undo
9 9
 
10 10
 trait AutoApi
11 11
 {
12
-	/* =======================================================================
12
+    /* =======================================================================
13 13
 	 * ===================== Automatic API Support ===========================
14 14
 	 * ======================================================================= */
15 15
 
16
-	/** @var array A map of column name to functions that hook the insert function */
17
-	protected $createHooks;
16
+    /** @var array A map of column name to functions that hook the insert function */
17
+    protected $createHooks;
18 18
 
19
-	/** @var array A map of column name to functions that hook the read function */
20
-	protected $readHooks;
19
+    /** @var array A map of column name to functions that hook the read function */
20
+    protected $readHooks;
21 21
 
22
-	/** @var array A map of column name to functions that hook the update function */
23
-	protected $updateHooks;
22
+    /** @var array A map of column name to functions that hook the update function */
23
+    protected $updateHooks;
24 24
 
25
-	/** @var array A map of column name to functions that hook the update function */
26
-	protected $deleteHooks;	
25
+    /** @var array A map of column name to functions that hook the update function */
26
+    protected $deleteHooks;	
27 27
 
28
-	/** @var array A map of column name to functions that hook the search function */
29
-	protected $searchHooks;
28
+    /** @var array A map of column name to functions that hook the search function */
29
+    protected $searchHooks;
30 30
 
31
-	/** @var array A list of table column definitions */
32
-	protected $tableDefinition;
31
+    /** @var array A list of table column definitions */
32
+    protected $tableDefinition;
33 33
 
34 34
 
35
-	/**
36
-	 * @param Array $queryparams associative array of query params. Reserved options are
37
-	 *                             "search_order_by", "search_order_direction", "search_limit", "search_offset"
38
-	 *                             or column names corresponding to an instance of miBadger\Query\QueryExpression
39
-	 * @param Array $fieldWhitelist names of the columns that will appear in the output results
40
-	 * 
41
-	 * @return Array an associative array containing the query parameters, and a data field containing an array of search results (associative arrays indexed by the keys in $fieldWhitelist)
42
-	 */
43
-	public function apiSearch(Array $queryParams, Array $fieldWhitelist, ?QueryExpression $whereClause = null, int $maxResultLimit = 100): Array
44
-	{
45
-		$query = $this->search();
35
+    /**
36
+     * @param Array $queryparams associative array of query params. Reserved options are
37
+     *                             "search_order_by", "search_order_direction", "search_limit", "search_offset"
38
+     *                             or column names corresponding to an instance of miBadger\Query\QueryExpression
39
+     * @param Array $fieldWhitelist names of the columns that will appear in the output results
40
+     * 
41
+     * @return Array an associative array containing the query parameters, and a data field containing an array of search results (associative arrays indexed by the keys in $fieldWhitelist)
42
+     */
43
+    public function apiSearch(Array $queryParams, Array $fieldWhitelist, ?QueryExpression $whereClause = null, int $maxResultLimit = 100): Array
44
+    {
45
+        $query = $this->search();
46 46
 
47
-		// Build query
48
-		$orderColumn = $queryParams['search_order_by'] ?? null;
49
-		if (!in_array($orderColumn, $fieldWhitelist)) {
50
-			$orderColumn = null;
51
-		}
47
+        // Build query
48
+        $orderColumn = $queryParams['search_order_by'] ?? null;
49
+        if (!in_array($orderColumn, $fieldWhitelist)) {
50
+            $orderColumn = null;
51
+        }
52 52
 
53
-		$orderDirection = $queryParams['search_order_direction'] ?? null;
54
-		if ($orderColumn !== null) {
55
-			$query->orderBy($orderColumn, $orderDirection);
56
-		}
53
+        $orderDirection = $queryParams['search_order_direction'] ?? null;
54
+        if ($orderColumn !== null) {
55
+            $query->orderBy($orderColumn, $orderDirection);
56
+        }
57 57
 		
58
-		if ($whereClause !== null) {
59
-			$query->where($whereClause);
60
-		}
61
-
62
-		$limit = min((int) ($queryParams['search_limit'] ?? $maxResultLimit), $maxResultLimit);
63
-		$query->limit($limit);
64
-
65
-		$offset = $queryParams['search_offset'] ?? 0;
66
-		$query->offset($offset);
67
-
68
-		$numPages = $query->getNumberOfPages();
69
-		$currentPage = $query->getCurrentPage();
70
-
71
-		// Fetch results
72
-		$results = $query->fetchAll();
73
-		$resultsArray = [];
74
-		foreach ($results as $result) {
75
-			$resultsArray[] = $result->toArray($fieldWhitelist);
76
-		}
77
-
78
-		return [
79
-			'search_offset' => $offset,
80
-			'search_limit' => $limit,
81
-			'search_order_by' => $orderColumn,
82
-			'search_order_direction' => $orderDirection,
83
-			'search_pages' => $numPages,
84
-			'search_current' => $currentPage,
85
-			'data' => $resultsArray
86
-		];
87
-	}
88
-
89
-	public function toArray($fieldWhitelist)
90
-	{
91
-		$output = [];
92
-		foreach ($this->tableDefinition as $colName => $definition) {
93
-			if (in_array($colName, $fieldWhitelist)) {
94
-				$output[$colName] = $definition['value'];
95
-			}
96
-		}
97
-
98
-		return $output;
99
-	}
100
-
101
-	/**
102
-	 * @param string|int $id the id of the current entity
103
-	 * @param Array $fieldWhitelist an array of fields that are allowed to appear in the output
104
-	 * 
105
-	 * @param Array An associative array containing the data for this record, 
106
-	 * 				where the keys are entries in $fieldWhitelist
107
-	 */
108
-	public function apiRead($id, Array $fieldWhitelist): Array
109
-	{
110
-		// @TODO: Should apiRead throw exception or return null on fail?
111
-		$this->read($id);
112
-		return $this->toArray($fieldWhitelist);
113
-	}
114
-
115
-	/* =============================================================
58
+        if ($whereClause !== null) {
59
+            $query->where($whereClause);
60
+        }
61
+
62
+        $limit = min((int) ($queryParams['search_limit'] ?? $maxResultLimit), $maxResultLimit);
63
+        $query->limit($limit);
64
+
65
+        $offset = $queryParams['search_offset'] ?? 0;
66
+        $query->offset($offset);
67
+
68
+        $numPages = $query->getNumberOfPages();
69
+        $currentPage = $query->getCurrentPage();
70
+
71
+        // Fetch results
72
+        $results = $query->fetchAll();
73
+        $resultsArray = [];
74
+        foreach ($results as $result) {
75
+            $resultsArray[] = $result->toArray($fieldWhitelist);
76
+        }
77
+
78
+        return [
79
+            'search_offset' => $offset,
80
+            'search_limit' => $limit,
81
+            'search_order_by' => $orderColumn,
82
+            'search_order_direction' => $orderDirection,
83
+            'search_pages' => $numPages,
84
+            'search_current' => $currentPage,
85
+            'data' => $resultsArray
86
+        ];
87
+    }
88
+
89
+    public function toArray($fieldWhitelist)
90
+    {
91
+        $output = [];
92
+        foreach ($this->tableDefinition as $colName => $definition) {
93
+            if (in_array($colName, $fieldWhitelist)) {
94
+                $output[$colName] = $definition['value'];
95
+            }
96
+        }
97
+
98
+        return $output;
99
+    }
100
+
101
+    /**
102
+     * @param string|int $id the id of the current entity
103
+     * @param Array $fieldWhitelist an array of fields that are allowed to appear in the output
104
+     * 
105
+     * @param Array An associative array containing the data for this record, 
106
+     * 				where the keys are entries in $fieldWhitelist
107
+     */
108
+    public function apiRead($id, Array $fieldWhitelist): Array
109
+    {
110
+        // @TODO: Should apiRead throw exception or return null on fail?
111
+        $this->read($id);
112
+        return $this->toArray($fieldWhitelist);
113
+    }
114
+
115
+    /* =============================================================
116 116
 	 * ===================== Constraint validation =================
117 117
 	 * ============================================================= */
118 118
 
119
-	/**
120
-	 * Copy all table variables between two instances
121
-	 */
122
-	public function syncInstanceFrom($from)
123
-	{
124
-		foreach ($this->tableDefinition as $colName => $definition) {
125
-			$this->tableDefinition[$colName]['value'] = $from->tableDefinition[$colName]['value'];
126
-		}
127
-	}
128
-
129
-	private function filterInputColumns($input, $whitelist)
130
-	{
131
-		$filteredInput = $input;
132
-		foreach ($input as $colName => $value) {
133
-			if (!in_array($colName, $whitelist)) {
134
-				unset($filteredInput[$colName]);
135
-			}
136
-		}
137
-		return $filteredInput;
138
-	}
139
-
140
-	private function validateExcessKeys($input)
141
-	{
142
-		$errors = [];
143
-		foreach ($input as $colName => $value) {
144
-			if (!array_key_exists($colName, $this->tableDefinition)) {
145
-				$errors[$colName] = "Unknown input field";
146
-				continue;
147
-			}
148
-		}
149
-		return $errors;
150
-	}
151
-
152
-	private function validateImmutableColumns($input)
153
-	{
154
-		$errors = [];
155
-		foreach ($this->tableDefinition as $colName => $definition) {
156
-			$property = $definition['properties'] ?? null;
157
-			if (array_key_exists($colName, $input)
158
-				&& $property & ColumnProperty::IMMUTABLE) {
159
-				$errors[$colName] = "Field cannot be changed";
160
-			}
161
-		}
162
-		return $errors;
163
-	}
164
-
165
-	/**
166
-	 * Checks whether input values are correct:
167
-	 * 1. Checks whether a value passes the validation function for that column
168
-	 * 2. Checks whether a value supplied to a relationship column is a valid value
169
-	 */
170
-	private function validateInputValues($input)
171
-	{
172
-		$errors = [];
173
-		foreach ($this->tableDefinition as $colName => $definition) {
174
-			// Validation check 1: If validate function is present
175
-			if (array_key_exists($colName, $input) 
176
-				&& is_callable($definition['validate'] ?? null)) {
177
-				$inputValue = $input[$colName];
178
-
179
-				// If validation function fails
180
-				[$status, $message] = $definition['validate']($inputValue);
181
-				if (!$status) {
182
-					$errors[$colName] = $message;
183
-				}	
184
-			}
185
-
186
-			// Validation check 2: If relation column, check whether entity exists
187
-			$properties = $definition['properties'] ?? null;
188
-			if (isset($definition['relation'])
189
-				&& ($properties & ColumnProperty::NOT_NULL)) {
190
-				$instance = clone $definition['relation'];
191
-				try {
192
-					$instance->read($input[$colName] ?? $definition['value'] ?? null);
193
-				} catch (ActiveRecordException $e) {
194
-					$errors[$colName] = "Entity for this value doesn't exist";
195
-				}
196
-			}
197
-		}
198
-		return $errors;
199
-	}
200
-
201
-	/**
202
-	 * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
203
-	 * Determines whether there are required columns for which no data is provided
204
-	 */
205
-	private function validateMissingKeys($input)
206
-	{
207
-		$errors = [];
208
-
209
-		foreach ($this->tableDefinition as $colName => $colDefinition) {
210
-			$default = $colDefinition['default'] ?? null;
211
-			$properties = $colDefinition['properties'] ?? null;
212
-			$value = $colDefinition['value'];
213
-
214
-			// If nullable and default not set => null
215
-			// If nullable and default null => default (null)
216
-			// If nullable and default set => default (value)
217
-
218
-			// if not nullable and default not set => error
219
-			// if not nullable and default null => error
220
-			// if not nullable and default st => default (value)
221
-			// => if not nullable and default null and value not set (or null) => error message in this method
222
-			if ($properties & ColumnProperty::NOT_NULL
223
-				&& $default === null
224
-				&& !($properties & ColumnProperty::AUTO_INCREMENT)
225
-				&& (!array_key_exists($colName, $input) 
226
-					|| $input[$colName] === null 
227
-					|| (is_string($input[$colName]) && $input[$colName] === '') )
228
-				&& ($value === null
229
-					|| (is_string($value) && $value === ''))) {
230
-				$errors[$colName] = sprintf("The required field \"%s\" is missing", $colName);
231
-			} 
232
-		}
233
-
234
-		return $errors;
235
-	}
236
-
237
-	/**
238
-	 * Copies the values for entries in the input with matching variable names in the record definition
239
-	 * @param Array $input The input data to be loaded into $this record
240
-	 */
241
-	private function loadData($input)
242
-	{
243
-		foreach ($this->tableDefinition as $colName => $definition) {
244
-			if (array_key_exists($colName, $input)) {
245
-				$definition['value'] = $input[$colName];
246
-			}
247
-		}
248
-	}
249
-
250
-	/**
251
-	 * @param Array $input Associative array of input values
252
-	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
253
-	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
254
-	 * 					of the modified data.
255
-	 */
256
-	public function apiCreate(Array $input, Array $createWhitelist, Array $readWhitelist)
257
-	{
258
-		// Clone $this to new instance (for restoring if validation goes wrong)
259
-		$transaction = $this->newInstance();
260
-		$errors = [];
261
-
262
-		// Filter out all non-whitelisted input values
263
-		$input = $this->filterInputColumns($input, $createWhitelist);
264
-
265
-		// Validate excess keys
266
-		$errors += $transaction->validateExcessKeys($input);
267
-
268
-		// Validate input values (using validation function)
269
-		$errors += $transaction->validateInputValues($input);
270
-
271
-		// "Copy" data into transaction
272
-		$transaction->loadData($input);
273
-
274
-		// Run create hooks
275
-		foreach ($transaction->createHooks as $colName => $fn) {
276
-			$fn();
277
-		}
278
-
279
-		// Validate missing keys
280
-		$errors += $transaction->validateMissingKeys($input);
281
-
282
-		// If no errors, commit the pending data
283
-		if (empty($errors)) {
284
-			$this->syncInstanceFrom($transaction);
285
-
286
-			// Insert default values for not-null fields
287
-			$this->insertDefaults();
288
-
289
-			try {
290
-				(new Query($this->getPdo(), $this->getTableName()))
291
-					->insert($this->getActiveRecordColumns())
292
-					->execute();
293
-
294
-				$this->setId(intval($this->getPdo()->lastInsertId()));
295
-			} catch (\PDOException $e) {
296
-				// @TODO: Potentially filter and store mysql messages (where possible) in error messages
297
-				throw new ActiveRecordException($e->getMessage(), 0, $e);
298
-			}
299
-
300
-			return [null, $this->toArray($readWhitelist)];
301
-		} else {
302
-			return [$errors, null];
303
-		}
304
-	}
305
-
306
-	/**
307
-	 * @param Array $input Associative array of input values
308
-	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
309
-	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
310
-	 * 					of the modified data.
311
-	 */
312
-	public function apiUpdate(Array $input, Array $updateWhitelist, Array $readWhitelist)
313
-	{
314
-		$transaction = $this->newInstance();
315
-		$transaction->syncInstanceFrom($this);
316
-		$errors = [];
317
-
318
-		// Filter out all non-whitelisted input values
319
-		$input = $this->filterInputColumns($input, $updateWhitelist);
320
-
321
-		// Check for excess keys
322
-		$errors += $transaction->validateExcessKeys($input);
323
-
324
-		// Check for immutable keys
325
-		$errors += $transaction->validateImmutableColumns($input);
326
-
327
-		// Validate input values (using validation function)
328
-		$errors += $transaction->validateInputValues($input);
329
-
330
-		// "Copy" data into transaction
331
-		$transaction->loadData($input);
332
-
333
-		// Run create hooks
334
-		foreach ($transaction->updateHooks as $colName => $fn) {
335
-			$fn();
336
-		}
337
-
338
-		// Validate missing keys
339
-		$errors += $transaction->validateMissingKeys($input);
340
-
341
-		// Update database
342
-		if (empty($errors)) {
343
-			$this->syncInstanceFrom($transaction);
344
-
345
-			try {
346
-				(new Query($this->getPdo(), $this->getTableName()))
347
-					->update($this->getActiveRecordColumns())
348
-					->where(Query::Equal('id', $this->getId()))
349
-					->execute();
350
-			} catch (\PDOException $e) {
351
-				throw new ActiveRecordException($e->getMessage(), 0, $e);
352
-			}
353
-
354
-			return [null, $this->toArray($readWhitelist)];
355
-		} else {
356
-			return [$errors, null];
357
-		}
358
-	}
359
-
360
-	/**
361
-	 * Returns this active record after reading the attributes from the entry with the given identifier.
362
-	 *
363
-	 * @param mixed $id
364
-	 * @return $this
365
-	 * @throws ActiveRecordException on failure.
366
-	 */
367
-	abstract public function read($id);
368
-
369
-	/**
370
-	 * Returns the PDO.
371
-	 *
372
-	 * @return \PDO the PDO.
373
-	 */
374
-	abstract public function getPdo();
375
-
376
-	/**
377
-	 * Set the ID.
378
-	 *
379
-	 * @param int $id
380
-	 * @return $this
381
-	 */
382
-	abstract protected function setId($id);
383
-
384
-	/**
385
-	 * Returns the ID.
386
-	 *
387
-	 * @return null|int The ID.
388
-	 */
389
-	abstract protected function getId();
390
-
391
-	/**
392
-	 * Returns the active record table.
393
-	 *
394
-	 * @return string the active record table name.
395
-	 */
396
-	abstract public function getTableName();
397
-
398
-	/**
399
-	 * Returns the name -> variable mapping for the table definition.
400
-	 * @return Array The mapping
401
-	 */
402
-	abstract protected function getActiveRecordColumns();
119
+    /**
120
+     * Copy all table variables between two instances
121
+     */
122
+    public function syncInstanceFrom($from)
123
+    {
124
+        foreach ($this->tableDefinition as $colName => $definition) {
125
+            $this->tableDefinition[$colName]['value'] = $from->tableDefinition[$colName]['value'];
126
+        }
127
+    }
128
+
129
+    private function filterInputColumns($input, $whitelist)
130
+    {
131
+        $filteredInput = $input;
132
+        foreach ($input as $colName => $value) {
133
+            if (!in_array($colName, $whitelist)) {
134
+                unset($filteredInput[$colName]);
135
+            }
136
+        }
137
+        return $filteredInput;
138
+    }
139
+
140
+    private function validateExcessKeys($input)
141
+    {
142
+        $errors = [];
143
+        foreach ($input as $colName => $value) {
144
+            if (!array_key_exists($colName, $this->tableDefinition)) {
145
+                $errors[$colName] = "Unknown input field";
146
+                continue;
147
+            }
148
+        }
149
+        return $errors;
150
+    }
151
+
152
+    private function validateImmutableColumns($input)
153
+    {
154
+        $errors = [];
155
+        foreach ($this->tableDefinition as $colName => $definition) {
156
+            $property = $definition['properties'] ?? null;
157
+            if (array_key_exists($colName, $input)
158
+                && $property & ColumnProperty::IMMUTABLE) {
159
+                $errors[$colName] = "Field cannot be changed";
160
+            }
161
+        }
162
+        return $errors;
163
+    }
164
+
165
+    /**
166
+     * Checks whether input values are correct:
167
+     * 1. Checks whether a value passes the validation function for that column
168
+     * 2. Checks whether a value supplied to a relationship column is a valid value
169
+     */
170
+    private function validateInputValues($input)
171
+    {
172
+        $errors = [];
173
+        foreach ($this->tableDefinition as $colName => $definition) {
174
+            // Validation check 1: If validate function is present
175
+            if (array_key_exists($colName, $input) 
176
+                && is_callable($definition['validate'] ?? null)) {
177
+                $inputValue = $input[$colName];
178
+
179
+                // If validation function fails
180
+                [$status, $message] = $definition['validate']($inputValue);
181
+                if (!$status) {
182
+                    $errors[$colName] = $message;
183
+                }	
184
+            }
185
+
186
+            // Validation check 2: If relation column, check whether entity exists
187
+            $properties = $definition['properties'] ?? null;
188
+            if (isset($definition['relation'])
189
+                && ($properties & ColumnProperty::NOT_NULL)) {
190
+                $instance = clone $definition['relation'];
191
+                try {
192
+                    $instance->read($input[$colName] ?? $definition['value'] ?? null);
193
+                } catch (ActiveRecordException $e) {
194
+                    $errors[$colName] = "Entity for this value doesn't exist";
195
+                }
196
+            }
197
+        }
198
+        return $errors;
199
+    }
200
+
201
+    /**
202
+     * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
203
+     * Determines whether there are required columns for which no data is provided
204
+     */
205
+    private function validateMissingKeys($input)
206
+    {
207
+        $errors = [];
208
+
209
+        foreach ($this->tableDefinition as $colName => $colDefinition) {
210
+            $default = $colDefinition['default'] ?? null;
211
+            $properties = $colDefinition['properties'] ?? null;
212
+            $value = $colDefinition['value'];
213
+
214
+            // If nullable and default not set => null
215
+            // If nullable and default null => default (null)
216
+            // If nullable and default set => default (value)
217
+
218
+            // if not nullable and default not set => error
219
+            // if not nullable and default null => error
220
+            // if not nullable and default st => default (value)
221
+            // => if not nullable and default null and value not set (or null) => error message in this method
222
+            if ($properties & ColumnProperty::NOT_NULL
223
+                && $default === null
224
+                && !($properties & ColumnProperty::AUTO_INCREMENT)
225
+                && (!array_key_exists($colName, $input) 
226
+                    || $input[$colName] === null 
227
+                    || (is_string($input[$colName]) && $input[$colName] === '') )
228
+                && ($value === null
229
+                    || (is_string($value) && $value === ''))) {
230
+                $errors[$colName] = sprintf("The required field \"%s\" is missing", $colName);
231
+            } 
232
+        }
233
+
234
+        return $errors;
235
+    }
236
+
237
+    /**
238
+     * Copies the values for entries in the input with matching variable names in the record definition
239
+     * @param Array $input The input data to be loaded into $this record
240
+     */
241
+    private function loadData($input)
242
+    {
243
+        foreach ($this->tableDefinition as $colName => $definition) {
244
+            if (array_key_exists($colName, $input)) {
245
+                $definition['value'] = $input[$colName];
246
+            }
247
+        }
248
+    }
249
+
250
+    /**
251
+     * @param Array $input Associative array of input values
252
+     * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
253
+     * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
254
+     * 					of the modified data.
255
+     */
256
+    public function apiCreate(Array $input, Array $createWhitelist, Array $readWhitelist)
257
+    {
258
+        // Clone $this to new instance (for restoring if validation goes wrong)
259
+        $transaction = $this->newInstance();
260
+        $errors = [];
261
+
262
+        // Filter out all non-whitelisted input values
263
+        $input = $this->filterInputColumns($input, $createWhitelist);
264
+
265
+        // Validate excess keys
266
+        $errors += $transaction->validateExcessKeys($input);
267
+
268
+        // Validate input values (using validation function)
269
+        $errors += $transaction->validateInputValues($input);
270
+
271
+        // "Copy" data into transaction
272
+        $transaction->loadData($input);
273
+
274
+        // Run create hooks
275
+        foreach ($transaction->createHooks as $colName => $fn) {
276
+            $fn();
277
+        }
278
+
279
+        // Validate missing keys
280
+        $errors += $transaction->validateMissingKeys($input);
281
+
282
+        // If no errors, commit the pending data
283
+        if (empty($errors)) {
284
+            $this->syncInstanceFrom($transaction);
285
+
286
+            // Insert default values for not-null fields
287
+            $this->insertDefaults();
288
+
289
+            try {
290
+                (new Query($this->getPdo(), $this->getTableName()))
291
+                    ->insert($this->getActiveRecordColumns())
292
+                    ->execute();
293
+
294
+                $this->setId(intval($this->getPdo()->lastInsertId()));
295
+            } catch (\PDOException $e) {
296
+                // @TODO: Potentially filter and store mysql messages (where possible) in error messages
297
+                throw new ActiveRecordException($e->getMessage(), 0, $e);
298
+            }
299
+
300
+            return [null, $this->toArray($readWhitelist)];
301
+        } else {
302
+            return [$errors, null];
303
+        }
304
+    }
305
+
306
+    /**
307
+     * @param Array $input Associative array of input values
308
+     * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
309
+     * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
310
+     * 					of the modified data.
311
+     */
312
+    public function apiUpdate(Array $input, Array $updateWhitelist, Array $readWhitelist)
313
+    {
314
+        $transaction = $this->newInstance();
315
+        $transaction->syncInstanceFrom($this);
316
+        $errors = [];
317
+
318
+        // Filter out all non-whitelisted input values
319
+        $input = $this->filterInputColumns($input, $updateWhitelist);
320
+
321
+        // Check for excess keys
322
+        $errors += $transaction->validateExcessKeys($input);
323
+
324
+        // Check for immutable keys
325
+        $errors += $transaction->validateImmutableColumns($input);
326
+
327
+        // Validate input values (using validation function)
328
+        $errors += $transaction->validateInputValues($input);
329
+
330
+        // "Copy" data into transaction
331
+        $transaction->loadData($input);
332
+
333
+        // Run create hooks
334
+        foreach ($transaction->updateHooks as $colName => $fn) {
335
+            $fn();
336
+        }
337
+
338
+        // Validate missing keys
339
+        $errors += $transaction->validateMissingKeys($input);
340
+
341
+        // Update database
342
+        if (empty($errors)) {
343
+            $this->syncInstanceFrom($transaction);
344
+
345
+            try {
346
+                (new Query($this->getPdo(), $this->getTableName()))
347
+                    ->update($this->getActiveRecordColumns())
348
+                    ->where(Query::Equal('id', $this->getId()))
349
+                    ->execute();
350
+            } catch (\PDOException $e) {
351
+                throw new ActiveRecordException($e->getMessage(), 0, $e);
352
+            }
353
+
354
+            return [null, $this->toArray($readWhitelist)];
355
+        } else {
356
+            return [$errors, null];
357
+        }
358
+    }
359
+
360
+    /**
361
+     * Returns this active record after reading the attributes from the entry with the given identifier.
362
+     *
363
+     * @param mixed $id
364
+     * @return $this
365
+     * @throws ActiveRecordException on failure.
366
+     */
367
+    abstract public function read($id);
368
+
369
+    /**
370
+     * Returns the PDO.
371
+     *
372
+     * @return \PDO the PDO.
373
+     */
374
+    abstract public function getPdo();
375
+
376
+    /**
377
+     * Set the ID.
378
+     *
379
+     * @param int $id
380
+     * @return $this
381
+     */
382
+    abstract protected function setId($id);
383
+
384
+    /**
385
+     * Returns the ID.
386
+     *
387
+     * @return null|int The ID.
388
+     */
389
+    abstract protected function getId();
390
+
391
+    /**
392
+     * Returns the active record table.
393
+     *
394
+     * @return string the active record table name.
395
+     */
396
+    abstract public function getTableName();
397
+
398
+    /**
399
+     * Returns the name -> variable mapping for the table definition.
400
+     * @return Array The mapping
401
+     */
402
+    abstract protected function getActiveRecordColumns();
403 403
 }
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/ActiveRecordQuery.php 1 patch
Indentation   +266 added lines, -266 removed lines patch added patch discarded remove patch
@@ -20,276 +20,276 @@
 block discarded – undo
20 20
  */
21 21
 class ActiveRecordQuery implements \IteratorAggregate
22 22
 {
23
-	private $instance;
23
+    private $instance;
24 24
 
25
-	private $query;
25
+    private $query;
26 26
 
27
-	private $type;
27
+    private $type;
28 28
 
29
-	private $clauses = [];
29
+    private $clauses = [];
30 30
 
31
-	private $maxresultCount;
31
+    private $maxresultCount;
32 32
 
33
-	private $results;
33
+    private $results;
34 34
 	
35
-	private $whereExpression = null;
36
-
37
-	private $limit;
38
-
39
-	private $offset;
40
-
41
-	private $orderBy;
42
-
43
-	private $orderDirection;
44
-
45
-	/**
46
-	 * Constructs a new Active Record Query
47
-	 */
48
-	public function __construct(AbstractActiveRecord $instance, Array $additionalWhereClauses)
49
-	{
50
-		$this->instance = $instance;
51
-		$this->query = new Query($instance->getPdo(), $instance->getTableName());
52
-		$this->type = $instance;
53
-		$this->clauses = $additionalWhereClauses;
54
-		$this->maxResultCount = null;
55
-		$this->results = null;
56
-		$this->limit = null;
57
-		$this->offset = null;
58
-	}
59
-
60
-	private function getWhereCondition()
61
-	{
62
-		$clauses = $this->clauses;
63
-
64
-		// Optionally add user concatenated where expression
65
-		if ($this->whereExpression !== null) {
66
-			$clauses[] = $this->whereExpression;
67
-		}
68
-
69
-		// Construct where clause
70
-		if (count($clauses) > 0) {
71
-			return Query::AndArray($clauses);
72
-		}
73
-		return null;
74
-	}
75
-
76
-	/**
77
-	 * Executes the query
78
-	 */
79
-	public function execute()
80
-	{
81
-		$whereCondition = $this->getWhereCondition();
82
-		if ($whereCondition !== null) {
83
-			$this->query->where($whereCondition);
84
-		}
85
-
86
-		$this->query->select();
87
-
88
-		$this->results = $this->query->execute();
89
-
90
-		return $this;
91
-	}
92
-
93
-	/**
94
-	 * Returns an iterator for the result set
95
-	 * @return ArrayIterator
96
-	 */
97
-	public function getIterator()
98
-	{
99
-		return new \ArrayIterator($this->fetchAll());
100
-	}
101
-
102
-	/**
103
-	 * returns the result set of ActiveRecord instances for this query
104
-	 * @return Array
105
-	 */
106
-	public function fetchAll()
107
-	{
108
-		try {
109
-			if ($this->results === null) {
110
-				$this->execute();	
111
-			}
112
-
113
-			$entries = $this->results->fetchAll();
114
-			if ($entries === false) {
115
-				return [];
116
-			}
117
-
118
-			$typedResults = [];
119
-			foreach ($entries as $entry) {
120
-				$typedEntry = $this->type->newInstance();
121
-				$typedEntry->fill($entry);
122
-				$typedResults[] = $typedEntry;
123
-			}
124
-
125
-			return $typedResults;
126
-		} catch (\PDOException $e) {
127
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
128
-		}
129
-	}
130
-
131
-	public function fetchAllAsArray($readWhitelist)
132
-	{
133
-		$data = $this->fetchAll();
134
-		$output = [];
135
-		foreach ($data as $entry) {
136
-			$output[] = $entry->toArray($readWhitelist);
137
-		}
138
-		return $output;
139
-	}
140
-
141
-	/**
142
-	 * Fetch one record from the database
143
-	 * @return AbstractActiveRecord 
144
-	 */
145
-	public function fetch()
146
-	{
147
-		try {
148
-			if ($this->results === null) {
149
-				$this->execute();
150
-			}
151
-
152
-			$typedResult = $this->type->newInstance();
153
-
154
-			$entry = $this->results->fetch();
155
-			if ($entry === false) {
156
-				return null;
157
-			}
158
-
159
-			$typedResult->fill($entry);
160
-
161
-			return $typedResult;
162
-		} catch (\PDOException $e) {
163
-			throw new ActiveRecordException($e->getMessage(), 0, $e);
164
-		}
165
-	}
166
-
167
-	/**
168
-	 * Fetch one record from the database and format it as an associative array, 
169
-	 * 	 filtered by the entries in $readwhitelist
170
-	 * @param Array $readWhitelist Array of whitelisted database column keys to be returned in the result
171
-	 * @return Array|Null
172
-	 */
173
-	public function fetchAsArray($readWhitelist)
174
-	{
175
-		$res = $this->fetch();
176
-		if ($res !== null) {
177
-			return $res->toArray($readWhitelist);
178
-		}
179
-		return null;
180
-	}
181
-
182
-	public function countMaxResults()
183
-	{
184
-		if ($this->maxResultCount === null) {
185
-			$query = new Query($this->instance->getPdo(), $this->instance->getTableName());
186
-			$query->select(['count(*) as count'], false);
187
-
188
-			$whereCondition = $this->getWhereCondition();
189
-			if ($whereCondition !== null) {
190
-				$query->where($whereCondition);
191
-			}
192
-
193
-			$this->maxResultCount = $query->execute()->fetch()['count'];
194
-		}
195
-		return $this->maxResultCount;
196
-	}
197
-
198
-	public function getNumberOfPages()
199
-	{
200
-		if ($this->limit === null) {
201
-			return 1;
202
-		}
203
-
204
-		if ($this->limit === 0) {
205
-			return 0;
206
-		}
207
-
208
-		$resultCount = $this->countMaxResults();
209
-		if ($resultCount % $this->limit > 0) {
210
-			return (int) floor($resultCount / $this->limit) + 1;
211
-		}
212
-		return (int) floor($resultCount / $this->limit);
213
-	}
214
-
215
-	public function getCurrentPage()
216
-	{
217
-		if ($this->offset === null || $this->offset === 0) {
218
-			return 1;
219
-		}
220
-
221
-		if ($this->limit === null || $this->limit === 0) {
222
-			return 1;
223
-		}
224
-
225
-		return (int) floor($this->offset / $this->limit);
226
-	}
227
-
228
-	/**
229
-	 * Set the where condition
230
-	 *
231
-	 * @param QueryExpression $expression the query expression
232
-	 * @return $this
233
-	 * @see https://en.wikipedia.org/wiki/SQL#Operators
234
-	 * @see https://en.wikipedia.org/wiki/Where_(SQL)
235
-	 */
236
-	public function where(QueryExpression $expression)
237
-	{
238
-		$this->whereExpression = $expression;
239
-		return $this;
240
-	}
241
-
242
-	/**
243
-	 * Set an additional group by.
244
-	 *
245
-	 * @param string $column
246
-	 * @return $this
247
-	 * @see https://en.wikipedia.org/wiki/SQL#Queries
248
-	 */
249
-	public function groupBy($column)
250
-	{
251
-		$this->query->groupBy($column);
252
-		return $this;
253
-	}
254
-
255
-	/**
256
-	 * Set an additional order condition.
257
-	 *
258
-	 * @param string $column
259
-	 * @param string|null $order
260
-	 * @return $this
261
-	 * @see https://en.wikipedia.org/wiki/SQL#Queries
262
-	 * @see https://en.wikipedia.org/wiki/Order_by
263
-	 */
264
-	public function orderBy($column, $order = null)
265
-	{
266
-		$this->query->orderBy($column, $order);	
267
-		return $this;
268
-	}
269
-
270
-	/**
271
-	 * Set the limit.
272
-	 *
273
-	 * @param mixed $limit
274
-	 * @return $this
275
-	 */
276
-	public function limit($limit)
277
-	{
278
-		$this->limit = $limit;
279
-		$this->query->limit($limit);
280
-		return $this;
281
-	}
282
-
283
-	/**
284
-	 * Set the offset.
285
-	 *
286
-	 * @param mixed $offset
287
- 	 * @return $this
288
-	 */
289
-	public function offset($offset)
290
-	{
291
-		$this->offset = $offset;
292
-		$this->query->offset($offset);
293
-		return $this;
294
-	}
35
+    private $whereExpression = null;
36
+
37
+    private $limit;
38
+
39
+    private $offset;
40
+
41
+    private $orderBy;
42
+
43
+    private $orderDirection;
44
+
45
+    /**
46
+     * Constructs a new Active Record Query
47
+     */
48
+    public function __construct(AbstractActiveRecord $instance, Array $additionalWhereClauses)
49
+    {
50
+        $this->instance = $instance;
51
+        $this->query = new Query($instance->getPdo(), $instance->getTableName());
52
+        $this->type = $instance;
53
+        $this->clauses = $additionalWhereClauses;
54
+        $this->maxResultCount = null;
55
+        $this->results = null;
56
+        $this->limit = null;
57
+        $this->offset = null;
58
+    }
59
+
60
+    private function getWhereCondition()
61
+    {
62
+        $clauses = $this->clauses;
63
+
64
+        // Optionally add user concatenated where expression
65
+        if ($this->whereExpression !== null) {
66
+            $clauses[] = $this->whereExpression;
67
+        }
68
+
69
+        // Construct where clause
70
+        if (count($clauses) > 0) {
71
+            return Query::AndArray($clauses);
72
+        }
73
+        return null;
74
+    }
75
+
76
+    /**
77
+     * Executes the query
78
+     */
79
+    public function execute()
80
+    {
81
+        $whereCondition = $this->getWhereCondition();
82
+        if ($whereCondition !== null) {
83
+            $this->query->where($whereCondition);
84
+        }
85
+
86
+        $this->query->select();
87
+
88
+        $this->results = $this->query->execute();
89
+
90
+        return $this;
91
+    }
92
+
93
+    /**
94
+     * Returns an iterator for the result set
95
+     * @return ArrayIterator
96
+     */
97
+    public function getIterator()
98
+    {
99
+        return new \ArrayIterator($this->fetchAll());
100
+    }
101
+
102
+    /**
103
+     * returns the result set of ActiveRecord instances for this query
104
+     * @return Array
105
+     */
106
+    public function fetchAll()
107
+    {
108
+        try {
109
+            if ($this->results === null) {
110
+                $this->execute();	
111
+            }
112
+
113
+            $entries = $this->results->fetchAll();
114
+            if ($entries === false) {
115
+                return [];
116
+            }
117
+
118
+            $typedResults = [];
119
+            foreach ($entries as $entry) {
120
+                $typedEntry = $this->type->newInstance();
121
+                $typedEntry->fill($entry);
122
+                $typedResults[] = $typedEntry;
123
+            }
124
+
125
+            return $typedResults;
126
+        } catch (\PDOException $e) {
127
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
128
+        }
129
+    }
130
+
131
+    public function fetchAllAsArray($readWhitelist)
132
+    {
133
+        $data = $this->fetchAll();
134
+        $output = [];
135
+        foreach ($data as $entry) {
136
+            $output[] = $entry->toArray($readWhitelist);
137
+        }
138
+        return $output;
139
+    }
140
+
141
+    /**
142
+     * Fetch one record from the database
143
+     * @return AbstractActiveRecord 
144
+     */
145
+    public function fetch()
146
+    {
147
+        try {
148
+            if ($this->results === null) {
149
+                $this->execute();
150
+            }
151
+
152
+            $typedResult = $this->type->newInstance();
153
+
154
+            $entry = $this->results->fetch();
155
+            if ($entry === false) {
156
+                return null;
157
+            }
158
+
159
+            $typedResult->fill($entry);
160
+
161
+            return $typedResult;
162
+        } catch (\PDOException $e) {
163
+            throw new ActiveRecordException($e->getMessage(), 0, $e);
164
+        }
165
+    }
166
+
167
+    /**
168
+     * Fetch one record from the database and format it as an associative array, 
169
+     * 	 filtered by the entries in $readwhitelist
170
+     * @param Array $readWhitelist Array of whitelisted database column keys to be returned in the result
171
+     * @return Array|Null
172
+     */
173
+    public function fetchAsArray($readWhitelist)
174
+    {
175
+        $res = $this->fetch();
176
+        if ($res !== null) {
177
+            return $res->toArray($readWhitelist);
178
+        }
179
+        return null;
180
+    }
181
+
182
+    public function countMaxResults()
183
+    {
184
+        if ($this->maxResultCount === null) {
185
+            $query = new Query($this->instance->getPdo(), $this->instance->getTableName());
186
+            $query->select(['count(*) as count'], false);
187
+
188
+            $whereCondition = $this->getWhereCondition();
189
+            if ($whereCondition !== null) {
190
+                $query->where($whereCondition);
191
+            }
192
+
193
+            $this->maxResultCount = $query->execute()->fetch()['count'];
194
+        }
195
+        return $this->maxResultCount;
196
+    }
197
+
198
+    public function getNumberOfPages()
199
+    {
200
+        if ($this->limit === null) {
201
+            return 1;
202
+        }
203
+
204
+        if ($this->limit === 0) {
205
+            return 0;
206
+        }
207
+
208
+        $resultCount = $this->countMaxResults();
209
+        if ($resultCount % $this->limit > 0) {
210
+            return (int) floor($resultCount / $this->limit) + 1;
211
+        }
212
+        return (int) floor($resultCount / $this->limit);
213
+    }
214
+
215
+    public function getCurrentPage()
216
+    {
217
+        if ($this->offset === null || $this->offset === 0) {
218
+            return 1;
219
+        }
220
+
221
+        if ($this->limit === null || $this->limit === 0) {
222
+            return 1;
223
+        }
224
+
225
+        return (int) floor($this->offset / $this->limit);
226
+    }
227
+
228
+    /**
229
+     * Set the where condition
230
+     *
231
+     * @param QueryExpression $expression the query expression
232
+     * @return $this
233
+     * @see https://en.wikipedia.org/wiki/SQL#Operators
234
+     * @see https://en.wikipedia.org/wiki/Where_(SQL)
235
+     */
236
+    public function where(QueryExpression $expression)
237
+    {
238
+        $this->whereExpression = $expression;
239
+        return $this;
240
+    }
241
+
242
+    /**
243
+     * Set an additional group by.
244
+     *
245
+     * @param string $column
246
+     * @return $this
247
+     * @see https://en.wikipedia.org/wiki/SQL#Queries
248
+     */
249
+    public function groupBy($column)
250
+    {
251
+        $this->query->groupBy($column);
252
+        return $this;
253
+    }
254
+
255
+    /**
256
+     * Set an additional order condition.
257
+     *
258
+     * @param string $column
259
+     * @param string|null $order
260
+     * @return $this
261
+     * @see https://en.wikipedia.org/wiki/SQL#Queries
262
+     * @see https://en.wikipedia.org/wiki/Order_by
263
+     */
264
+    public function orderBy($column, $order = null)
265
+    {
266
+        $this->query->orderBy($column, $order);	
267
+        return $this;
268
+    }
269
+
270
+    /**
271
+     * Set the limit.
272
+     *
273
+     * @param mixed $limit
274
+     * @return $this
275
+     */
276
+    public function limit($limit)
277
+    {
278
+        $this->limit = $limit;
279
+        $this->query->limit($limit);
280
+        return $this;
281
+    }
282
+
283
+    /**
284
+     * Set the offset.
285
+     *
286
+     * @param mixed $offset
287
+     * @return $this
288
+     */
289
+    public function offset($offset)
290
+    {
291
+        $this->offset = $offset;
292
+        $this->query->offset($offset);
293
+        return $this;
294
+    }
295 295
 }
Please login to merge, or discard this patch.