Completed
Push — v2 ( a375df...98ab20 )
by Berend
04:42
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   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -18,169 +18,169 @@
 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 buildConstraintOnDeleteCascade($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 buildConstraintOnDeleteCascade($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
-	}
38
+        return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
39
+    }
40 40
  
41
-	public static function buildConstraintOnDeleteSetNull($parentTable, $parentColumn, $childTable, $childColumn)
42
-	{
43
-		$template = <<<SQL
41
+    public static function buildConstraintOnDeleteSetNull($parentTable, $parentColumn, $childTable, $childColumn)
42
+    {
43
+        $template = <<<SQL
44 44
 ALTER TABLE `%s`
45 45
 ADD CONSTRAINT 
46 46
 FOREIGN KEY (`%s`) 
47 47
 REFERENCES `%s` (`%s`)
48 48
 ON DELETE SET NULL
49 49
 SQL;
50
-  		return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
51
-	}
52
-
53
-	/**
54
-	 * Returns the type string as it should appear in the mysql create table statement for the given column
55
-	 * @return string The type string
56
-	 */
57
-	public static function getDatabaseTypeString($colName, $type, $length)
58
-	{
59
-		switch (strtoupper($type)) {
60
-			case '':
61
-				throw new ActiveRecordException(sprintf("Column %s has invalid type \"NULL\"", $colName));
50
+            return sprintf($template, $childTable, $childColumn, $parentTable, $parentColumn);
51
+    }
52
+
53
+    /**
54
+     * Returns the type string as it should appear in the mysql create table statement for the given column
55
+     * @return string The type string
56
+     */
57
+    public static function getDatabaseTypeString($colName, $type, $length)
58
+    {
59
+        switch (strtoupper($type)) {
60
+            case '':
61
+                throw new ActiveRecordException(sprintf("Column %s has invalid type \"NULL\"", $colName));
62 62
 			
63
-			case 'BOOL';
64
-			case 'BOOLEAN':
65
-			case 'DATETIME':
66
-			case 'DATE':
67
-			case 'TIME':
68
-			case 'TEXT':
69
-			case 'INT UNSIGNED':
70
-				return $type;
71
-
72
-			case 'VARCHAR':
73
-				if ($length === null) {
74
-					throw new ActiveRecordException(sprintf("field type %s requires specified column field \"LENGTH\"", $colName));
75
-				} else {
76
-					return sprintf('%s(%d)', $type, $length);	
77
-				}
78
-
79
-			case 'INT':
80
-			case 'TINYINT':
81
-			case 'BIGINT':
82
-			default: 	
83
-				// Implicitly assuming that non-specified cases are correct without a length parameter
84
-				if ($length === null) {
85
-					return $type;
86
-				} else {
87
-					return sprintf('%s(%d)', $type, $length);	
88
-				}
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * Builds the part of a MySQL create table statement that corresponds to the supplied column
94
-	 * @param string $colName 	Name of the database column
95
-	 * @param string $type 		The type of the string
96
-	 * @param int $properties 	The set of Column properties that apply to this column (See ColumnProperty for options)
97
-	 * @return string
98
-	 */
99
-	public static function buildCreateTableColumnEntry($colName, $type, $length, $properties, $default)
100
-	{
101
-		$stmnt = sprintf('`%s` %s ', $colName, self::getDatabaseTypeString($colName, $type, $length));
102
-		if ($properties & ColumnProperty::NOT_NULL) {
103
-			$stmnt .= 'NOT NULL ';
104
-		} else {
105
-			$stmnt .= 'NULL ';
106
-		}
107
-
108
-		if ($default !== NULL) {
109
-			$stmnt .= 'DEFAULT ' . var_export($default, true) . ' ';
110
-		}
111
-
112
-		if ($properties & ColumnProperty::AUTO_INCREMENT) {
113
-			$stmnt .= 'AUTO_INCREMENT ';
114
-		}
115
-
116
-		if ($properties & ColumnProperty::UNIQUE) {
117
-			$stmnt .= 'UNIQUE ';
118
-		}
119
-
120
-		if ($properties & ColumnProperty::PRIMARY_KEY) {
121
-			$stmnt .= 'PRIMARY KEY ';
122
-		}
123
-
124
-		return $stmnt;
125
-	}
126
-
127
-	/**
128
-	 * Sorts the column statement components in the order such that the id appears first, 
129
-	 * 		followed by all other columns in alphabetical ascending order
130
-	 * @param   Array $colStatements Array of column statements
131
-	 * @return  Array
132
-	 */
133
-	private static function sortColumnStatements($colStatements)
134
-	{
135
-		// Find ID statement and put it first
136
-		$sortedStatements = [];
137
-
138
-		$sortedStatements[] = $colStatements[AbstractActiveRecord::COLUMN_NAME_ID];
139
-		unset($colStatements[AbstractActiveRecord::COLUMN_NAME_ID]);
140
-
141
-		// Sort remaining columns in alphabetical order
142
-		$columns = array_keys($colStatements);
143
-		sort($columns);
144
-		foreach ($columns as $colName) {
145
-			$sortedStatements[] = $colStatements[$colName];
146
-		}
147
-
148
-		return $sortedStatements;
149
-	}
150
-
151
-	/**
152
-	 * Builds the MySQL Create Table statement for the internal table definition
153
-	 * @return string
154
-	 */
155
-	public static function buildCreateTableSQL($tableName, $tableDefinition)
156
-	{
157
-		$columnStatements = [];
158
-		foreach ($tableDefinition as $colName => $definition) {
159
-			// Destructure column definition
160
-			$type    = $definition['type'] ?? null;
161
-			$default = $definition['default'] ?? null;
162
-			$length  = $definition['length'] ?? null;
163
-			$properties = $definition['properties'] ?? null;
164
-
165
-			if (isset($definition['relation']) && $type !== null) {
166
-				$msg = sprintf("Column \"%s\" on table \"%s\": ", $colName, $tableName);
167
-				$msg .= "Relationship columns have an automatically inferred type, so type should be omitted";
168
-				throw new ActiveRecordException($msg);
169
-			} else if (isset($definition['relation'])) {
170
-				$type = AbstractActiveRecord::COLUMN_TYPE_ID;
171
-			}
172
-
173
-			$columnStatements[$colName] = self::buildCreateTableColumnEntry($colName, $type, $length, $properties, $default);
174
-		}
175
-
176
-		// Sort table (first column is id, the remaining are alphabetically sorted)
177
-		$columnStatements = self::sortColumnStatements($columnStatements);
178
-
179
-		$sql = sprintf("CREATE TABLE %s (\n%s\n) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 
180
-			$tableName, 
181
-			implode(",\n", $columnStatements));
182
-
183
-		return $sql;
184
-	}
63
+            case 'BOOL';
64
+            case 'BOOLEAN':
65
+            case 'DATETIME':
66
+            case 'DATE':
67
+            case 'TIME':
68
+            case 'TEXT':
69
+            case 'INT UNSIGNED':
70
+                return $type;
71
+
72
+            case 'VARCHAR':
73
+                if ($length === null) {
74
+                    throw new ActiveRecordException(sprintf("field type %s requires specified column field \"LENGTH\"", $colName));
75
+                } else {
76
+                    return sprintf('%s(%d)', $type, $length);	
77
+                }
78
+
79
+            case 'INT':
80
+            case 'TINYINT':
81
+            case 'BIGINT':
82
+            default: 	
83
+                // Implicitly assuming that non-specified cases are correct without a length parameter
84
+                if ($length === null) {
85
+                    return $type;
86
+                } else {
87
+                    return sprintf('%s(%d)', $type, $length);	
88
+                }
89
+        }
90
+    }
91
+
92
+    /**
93
+     * Builds the part of a MySQL create table statement that corresponds to the supplied column
94
+     * @param string $colName 	Name of the database column
95
+     * @param string $type 		The type of the string
96
+     * @param int $properties 	The set of Column properties that apply to this column (See ColumnProperty for options)
97
+     * @return string
98
+     */
99
+    public static function buildCreateTableColumnEntry($colName, $type, $length, $properties, $default)
100
+    {
101
+        $stmnt = sprintf('`%s` %s ', $colName, self::getDatabaseTypeString($colName, $type, $length));
102
+        if ($properties & ColumnProperty::NOT_NULL) {
103
+            $stmnt .= 'NOT NULL ';
104
+        } else {
105
+            $stmnt .= 'NULL ';
106
+        }
107
+
108
+        if ($default !== NULL) {
109
+            $stmnt .= 'DEFAULT ' . var_export($default, true) . ' ';
110
+        }
111
+
112
+        if ($properties & ColumnProperty::AUTO_INCREMENT) {
113
+            $stmnt .= 'AUTO_INCREMENT ';
114
+        }
115
+
116
+        if ($properties & ColumnProperty::UNIQUE) {
117
+            $stmnt .= 'UNIQUE ';
118
+        }
119
+
120
+        if ($properties & ColumnProperty::PRIMARY_KEY) {
121
+            $stmnt .= 'PRIMARY KEY ';
122
+        }
123
+
124
+        return $stmnt;
125
+    }
126
+
127
+    /**
128
+     * Sorts the column statement components in the order such that the id appears first, 
129
+     * 		followed by all other columns in alphabetical ascending order
130
+     * @param   Array $colStatements Array of column statements
131
+     * @return  Array
132
+     */
133
+    private static function sortColumnStatements($colStatements)
134
+    {
135
+        // Find ID statement and put it first
136
+        $sortedStatements = [];
137
+
138
+        $sortedStatements[] = $colStatements[AbstractActiveRecord::COLUMN_NAME_ID];
139
+        unset($colStatements[AbstractActiveRecord::COLUMN_NAME_ID]);
140
+
141
+        // Sort remaining columns in alphabetical order
142
+        $columns = array_keys($colStatements);
143
+        sort($columns);
144
+        foreach ($columns as $colName) {
145
+            $sortedStatements[] = $colStatements[$colName];
146
+        }
147
+
148
+        return $sortedStatements;
149
+    }
150
+
151
+    /**
152
+     * Builds the MySQL Create Table statement for the internal table definition
153
+     * @return string
154
+     */
155
+    public static function buildCreateTableSQL($tableName, $tableDefinition)
156
+    {
157
+        $columnStatements = [];
158
+        foreach ($tableDefinition as $colName => $definition) {
159
+            // Destructure column definition
160
+            $type    = $definition['type'] ?? null;
161
+            $default = $definition['default'] ?? null;
162
+            $length  = $definition['length'] ?? null;
163
+            $properties = $definition['properties'] ?? null;
164
+
165
+            if (isset($definition['relation']) && $type !== null) {
166
+                $msg = sprintf("Column \"%s\" on table \"%s\": ", $colName, $tableName);
167
+                $msg .= "Relationship columns have an automatically inferred type, so type should be omitted";
168
+                throw new ActiveRecordException($msg);
169
+            } else if (isset($definition['relation'])) {
170
+                $type = AbstractActiveRecord::COLUMN_TYPE_ID;
171
+            }
172
+
173
+            $columnStatements[$colName] = self::buildCreateTableColumnEntry($colName, $type, $length, $properties, $default);
174
+        }
175
+
176
+        // Sort table (first column is id, the remaining are alphabetically sorted)
177
+        $columnStatements = self::sortColumnStatements($columnStatements);
178
+
179
+        $sql = sprintf("CREATE TABLE %s (\n%s\n) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 
180
+            $tableName, 
181
+            implode(",\n", $columnStatements));
182
+
183
+        return $sql;
184
+    }
185 185
 
186 186
 }
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/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.
src/Traits/Datefields.php 1 patch
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -10,111 +10,111 @@
 block discarded – undo
10 10
 
11 11
 trait Datefields
12 12
 {
13
-	/** @var string The timestamp representing the moment this record was created */
14
-	protected $created;
15
-
16
-	/** @var string The timestamp representing the moment this record was last updated */
17
-	protected $lastModified;
18
-
19
-	/**
20
-	 * this method is required to be called in the constructor for each class that uses this trait. 
21
-	 * It adds the datefields to the table definition and registers the callback hooks
22
-	 */
23
-	protected function initDatefields()
24
-	{
25
-		$this->extendTableDefinition(TRAIT_DATEFIELDS_CREATED, [
26
-			'value' => &$this->created,
27
-			'validate' => null,
28
-			'type' => 'DATETIME',
29
-			'properties' => ColumnProperty::NOT_NULL | ColumnProperty::IMMUTABLE
30
-		]);
31
-
32
-		$this->extendTableDefinition(TRAIT_DATEFIELDS_LAST_MODIFIED, [
33
-			'value' => &$this->lastModified,
34
-			'validate' => null,
35
-			'type' => 'DATETIME',
36
-			'properties' => ColumnProperty::NOT_NULL | ColumnProperty::IMMUTABLE
37
-		]);
13
+    /** @var string The timestamp representing the moment this record was created */
14
+    protected $created;
15
+
16
+    /** @var string The timestamp representing the moment this record was last updated */
17
+    protected $lastModified;
18
+
19
+    /**
20
+     * this method is required to be called in the constructor for each class that uses this trait. 
21
+     * It adds the datefields to the table definition and registers the callback hooks
22
+     */
23
+    protected function initDatefields()
24
+    {
25
+        $this->extendTableDefinition(TRAIT_DATEFIELDS_CREATED, [
26
+            'value' => &$this->created,
27
+            'validate' => null,
28
+            'type' => 'DATETIME',
29
+            'properties' => ColumnProperty::NOT_NULL | ColumnProperty::IMMUTABLE
30
+        ]);
31
+
32
+        $this->extendTableDefinition(TRAIT_DATEFIELDS_LAST_MODIFIED, [
33
+            'value' => &$this->lastModified,
34
+            'validate' => null,
35
+            'type' => 'DATETIME',
36
+            'properties' => ColumnProperty::NOT_NULL | ColumnProperty::IMMUTABLE
37
+        ]);
38 38
 		
39
-		$this->registerCreateHook(TRAIT_DATEFIELDS_CREATED, 'DatefieldsLastModifiedCreateHook');
40
-		$this->registerCreateHook(TRAIT_DATEFIELDS_LAST_MODIFIED, 'DatefieldsCreatedCreateHook');
41
-		$this->registerUpdateHook(TRAIT_DATEFIELDS_LAST_MODIFIED, 'DatefieldsUpdateHook');
42
-
43
-		$this->created = null;
44
-		$this->lastModified = null;
45
-	}
46
-
47
-	/**
48
-	 * The hook that gets called to set the last modified timestamp whenever a new record is created
49
-	 */
50
-	protected function DatefieldsLastModifiedCreateHook()
51
-	{
52
-		$this->lastModified = (new \DateTime('now'))->format('Y-m-d H:i:s');
53
-	}
54
-
55
-	/**
56
-	 * The hook that gets called to set the created timestamp whenever a new record is created
57
-	 */
58
-	protected function DatefieldsCreatedCreateHook()
59
-	{
60
-		$this->created = (new \DateTime('now'))->format('Y-m-d H:i:s');
61
-	}
62
-
63
-	/**
64
-	 * The hook that gets called to set the timestamp whenever a record gets updated
65
-	 */
66
-	protected function DatefieldsUpdateHook()
67
-	{
68
-		$this->lastModified = (new \DateTime('now'))->format('Y-m-d H:i:s');
69
-	}
70
-
71
-	/**
72
-	 * Returns the timestamp of last update for this record
73
-	 * @return \DateTime
74
-	 */
75
-	public function getLastModifiedDate()
76
-	{
77
-		return new \DateTime($this->lastModified);
78
-	}
79
-
80
-	/**
81
-	 * Returns the timestamp of when this record was created
82
-	 * @return \DateTime
83
-	 */
84
-	public function getCreationDate()
85
-	{
86
-		return new \DateTime($this->created);
87
-	}
88
-
89
-	/**
90
-	 * @return void
91
-	 */
92
-	abstract protected function extendTableDefinition($columnName, $definition);
39
+        $this->registerCreateHook(TRAIT_DATEFIELDS_CREATED, 'DatefieldsLastModifiedCreateHook');
40
+        $this->registerCreateHook(TRAIT_DATEFIELDS_LAST_MODIFIED, 'DatefieldsCreatedCreateHook');
41
+        $this->registerUpdateHook(TRAIT_DATEFIELDS_LAST_MODIFIED, 'DatefieldsUpdateHook');
42
+
43
+        $this->created = null;
44
+        $this->lastModified = null;
45
+    }
46
+
47
+    /**
48
+     * The hook that gets called to set the last modified timestamp whenever a new record is created
49
+     */
50
+    protected function DatefieldsLastModifiedCreateHook()
51
+    {
52
+        $this->lastModified = (new \DateTime('now'))->format('Y-m-d H:i:s');
53
+    }
54
+
55
+    /**
56
+     * The hook that gets called to set the created timestamp whenever a new record is created
57
+     */
58
+    protected function DatefieldsCreatedCreateHook()
59
+    {
60
+        $this->created = (new \DateTime('now'))->format('Y-m-d H:i:s');
61
+    }
62
+
63
+    /**
64
+     * The hook that gets called to set the timestamp whenever a record gets updated
65
+     */
66
+    protected function DatefieldsUpdateHook()
67
+    {
68
+        $this->lastModified = (new \DateTime('now'))->format('Y-m-d H:i:s');
69
+    }
70
+
71
+    /**
72
+     * Returns the timestamp of last update for this record
73
+     * @return \DateTime
74
+     */
75
+    public function getLastModifiedDate()
76
+    {
77
+        return new \DateTime($this->lastModified);
78
+    }
79
+
80
+    /**
81
+     * Returns the timestamp of when this record was created
82
+     * @return \DateTime
83
+     */
84
+    public function getCreationDate()
85
+    {
86
+        return new \DateTime($this->created);
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
-	
121 120
\ No newline at end of file
121
+    
122 122
\ 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::buildConstraintOnDeleteCascade($leftParentTable, 'id', $childTable, $this->_leftColumnName);
77
-		$rightConstraint = SchemaBuilder::buildConstraintOnDeleteCascade($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::buildConstraintOnDeleteCascade($leftParentTable, 'id', $childTable, $this->_leftColumnName);
77
+        $rightConstraint = SchemaBuilder::buildConstraintOnDeleteCascade($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.