Passed
Push — 1.0.0-dev ( 83bedf...ceb5d8 )
by nguereza
02:34
created
core/classes/Config.php 2 patches
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -1,190 +1,190 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Config{
27
+    class Config{
28 28
 		
29
-		/**
30
-		 * The list of loaded configuration
31
-		 * @var array
32
-		 */
33
-		private static $config = array();
29
+        /**
30
+         * The list of loaded configuration
31
+         * @var array
32
+         */
33
+        private static $config = array();
34 34
 
35
-		/**
36
-		 * The logger instance
37
-		 * @var Log
38
-		 */
39
-		private static $logger;
35
+        /**
36
+         * The logger instance
37
+         * @var Log
38
+         */
39
+        private static $logger;
40 40
 
41
-		/**
42
-		 * The signleton of the logger
43
-		 * @return Object the Log instance
44
-		 */
45
-		private static function getLogger(){
46
-			if(self::$logger == null){
47
-				$logger = array();
48
-				$logger[0] =& class_loader('Log', 'classes');
49
-				$logger[0]->setLogger('Library::Config');
50
-				self::$logger = $logger[0];
51
-			}
52
-			return self::$logger;			
53
-		}
41
+        /**
42
+         * The signleton of the logger
43
+         * @return Object the Log instance
44
+         */
45
+        private static function getLogger(){
46
+            if(self::$logger == null){
47
+                $logger = array();
48
+                $logger[0] =& class_loader('Log', 'classes');
49
+                $logger[0]->setLogger('Library::Config');
50
+                self::$logger = $logger[0];
51
+            }
52
+            return self::$logger;			
53
+        }
54 54
 
55
-		/**
56
-		 * Set the log instance for future use
57
-		 * @param Log $logger the log object
58
-		 * @return Log the log instance
59
-		 */
60
-		public static function setLogger($logger){
61
-			self::$logger = $logger;
62
-			return self::$logger;
63
-		}
55
+        /**
56
+         * Set the log instance for future use
57
+         * @param Log $logger the log object
58
+         * @return Log the log instance
59
+         */
60
+        public static function setLogger($logger){
61
+            self::$logger = $logger;
62
+            return self::$logger;
63
+        }
64 64
 
65
-		/**
66
-		 * Initialize the configuration by loading all the configuration from config file
67
-		 */
68
-		public static function init(){
69
-			$logger = static::getLogger();
70
-			$logger->debug('Initialization of the configuration');
71
-			self::$config = & load_configurations();
72
-			self::setBaseUrlUsingServerVar();
73
-			if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
74
-				$logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75
-			}
76
-			$logger->info('Configuration initialized successfully');
77
-			$logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
78
-		}
65
+        /**
66
+         * Initialize the configuration by loading all the configuration from config file
67
+         */
68
+        public static function init(){
69
+            $logger = static::getLogger();
70
+            $logger->debug('Initialization of the configuration');
71
+            self::$config = & load_configurations();
72
+            self::setBaseUrlUsingServerVar();
73
+            if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
74
+                $logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75
+            }
76
+            $logger->info('Configuration initialized successfully');
77
+            $logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
78
+        }
79 79
 
80
-		/**
81
-		 * Get the configuration item value
82
-		 * @param  string $item    the configuration item name to get
83
-		 * @param  mixed $default the default value to use if can not find the config item in the list
84
-		 * @return mixed          the config value if exist or the default value
85
-		 */
86
-		public static function get($item, $default = null){
87
-			$logger = static::getLogger();
88
-			if(array_key_exists($item, self::$config)){
89
-				return self::$config[$item];
90
-			}
91
-			$logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
92
-			return $default;
93
-		}
80
+        /**
81
+         * Get the configuration item value
82
+         * @param  string $item    the configuration item name to get
83
+         * @param  mixed $default the default value to use if can not find the config item in the list
84
+         * @return mixed          the config value if exist or the default value
85
+         */
86
+        public static function get($item, $default = null){
87
+            $logger = static::getLogger();
88
+            if(array_key_exists($item, self::$config)){
89
+                return self::$config[$item];
90
+            }
91
+            $logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
92
+            return $default;
93
+        }
94 94
 
95
-		/**
96
-		 * Set the configuration item value
97
-		 * @param string $item  the config item name to set
98
-		 * @param mixed $value the config item value
99
-		 */
100
-		public static function set($item, $value){
101
-			self::$config[$item] = $value;
102
-		}
95
+        /**
96
+         * Set the configuration item value
97
+         * @param string $item  the config item name to set
98
+         * @param mixed $value the config item value
99
+         */
100
+        public static function set($item, $value){
101
+            self::$config[$item] = $value;
102
+        }
103 103
 
104
-		/**
105
-		 * Get all the configuration values
106
-		 * @return array the config values
107
-		 */
108
-		public static function getAll(){
109
-			return self::$config;
110
-		}
104
+        /**
105
+         * Get all the configuration values
106
+         * @return array the config values
107
+         */
108
+        public static function getAll(){
109
+            return self::$config;
110
+        }
111 111
 
112
-		/**
113
-		 * Set the configuration values bu merged with the existing configuration
114
-		 * @param array $config the config values to add in the configuration list
115
-		 */
116
-		public static function setAll(array $config = array()){
117
-			self::$config = array_merge(self::$config, $config);
118
-		}
112
+        /**
113
+         * Set the configuration values bu merged with the existing configuration
114
+         * @param array $config the config values to add in the configuration list
115
+         */
116
+        public static function setAll(array $config = array()){
117
+            self::$config = array_merge(self::$config, $config);
118
+        }
119 119
 
120
-		/**
121
-		 * Delete the configuration item in the list
122
-		 * @param  string $item the config item name to be deleted
123
-		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124
-		 */
125
-		public static function delete($item){
126
-			$logger = static::getLogger();
127
-			if(array_key_exists($item, self::$config)){
128
-				$logger->info('Delete config item ['.$item.']');
129
-				unset(self::$config[$item]);
130
-				return true;
131
-			}
132
-			else{
133
-				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
134
-				return false;
135
-			}
136
-		}
120
+        /**
121
+         * Delete the configuration item in the list
122
+         * @param  string $item the config item name to be deleted
123
+         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124
+         */
125
+        public static function delete($item){
126
+            $logger = static::getLogger();
127
+            if(array_key_exists($item, self::$config)){
128
+                $logger->info('Delete config item ['.$item.']');
129
+                unset(self::$config[$item]);
130
+                return true;
131
+            }
132
+            else{
133
+                $logger->warning('Config item ['.$item.'] to be deleted does not exists');
134
+                return false;
135
+            }
136
+        }
137 137
 
138
-		/**
139
-		 * Load the configuration file. This an alias to Loader::config()
140
-		 * @param  string $config the config name to be loaded
141
-		 */
142
-		public static function load($config){
143
-			Loader::config($config);
144
-		}
138
+        /**
139
+         * Load the configuration file. This an alias to Loader::config()
140
+         * @param  string $config the config name to be loaded
141
+         */
142
+        public static function load($config){
143
+            Loader::config($config);
144
+        }
145 145
 
146
-		/**
147
-		 * Set the configuration for "base_url" if is not set in the configuration
148
-		 */
149
-		private static function setBaseUrlUsingServerVar(){
150
-			$logger = static::getLogger();
151
-			if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
-				if(ENVIRONMENT == 'production'){
153
-					$logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154
-				}
155
-				$baseUrl = null;
156
-				$protocol = 'http';
157
-				if(is_https()){
158
-					$protocol = 'https';
159
-				}
160
-				$protocol .='://';
146
+        /**
147
+         * Set the configuration for "base_url" if is not set in the configuration
148
+         */
149
+        private static function setBaseUrlUsingServerVar(){
150
+            $logger = static::getLogger();
151
+            if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
+                if(ENVIRONMENT == 'production'){
153
+                    $logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154
+                }
155
+                $baseUrl = null;
156
+                $protocol = 'http';
157
+                if(is_https()){
158
+                    $protocol = 'https';
159
+                }
160
+                $protocol .='://';
161 161
 
162
-				if (isset($_SERVER['SERVER_ADDR'])){
163
-					$baseUrl = $_SERVER['SERVER_ADDR'];
164
-					//check if the server is running under IPv6
165
-					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
-						$baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
167
-					}
168
-					$serverPort = 80;
169
-					if (isset($_SERVER['SERVER_PORT'])) {
170
-						$serverPort = $_SERVER['SERVER_PORT'];
171
-					}
172
-					$port = '';
173
-					if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
-						$port = ':'.$serverPort;
175
-					}
176
-					$baseUrl = $protocol . $baseUrl . $port . substr(
177
-																		$_SERVER['SCRIPT_NAME'], 
178
-																		0, 
179
-																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
180
-																	);
181
-				}
182
-				else{
183
-					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
184
-					$baseUrl = 'http://localhost/';
185
-				}
186
-				self::set('base_url', $baseUrl);
187
-			}
188
-			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
189
-		}
190
-	}
162
+                if (isset($_SERVER['SERVER_ADDR'])){
163
+                    $baseUrl = $_SERVER['SERVER_ADDR'];
164
+                    //check if the server is running under IPv6
165
+                    if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
+                        $baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
167
+                    }
168
+                    $serverPort = 80;
169
+                    if (isset($_SERVER['SERVER_PORT'])) {
170
+                        $serverPort = $_SERVER['SERVER_PORT'];
171
+                    }
172
+                    $port = '';
173
+                    if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
+                        $port = ':'.$serverPort;
175
+                    }
176
+                    $baseUrl = $protocol . $baseUrl . $port . substr(
177
+                                                                        $_SERVER['SCRIPT_NAME'], 
178
+                                                                        0, 
179
+                                                                        strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
180
+                                                                    );
181
+                }
182
+                else{
183
+                    $logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
184
+                    $baseUrl = 'http://localhost/';
185
+                }
186
+                self::set('base_url', $baseUrl);
187
+            }
188
+            self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
189
+        }
190
+    }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Config{
27
+	class Config {
28 28
 		
29 29
 		/**
30 30
 		 * The list of loaded configuration
@@ -42,10 +42,10 @@  discard block
 block discarded – undo
42 42
 		 * The signleton of the logger
43 43
 		 * @return Object the Log instance
44 44
 		 */
45
-		private static function getLogger(){
46
-			if(self::$logger == null){
45
+		private static function getLogger() {
46
+			if (self::$logger == null) {
47 47
 				$logger = array();
48
-				$logger[0] =& class_loader('Log', 'classes');
48
+				$logger[0] = & class_loader('Log', 'classes');
49 49
 				$logger[0]->setLogger('Library::Config');
50 50
 				self::$logger = $logger[0];
51 51
 			}
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 		 * @param Log $logger the log object
58 58
 		 * @return Log the log instance
59 59
 		 */
60
-		public static function setLogger($logger){
60
+		public static function setLogger($logger) {
61 61
 			self::$logger = $logger;
62 62
 			return self::$logger;
63 63
 		}
@@ -65,12 +65,12 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Initialize the configuration by loading all the configuration from config file
67 67
 		 */
68
-		public static function init(){
68
+		public static function init() {
69 69
 			$logger = static::getLogger();
70 70
 			$logger->debug('Initialization of the configuration');
71 71
 			self::$config = & load_configurations();
72 72
 			self::setBaseUrlUsingServerVar();
73
-			if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
73
+			if (ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info', 'all'))) {
74 74
 				$logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75 75
 			}
76 76
 			$logger->info('Configuration initialized successfully');
@@ -83,12 +83,12 @@  discard block
 block discarded – undo
83 83
 		 * @param  mixed $default the default value to use if can not find the config item in the list
84 84
 		 * @return mixed          the config value if exist or the default value
85 85
 		 */
86
-		public static function get($item, $default = null){
86
+		public static function get($item, $default = null) {
87 87
 			$logger = static::getLogger();
88
-			if(array_key_exists($item, self::$config)){
88
+			if (array_key_exists($item, self::$config)) {
89 89
 				return self::$config[$item];
90 90
 			}
91
-			$logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
91
+			$logger->warning('Cannot find config item [' . $item . '] using the default value [' . $default . ']');
92 92
 			return $default;
93 93
 		}
94 94
 
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 		 * @param string $item  the config item name to set
98 98
 		 * @param mixed $value the config item value
99 99
 		 */
100
-		public static function set($item, $value){
100
+		public static function set($item, $value) {
101 101
 			self::$config[$item] = $value;
102 102
 		}
103 103
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 		 * Get all the configuration values
106 106
 		 * @return array the config values
107 107
 		 */
108
-		public static function getAll(){
108
+		public static function getAll() {
109 109
 			return self::$config;
110 110
 		}
111 111
 
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 		 * Set the configuration values bu merged with the existing configuration
114 114
 		 * @param array $config the config values to add in the configuration list
115 115
 		 */
116
-		public static function setAll(array $config = array()){
116
+		public static function setAll(array $config = array()) {
117 117
 			self::$config = array_merge(self::$config, $config);
118 118
 		}
119 119
 
@@ -122,15 +122,15 @@  discard block
 block discarded – undo
122 122
 		 * @param  string $item the config item name to be deleted
123 123
 		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124 124
 		 */
125
-		public static function delete($item){
125
+		public static function delete($item) {
126 126
 			$logger = static::getLogger();
127
-			if(array_key_exists($item, self::$config)){
128
-				$logger->info('Delete config item ['.$item.']');
127
+			if (array_key_exists($item, self::$config)) {
128
+				$logger->info('Delete config item [' . $item . ']');
129 129
 				unset(self::$config[$item]);
130 130
 				return true;
131 131
 			}
132
-			else{
133
-				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
132
+			else {
133
+				$logger->warning('Config item [' . $item . '] to be deleted does not exists');
134 134
 				return false;
135 135
 			}
136 136
 		}
@@ -139,39 +139,39 @@  discard block
 block discarded – undo
139 139
 		 * Load the configuration file. This an alias to Loader::config()
140 140
 		 * @param  string $config the config name to be loaded
141 141
 		 */
142
-		public static function load($config){
142
+		public static function load($config) {
143 143
 			Loader::config($config);
144 144
 		}
145 145
 
146 146
 		/**
147 147
 		 * Set the configuration for "base_url" if is not set in the configuration
148 148
 		 */
149
-		private static function setBaseUrlUsingServerVar(){
149
+		private static function setBaseUrlUsingServerVar() {
150 150
 			$logger = static::getLogger();
151
-			if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
-				if(ENVIRONMENT == 'production'){
151
+			if (!isset(self::$config['base_url']) || !is_url(self::$config['base_url'])) {
152
+				if (ENVIRONMENT == 'production') {
153 153
 					$logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154 154
 				}
155 155
 				$baseUrl = null;
156 156
 				$protocol = 'http';
157
-				if(is_https()){
157
+				if (is_https()) {
158 158
 					$protocol = 'https';
159 159
 				}
160
-				$protocol .='://';
160
+				$protocol .= '://';
161 161
 
162
-				if (isset($_SERVER['SERVER_ADDR'])){
162
+				if (isset($_SERVER['SERVER_ADDR'])) {
163 163
 					$baseUrl = $_SERVER['SERVER_ADDR'];
164 164
 					//check if the server is running under IPv6
165
-					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
-						$baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
165
+					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE) {
166
+						$baseUrl = '[' . $_SERVER['SERVER_ADDR'] . ']';
167 167
 					}
168 168
 					$serverPort = 80;
169 169
 					if (isset($_SERVER['SERVER_PORT'])) {
170 170
 						$serverPort = $_SERVER['SERVER_PORT'];
171 171
 					}
172 172
 					$port = '';
173
-					if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
-						$port = ':'.$serverPort;
173
+					if ($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))) {
174
+						$port = ':' . $serverPort;
175 175
 					}
176 176
 					$baseUrl = $protocol . $baseUrl . $port . substr(
177 177
 																		$_SERVER['SCRIPT_NAME'], 
@@ -179,12 +179,12 @@  discard block
 block discarded – undo
179 179
 																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
180 180
 																	);
181 181
 				}
182
-				else{
182
+				else {
183 183
 					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
184 184
 					$baseUrl = 'http://localhost/';
185 185
 				}
186 186
 				self::set('base_url', $baseUrl);
187 187
 			}
188
-			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
188
+			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') . '/';
189 189
 		}
190 190
 	}
Please login to merge, or discard this patch.
core/classes/cache/FileCache.php 3 patches
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -1,312 +1,312 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class FileCache implements CacheInterface{
27
+    class FileCache implements CacheInterface{
28 28
 		
29
-		/**
30
-		 * Whether to enable compression of the cache data file.
31
-		 * @var boolean
32
-		 */
33
-		private $compressCacheData = true;
29
+        /**
30
+         * Whether to enable compression of the cache data file.
31
+         * @var boolean
32
+         */
33
+        private $compressCacheData = true;
34 34
 		
35
-		/**
36
-		 * The logger instance
37
-		 * @var Log
38
-		 */
39
-		private $logger;
35
+        /**
36
+         * The logger instance
37
+         * @var Log
38
+         */
39
+        private $logger;
40 40
 		
41 41
 		
42
-		public function __construct(Log $logger = null){
43
-			if(! $this->isSupported()){
44
-				show_error('The cache for file system is not available. Check the cache directory if is exists or is writable.');
45
-			}
46
-			/**
47
-	         * instance of the Log class
48
-	         */
49
-	        if(is_object($logger)){
50
-	          $this->logger = $logger;
51
-	        }
52
-	        else{
53
-	            $this->logger =& class_loader('Log', 'classes');
54
-	            $this->logger->setLogger('Library::FileCache');
55
-	        }
42
+        public function __construct(Log $logger = null){
43
+            if(! $this->isSupported()){
44
+                show_error('The cache for file system is not available. Check the cache directory if is exists or is writable.');
45
+            }
46
+            /**
47
+             * instance of the Log class
48
+             */
49
+            if(is_object($logger)){
50
+                $this->logger = $logger;
51
+            }
52
+            else{
53
+                $this->logger =& class_loader('Log', 'classes');
54
+                $this->logger->setLogger('Library::FileCache');
55
+            }
56 56
 			
57
-			//if Zlib extension is not loaded set compressCacheData to false
58
-			if(! extension_loaded('zlib')){
59
-				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
60
-				$this->compressCacheData = false;
61
-			}
62
-		}
57
+            //if Zlib extension is not loaded set compressCacheData to false
58
+            if(! extension_loaded('zlib')){
59
+                $this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
60
+                $this->compressCacheData = false;
61
+            }
62
+        }
63 63
 
64
-		/**
65
-		 * This is used to get the cache data using the key
66
-		 * @param  string $key the key to identify the cache data
67
-		 * @return mixed      the cache data if exists else return false
68
-		 */
69
-		public function get($key){
70
-			$this->logger->debug('Getting cache data for key ['. $key .']');
71
-			$filePath = $this->getFilePath($key);
72
-			if(! file_exists($filePath)){
73
-				$this->logger->info('No cache file found for the key ['. $key .'], return false');
74
-				return false;
75
-			}
76
-			$this->logger->info('The cache file [' .$filePath. '] for the key ['. $key .'] exists, check if the cache data is valid');
77
-			$handle = fopen($filePath,'r');
78
-			if(! is_resource($handle)){
79
-				$this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
80
-				return false;
81
-			}
82
-			// Getting a shared lock 
83
-		    flock($handle, LOCK_SH);
84
-		    $data = file_get_contents($filePath);
85
-      		fclose($handle);
86
-      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
87
-      		if (! $data) {
88
-      			$this->logger->error('Can not unserialize the cache data for the key ['. $key .'], return false');
89
-		         // If unserializing somehow didn't work out, we'll delete the file
90
-		         unlink($filePath);
91
-		         return false;
92
-	      	}
93
-	      	if (time() > $data['expire']) {
94
-	      		$this->logger->info('The cache data for the key ['. $key .'] already expired delete the cache file [' .$filePath. ']');
95
-		        // Unlinking when the file was expired
96
-		        unlink($filePath);
97
-		        return false;
98
-		     }
99
-		     else{
100
-		     	$this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101
-		     	return $data['data'];
102
-		     }
103
-		}
64
+        /**
65
+         * This is used to get the cache data using the key
66
+         * @param  string $key the key to identify the cache data
67
+         * @return mixed      the cache data if exists else return false
68
+         */
69
+        public function get($key){
70
+            $this->logger->debug('Getting cache data for key ['. $key .']');
71
+            $filePath = $this->getFilePath($key);
72
+            if(! file_exists($filePath)){
73
+                $this->logger->info('No cache file found for the key ['. $key .'], return false');
74
+                return false;
75
+            }
76
+            $this->logger->info('The cache file [' .$filePath. '] for the key ['. $key .'] exists, check if the cache data is valid');
77
+            $handle = fopen($filePath,'r');
78
+            if(! is_resource($handle)){
79
+                $this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
80
+                return false;
81
+            }
82
+            // Getting a shared lock 
83
+            flock($handle, LOCK_SH);
84
+            $data = file_get_contents($filePath);
85
+                fclose($handle);
86
+                $data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
87
+                if (! $data) {
88
+                    $this->logger->error('Can not unserialize the cache data for the key ['. $key .'], return false');
89
+                    // If unserializing somehow didn't work out, we'll delete the file
90
+                    unlink($filePath);
91
+                    return false;
92
+                }
93
+                if (time() > $data['expire']) {
94
+                    $this->logger->info('The cache data for the key ['. $key .'] already expired delete the cache file [' .$filePath. ']');
95
+                // Unlinking when the file was expired
96
+                unlink($filePath);
97
+                return false;
98
+                }
99
+                else{
100
+                    $this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101
+                    return $data['data'];
102
+                }
103
+        }
104 104
 
105 105
 
106
-		/**
107
-		 * Save data to the cache
108
-		 * @param string  $key  the key to identify this cache data
109
-		 * @param mixed  $data the cache data
110
-		 * @param integer $ttl  the cache life time
111
-		 * @return boolean true if success otherwise will return false
112
-		 */
113
-		public function set($key, $data, $ttl = 0){
114
-			$expire = time() + $ttl;
115
-			$this->logger->debug('Setting cache data for key ['. $key .'], time to live [' .$ttl. '], expire at [' . date('Y-m-d H:i:s', $expire) . ']');
116
-			$filePath = $this->getFilePath($key);
117
-			$handle = fopen($filePath,'w');
118
-			if(! is_resource($handle)){
119
-				$this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
120
-				return false;
121
-			}
122
-			flock($handle, LOCK_EX); // exclusive lock, will get released when the file is closed
123
-			//Serializing along with the TTL
124
-		    $cacheData = serialize(array(
125
-									'mtime' => time(),
126
-									'expire' => $expire,
127
-									'data' => $data,
128
-									'ttl' => $ttl
129
-									)
130
-								);		   
131
-		    $result = fwrite($handle, $this->compressCacheData ? gzdeflate($cacheData, 9) : $cacheData);
132
-		    if(! $result){
133
-		    	$this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
134
-		    	fclose($handle);
135
-		    	return false;
136
-		    }
137
-		    else{
138
-		    	$this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
139
-		    	fclose($handle);
140
-				chmod($filePath, 0640);
141
-				return true;
142
-		    }
143
-		}	
106
+        /**
107
+         * Save data to the cache
108
+         * @param string  $key  the key to identify this cache data
109
+         * @param mixed  $data the cache data
110
+         * @param integer $ttl  the cache life time
111
+         * @return boolean true if success otherwise will return false
112
+         */
113
+        public function set($key, $data, $ttl = 0){
114
+            $expire = time() + $ttl;
115
+            $this->logger->debug('Setting cache data for key ['. $key .'], time to live [' .$ttl. '], expire at [' . date('Y-m-d H:i:s', $expire) . ']');
116
+            $filePath = $this->getFilePath($key);
117
+            $handle = fopen($filePath,'w');
118
+            if(! is_resource($handle)){
119
+                $this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
120
+                return false;
121
+            }
122
+            flock($handle, LOCK_EX); // exclusive lock, will get released when the file is closed
123
+            //Serializing along with the TTL
124
+            $cacheData = serialize(array(
125
+                                    'mtime' => time(),
126
+                                    'expire' => $expire,
127
+                                    'data' => $data,
128
+                                    'ttl' => $ttl
129
+                                    )
130
+                                );		   
131
+            $result = fwrite($handle, $this->compressCacheData ? gzdeflate($cacheData, 9) : $cacheData);
132
+            if(! $result){
133
+                $this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
134
+                fclose($handle);
135
+                return false;
136
+            }
137
+            else{
138
+                $this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
139
+                fclose($handle);
140
+                chmod($filePath, 0640);
141
+                return true;
142
+            }
143
+        }	
144 144
 
145 145
 
146
-		/**
147
-		 * Delete the cache data for given key
148
-		 * @param  string $key the key for cache to be deleted
149
-		 * @return boolean      true if the cache is delete, false if can't delete 
150
-		 * the cache or the cache with the given key not exist
151
-		 */
152
-		public function delete($key){
153
-			$this->logger->debug('Deleting of cache data for key [' .$key. ']');
154
-			$filePath = $this->getFilePath($key);
155
-			$this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
156
-			if(! file_exists($filePath)){
157
-				$this->logger->info('This cache file does not exists skipping');
158
-				return false;
159
-			}
160
-			else{
161
-				$this->logger->info('Found cache file [' .$filePath. '] remove it');
162
-	      		unlink($filePath);
163
-				return true;
164
-			}
165
-		}
146
+        /**
147
+         * Delete the cache data for given key
148
+         * @param  string $key the key for cache to be deleted
149
+         * @return boolean      true if the cache is delete, false if can't delete 
150
+         * the cache or the cache with the given key not exist
151
+         */
152
+        public function delete($key){
153
+            $this->logger->debug('Deleting of cache data for key [' .$key. ']');
154
+            $filePath = $this->getFilePath($key);
155
+            $this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
156
+            if(! file_exists($filePath)){
157
+                $this->logger->info('This cache file does not exists skipping');
158
+                return false;
159
+            }
160
+            else{
161
+                $this->logger->info('Found cache file [' .$filePath. '] remove it');
162
+                    unlink($filePath);
163
+                return true;
164
+            }
165
+        }
166 166
 		
167
-		/**
168
-		 * Get the cache information for given key
169
-		 * @param  string $key the key for cache to get the information for
170
-		 * @return boolean|array    the cache information. The associative array and must contains the following information:
171
-		 * 'mtime' => creation time of the cache (Unix timestamp),
172
-		 * 'expire' => expiration time of the cache (Unix timestamp),
173
-		 * 'ttl' => the time to live of the cache in second
174
-		 */
175
-		public function getInfo($key){
176
-			$this->logger->debug('Getting of cache info for key [' .$key. ']');
177
-			$filePath = $this->getFilePath($key);
178
-			$this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
179
-			if(! file_exists($filePath)){
180
-				$this->logger->info('This cache file does not exists skipping');
181
-				return false;
182
-			}
183
-			$this->logger->info('Found cache file [' .$filePath. '] check the validity');
184
-      		$data = file_get_contents($filePath);
185
-			$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
186
-			if(! $data){
187
-				$this->logger->warning('Can not unserialize the cache data for file [' . $filePath . ']');
188
-				return false;
189
-			}
190
-			$this->logger->info('This cache data is OK check for expire');
191
-			if(isset($data['expire']) && $data['expire'] > time()){
192
-				$this->logger->info('This cache not yet expired return cache informations');
193
-				$info = array(
194
-					'mtime' => $data['mtime'],
195
-					'expire' => $data['expire'],
196
-					'ttl' => $data['ttl']
197
-					);
198
-				return $info;
199
-			}
200
-			$this->logger->info('This cache already expired return false');
201
-			return false;
202
-		}
167
+        /**
168
+         * Get the cache information for given key
169
+         * @param  string $key the key for cache to get the information for
170
+         * @return boolean|array    the cache information. The associative array and must contains the following information:
171
+         * 'mtime' => creation time of the cache (Unix timestamp),
172
+         * 'expire' => expiration time of the cache (Unix timestamp),
173
+         * 'ttl' => the time to live of the cache in second
174
+         */
175
+        public function getInfo($key){
176
+            $this->logger->debug('Getting of cache info for key [' .$key. ']');
177
+            $filePath = $this->getFilePath($key);
178
+            $this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
179
+            if(! file_exists($filePath)){
180
+                $this->logger->info('This cache file does not exists skipping');
181
+                return false;
182
+            }
183
+            $this->logger->info('Found cache file [' .$filePath. '] check the validity');
184
+                $data = file_get_contents($filePath);
185
+            $data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
186
+            if(! $data){
187
+                $this->logger->warning('Can not unserialize the cache data for file [' . $filePath . ']');
188
+                return false;
189
+            }
190
+            $this->logger->info('This cache data is OK check for expire');
191
+            if(isset($data['expire']) && $data['expire'] > time()){
192
+                $this->logger->info('This cache not yet expired return cache informations');
193
+                $info = array(
194
+                    'mtime' => $data['mtime'],
195
+                    'expire' => $data['expire'],
196
+                    'ttl' => $data['ttl']
197
+                    );
198
+                return $info;
199
+            }
200
+            $this->logger->info('This cache already expired return false');
201
+            return false;
202
+        }
203 203
 
204 204
 
205
-		/**
206
-		 * Used to delete expired cache data
207
-		 */
208
-		public function deleteExpiredCache(){
209
-			$this->logger->debug('Deleting of expired cache files');
210
-			$list = glob(CACHE_PATH . '*.cache');
211
-			if(! $list){
212
-				$this->logger->info('No cache files were found skipping');
213
-			}
214
-			else{
215
-				$this->logger->info('Found [' . count($list) . '] cache files to remove if expired');
216
-				foreach ($list as $file) {
217
-					$this->logger->debug('Processing the cache file [' . $file . ']');
218
-					$data = file_get_contents($file);
219
-		      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
220
-		      		if(! $data){
221
-		      			$this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
222
-		      		}
223
-		      		else if(time() > $data['expire']){
224
-		      			$this->logger->info('The cache data for file [' . $file . '] already expired remove it');
225
-		      			unlink($file);
226
-		      		}
227
-		      		else{
228
-		      			$this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
229
-		      		}
230
-				}
231
-			}
232
-		}	
205
+        /**
206
+         * Used to delete expired cache data
207
+         */
208
+        public function deleteExpiredCache(){
209
+            $this->logger->debug('Deleting of expired cache files');
210
+            $list = glob(CACHE_PATH . '*.cache');
211
+            if(! $list){
212
+                $this->logger->info('No cache files were found skipping');
213
+            }
214
+            else{
215
+                $this->logger->info('Found [' . count($list) . '] cache files to remove if expired');
216
+                foreach ($list as $file) {
217
+                    $this->logger->debug('Processing the cache file [' . $file . ']');
218
+                    $data = file_get_contents($file);
219
+                        $data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
220
+                        if(! $data){
221
+                            $this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
222
+                        }
223
+                        else if(time() > $data['expire']){
224
+                            $this->logger->info('The cache data for file [' . $file . '] already expired remove it');
225
+                            unlink($file);
226
+                        }
227
+                        else{
228
+                            $this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
229
+                        }
230
+                }
231
+            }
232
+        }	
233 233
 
234
-		/**
235
-		 * Remove all file from cache folder
236
-		 */
237
-		public function clean(){
238
-			$this->logger->debug('Deleting of all cache files');
239
-			$list = glob(CACHE_PATH . '*.cache');
240
-			if(! $list){
241
-				$this->logger->info('No cache files were found skipping');
242
-			}
243
-			else{
244
-				$this->logger->info('Found [' . count($list) . '] cache files to remove');
245
-				foreach ($list as $file) {
246
-					$this->logger->debug('Processing the cache file [' . $file . ']');
247
-					unlink($file);
248
-				}
249
-			}
250
-		}
234
+        /**
235
+         * Remove all file from cache folder
236
+         */
237
+        public function clean(){
238
+            $this->logger->debug('Deleting of all cache files');
239
+            $list = glob(CACHE_PATH . '*.cache');
240
+            if(! $list){
241
+                $this->logger->info('No cache files were found skipping');
242
+            }
243
+            else{
244
+                $this->logger->info('Found [' . count($list) . '] cache files to remove');
245
+                foreach ($list as $file) {
246
+                    $this->logger->debug('Processing the cache file [' . $file . ']');
247
+                    unlink($file);
248
+                }
249
+            }
250
+        }
251 251
 	
252
-	    /**
253
-	     * @return boolean
254
-	     */
255
-	    public function isCompressCacheData(){
256
-	        return $this->compressCacheData;
257
-	    }
252
+        /**
253
+         * @return boolean
254
+         */
255
+        public function isCompressCacheData(){
256
+            return $this->compressCacheData;
257
+        }
258 258
 
259
-	    /**
260
-	     * @param boolean $compressCacheData
261
-	     *
262
-	     * @return object
263
-	     */
264
-	    public function setCompressCacheData($status = true){
265
-			//if Zlib extension is not loaded set compressCacheData to false
266
-			if($status === true && ! extension_loaded('zlib')){
259
+        /**
260
+         * @param boolean $compressCacheData
261
+         *
262
+         * @return object
263
+         */
264
+        public function setCompressCacheData($status = true){
265
+            //if Zlib extension is not loaded set compressCacheData to false
266
+            if($status === true && ! extension_loaded('zlib')){
267 267
 				
268
-				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
269
-				$this->compressCacheData = false;
270
-			}
271
-			else{
272
-				$this->compressCacheData = $status;
273
-			}
274
-			return $this;
275
-	    }
268
+                $this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
269
+                $this->compressCacheData = false;
270
+            }
271
+            else{
272
+                $this->compressCacheData = $status;
273
+            }
274
+            return $this;
275
+        }
276 276
 		
277
-		/**
278
-		 * Check whether the cache feature for the handle is supported
279
-		 *
280
-		 * @return bool
281
-		 */
282
-		public function isSupported(){
283
-			return CACHE_PATH && is_dir(CACHE_PATH) && is_writable(CACHE_PATH);
284
-		}
277
+        /**
278
+         * Check whether the cache feature for the handle is supported
279
+         *
280
+         * @return bool
281
+         */
282
+        public function isSupported(){
283
+            return CACHE_PATH && is_dir(CACHE_PATH) && is_writable(CACHE_PATH);
284
+        }
285 285
 
286
-		/**
287
-	     * Return the Log instance
288
-	     * @return object
289
-	     */
290
-	    public function getLogger(){
291
-	      return $this->logger;
292
-	    }
286
+        /**
287
+         * Return the Log instance
288
+         * @return object
289
+         */
290
+        public function getLogger(){
291
+            return $this->logger;
292
+        }
293 293
 
294
-	    /**
295
-	     * Set the log instance
296
-	     * @param Log $logger the log object
297
-	     */
298
-	    public function setLogger(Log $logger){
299
-	      $this->logger = $logger;
300
-	      return $this;
301
-	    }
294
+        /**
295
+         * Set the log instance
296
+         * @param Log $logger the log object
297
+         */
298
+        public function setLogger(Log $logger){
299
+            $this->logger = $logger;
300
+            return $this;
301
+        }
302 302
 		
303
-		/**
304
-		* Get the cache file full path for the given key
305
-		*
306
-		* @param string $key the cache item key
307
-		* @return string the full cache file path for this key
308
-		*/
309
-		private function getFilePath($key){
310
-			return CACHE_PATH . md5($key) . '.cache';
311
-		}
312
-	}
303
+        /**
304
+         * Get the cache file full path for the given key
305
+         *
306
+         * @param string $key the cache item key
307
+         * @return string the full cache file path for this key
308
+         */
309
+        private function getFilePath($key){
310
+            return CACHE_PATH . md5($key) . '.cache';
311
+        }
312
+    }
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class FileCache implements CacheInterface{
27
+	class FileCache implements CacheInterface {
28 28
 		
29 29
 		/**
30 30
 		 * Whether to enable compression of the cache data file.
@@ -39,23 +39,23 @@  discard block
 block discarded – undo
39 39
 		private $logger;
40 40
 		
41 41
 		
42
-		public function __construct(Log $logger = null){
43
-			if(! $this->isSupported()){
42
+		public function __construct(Log $logger = null) {
43
+			if (!$this->isSupported()) {
44 44
 				show_error('The cache for file system is not available. Check the cache directory if is exists or is writable.');
45 45
 			}
46 46
 			/**
47 47
 	         * instance of the Log class
48 48
 	         */
49
-	        if(is_object($logger)){
49
+	        if (is_object($logger)) {
50 50
 	          $this->logger = $logger;
51 51
 	        }
52
-	        else{
53
-	            $this->logger =& class_loader('Log', 'classes');
52
+	        else {
53
+	            $this->logger = & class_loader('Log', 'classes');
54 54
 	            $this->logger->setLogger('Library::FileCache');
55 55
 	        }
56 56
 			
57 57
 			//if Zlib extension is not loaded set compressCacheData to false
58
-			if(! extension_loaded('zlib')){
58
+			if (!extension_loaded('zlib')) {
59 59
 				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
60 60
 				$this->compressCacheData = false;
61 61
 			}
@@ -66,17 +66,17 @@  discard block
 block discarded – undo
66 66
 		 * @param  string $key the key to identify the cache data
67 67
 		 * @return mixed      the cache data if exists else return false
68 68
 		 */
69
-		public function get($key){
70
-			$this->logger->debug('Getting cache data for key ['. $key .']');
69
+		public function get($key) {
70
+			$this->logger->debug('Getting cache data for key [' . $key . ']');
71 71
 			$filePath = $this->getFilePath($key);
72
-			if(! file_exists($filePath)){
73
-				$this->logger->info('No cache file found for the key ['. $key .'], return false');
72
+			if (!file_exists($filePath)) {
73
+				$this->logger->info('No cache file found for the key [' . $key . '], return false');
74 74
 				return false;
75 75
 			}
76
-			$this->logger->info('The cache file [' .$filePath. '] for the key ['. $key .'] exists, check if the cache data is valid');
77
-			$handle = fopen($filePath,'r');
78
-			if(! is_resource($handle)){
79
-				$this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
76
+			$this->logger->info('The cache file [' . $filePath . '] for the key [' . $key . '] exists, check if the cache data is valid');
77
+			$handle = fopen($filePath, 'r');
78
+			if (!is_resource($handle)) {
79
+				$this->logger->error('Can not open the file cache [' . $filePath . '] for the key [' . $key . '], return false');
80 80
 				return false;
81 81
 			}
82 82
 			// Getting a shared lock 
@@ -84,20 +84,20 @@  discard block
 block discarded – undo
84 84
 		    $data = file_get_contents($filePath);
85 85
       		fclose($handle);
86 86
       		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
87
-      		if (! $data) {
88
-      			$this->logger->error('Can not unserialize the cache data for the key ['. $key .'], return false');
87
+      		if (!$data) {
88
+      			$this->logger->error('Can not unserialize the cache data for the key [' . $key . '], return false');
89 89
 		         // If unserializing somehow didn't work out, we'll delete the file
90 90
 		         unlink($filePath);
91 91
 		         return false;
92 92
 	      	}
93 93
 	      	if (time() > $data['expire']) {
94
-	      		$this->logger->info('The cache data for the key ['. $key .'] already expired delete the cache file [' .$filePath. ']');
94
+	      		$this->logger->info('The cache data for the key [' . $key . '] already expired delete the cache file [' . $filePath . ']');
95 95
 		        // Unlinking when the file was expired
96 96
 		        unlink($filePath);
97 97
 		        return false;
98 98
 		     }
99
-		     else{
100
-		     	$this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
99
+		     else {
100
+		     	$this->logger->info('The cache not yet expire, now return the cache data for key [' . $key . '], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101 101
 		     	return $data['data'];
102 102
 		     }
103 103
 		}
@@ -110,13 +110,13 @@  discard block
 block discarded – undo
110 110
 		 * @param integer $ttl  the cache life time
111 111
 		 * @return boolean true if success otherwise will return false
112 112
 		 */
113
-		public function set($key, $data, $ttl = 0){
113
+		public function set($key, $data, $ttl = 0) {
114 114
 			$expire = time() + $ttl;
115
-			$this->logger->debug('Setting cache data for key ['. $key .'], time to live [' .$ttl. '], expire at [' . date('Y-m-d H:i:s', $expire) . ']');
115
+			$this->logger->debug('Setting cache data for key [' . $key . '], time to live [' . $ttl . '], expire at [' . date('Y-m-d H:i:s', $expire) . ']');
116 116
 			$filePath = $this->getFilePath($key);
117
-			$handle = fopen($filePath,'w');
118
-			if(! is_resource($handle)){
119
-				$this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
117
+			$handle = fopen($filePath, 'w');
118
+			if (!is_resource($handle)) {
119
+				$this->logger->error('Can not open the file cache [' . $filePath . '] for the key [' . $key . '], return false');
120 120
 				return false;
121 121
 			}
122 122
 			flock($handle, LOCK_EX); // exclusive lock, will get released when the file is closed
@@ -129,13 +129,13 @@  discard block
 block discarded – undo
129 129
 									)
130 130
 								);		   
131 131
 		    $result = fwrite($handle, $this->compressCacheData ? gzdeflate($cacheData, 9) : $cacheData);
132
-		    if(! $result){
133
-		    	$this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
132
+		    if (!$result) {
133
+		    	$this->logger->error('Can not write cache data into file [' . $filePath . '] for the key [' . $key . '], return false');
134 134
 		    	fclose($handle);
135 135
 		    	return false;
136 136
 		    }
137
-		    else{
138
-		    	$this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
137
+		    else {
138
+		    	$this->logger->info('Cache data saved into file [' . $filePath . '] for the key [' . $key . ']');
139 139
 		    	fclose($handle);
140 140
 				chmod($filePath, 0640);
141 141
 				return true;
@@ -149,16 +149,16 @@  discard block
 block discarded – undo
149 149
 		 * @return boolean      true if the cache is delete, false if can't delete 
150 150
 		 * the cache or the cache with the given key not exist
151 151
 		 */
152
-		public function delete($key){
153
-			$this->logger->debug('Deleting of cache data for key [' .$key. ']');
152
+		public function delete($key) {
153
+			$this->logger->debug('Deleting of cache data for key [' . $key . ']');
154 154
 			$filePath = $this->getFilePath($key);
155
-			$this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
156
-			if(! file_exists($filePath)){
155
+			$this->logger->info('The file path for the key [' . $key . '] is [' . $filePath . ']');
156
+			if (!file_exists($filePath)) {
157 157
 				$this->logger->info('This cache file does not exists skipping');
158 158
 				return false;
159 159
 			}
160
-			else{
161
-				$this->logger->info('Found cache file [' .$filePath. '] remove it');
160
+			else {
161
+				$this->logger->info('Found cache file [' . $filePath . '] remove it');
162 162
 	      		unlink($filePath);
163 163
 				return true;
164 164
 			}
@@ -172,23 +172,23 @@  discard block
 block discarded – undo
172 172
 		 * 'expire' => expiration time of the cache (Unix timestamp),
173 173
 		 * 'ttl' => the time to live of the cache in second
174 174
 		 */
175
-		public function getInfo($key){
176
-			$this->logger->debug('Getting of cache info for key [' .$key. ']');
175
+		public function getInfo($key) {
176
+			$this->logger->debug('Getting of cache info for key [' . $key . ']');
177 177
 			$filePath = $this->getFilePath($key);
178
-			$this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
179
-			if(! file_exists($filePath)){
178
+			$this->logger->info('The file path for the key [' . $key . '] is [' . $filePath . ']');
179
+			if (!file_exists($filePath)) {
180 180
 				$this->logger->info('This cache file does not exists skipping');
181 181
 				return false;
182 182
 			}
183
-			$this->logger->info('Found cache file [' .$filePath. '] check the validity');
183
+			$this->logger->info('Found cache file [' . $filePath . '] check the validity');
184 184
       		$data = file_get_contents($filePath);
185 185
 			$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
186
-			if(! $data){
186
+			if (!$data) {
187 187
 				$this->logger->warning('Can not unserialize the cache data for file [' . $filePath . ']');
188 188
 				return false;
189 189
 			}
190 190
 			$this->logger->info('This cache data is OK check for expire');
191
-			if(isset($data['expire']) && $data['expire'] > time()){
191
+			if (isset($data['expire']) && $data['expire'] > time()) {
192 192
 				$this->logger->info('This cache not yet expired return cache informations');
193 193
 				$info = array(
194 194
 					'mtime' => $data['mtime'],
@@ -205,26 +205,26 @@  discard block
 block discarded – undo
205 205
 		/**
206 206
 		 * Used to delete expired cache data
207 207
 		 */
208
-		public function deleteExpiredCache(){
208
+		public function deleteExpiredCache() {
209 209
 			$this->logger->debug('Deleting of expired cache files');
210 210
 			$list = glob(CACHE_PATH . '*.cache');
211
-			if(! $list){
211
+			if (!$list) {
212 212
 				$this->logger->info('No cache files were found skipping');
213 213
 			}
214
-			else{
214
+			else {
215 215
 				$this->logger->info('Found [' . count($list) . '] cache files to remove if expired');
216 216
 				foreach ($list as $file) {
217 217
 					$this->logger->debug('Processing the cache file [' . $file . ']');
218 218
 					$data = file_get_contents($file);
219 219
 		      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
220
-		      		if(! $data){
220
+		      		if (!$data) {
221 221
 		      			$this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
222 222
 		      		}
223
-		      		else if(time() > $data['expire']){
223
+		      		else if (time() > $data['expire']) {
224 224
 		      			$this->logger->info('The cache data for file [' . $file . '] already expired remove it');
225 225
 		      			unlink($file);
226 226
 		      		}
227
-		      		else{
227
+		      		else {
228 228
 		      			$this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
229 229
 		      		}
230 230
 				}
@@ -234,13 +234,13 @@  discard block
 block discarded – undo
234 234
 		/**
235 235
 		 * Remove all file from cache folder
236 236
 		 */
237
-		public function clean(){
237
+		public function clean() {
238 238
 			$this->logger->debug('Deleting of all cache files');
239 239
 			$list = glob(CACHE_PATH . '*.cache');
240
-			if(! $list){
240
+			if (!$list) {
241 241
 				$this->logger->info('No cache files were found skipping');
242 242
 			}
243
-			else{
243
+			else {
244 244
 				$this->logger->info('Found [' . count($list) . '] cache files to remove');
245 245
 				foreach ($list as $file) {
246 246
 					$this->logger->debug('Processing the cache file [' . $file . ']');
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 	    /**
253 253
 	     * @return boolean
254 254
 	     */
255
-	    public function isCompressCacheData(){
255
+	    public function isCompressCacheData() {
256 256
 	        return $this->compressCacheData;
257 257
 	    }
258 258
 
@@ -261,14 +261,14 @@  discard block
 block discarded – undo
261 261
 	     *
262 262
 	     * @return object
263 263
 	     */
264
-	    public function setCompressCacheData($status = true){
264
+	    public function setCompressCacheData($status = true) {
265 265
 			//if Zlib extension is not loaded set compressCacheData to false
266
-			if($status === true && ! extension_loaded('zlib')){
266
+			if ($status === true && !extension_loaded('zlib')) {
267 267
 				
268 268
 				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
269 269
 				$this->compressCacheData = false;
270 270
 			}
271
-			else{
271
+			else {
272 272
 				$this->compressCacheData = $status;
273 273
 			}
274 274
 			return $this;
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		 *
280 280
 		 * @return bool
281 281
 		 */
282
-		public function isSupported(){
282
+		public function isSupported() {
283 283
 			return CACHE_PATH && is_dir(CACHE_PATH) && is_writable(CACHE_PATH);
284 284
 		}
285 285
 
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 	     * Return the Log instance
288 288
 	     * @return object
289 289
 	     */
290
-	    public function getLogger(){
290
+	    public function getLogger() {
291 291
 	      return $this->logger;
292 292
 	    }
293 293
 
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
 	     * Set the log instance
296 296
 	     * @param Log $logger the log object
297 297
 	     */
298
-	    public function setLogger(Log $logger){
298
+	    public function setLogger(Log $logger) {
299 299
 	      $this->logger = $logger;
300 300
 	      return $this;
301 301
 	    }
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 		* @param string $key the cache item key
307 307
 		* @return string the full cache file path for this key
308 308
 		*/
309
-		private function getFilePath($key){
309
+		private function getFilePath($key) {
310 310
 			return CACHE_PATH . md5($key) . '.cache';
311 311
 		}
312 312
 	}
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -48,8 +48,7 @@  discard block
 block discarded – undo
48 48
 	         */
49 49
 	        if(is_object($logger)){
50 50
 	          $this->logger = $logger;
51
-	        }
52
-	        else{
51
+	        } else{
53 52
 	            $this->logger =& class_loader('Log', 'classes');
54 53
 	            $this->logger->setLogger('Library::FileCache');
55 54
 	        }
@@ -95,8 +94,7 @@  discard block
 block discarded – undo
95 94
 		        // Unlinking when the file was expired
96 95
 		        unlink($filePath);
97 96
 		        return false;
98
-		     }
99
-		     else{
97
+		     } else{
100 98
 		     	$this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101 99
 		     	return $data['data'];
102 100
 		     }
@@ -133,8 +131,7 @@  discard block
 block discarded – undo
133 131
 		    	$this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
134 132
 		    	fclose($handle);
135 133
 		    	return false;
136
-		    }
137
-		    else{
134
+		    } else{
138 135
 		    	$this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
139 136
 		    	fclose($handle);
140 137
 				chmod($filePath, 0640);
@@ -156,8 +153,7 @@  discard block
 block discarded – undo
156 153
 			if(! file_exists($filePath)){
157 154
 				$this->logger->info('This cache file does not exists skipping');
158 155
 				return false;
159
-			}
160
-			else{
156
+			} else{
161 157
 				$this->logger->info('Found cache file [' .$filePath. '] remove it');
162 158
 	      		unlink($filePath);
163 159
 				return true;
@@ -210,8 +206,7 @@  discard block
 block discarded – undo
210 206
 			$list = glob(CACHE_PATH . '*.cache');
211 207
 			if(! $list){
212 208
 				$this->logger->info('No cache files were found skipping');
213
-			}
214
-			else{
209
+			} else{
215 210
 				$this->logger->info('Found [' . count($list) . '] cache files to remove if expired');
216 211
 				foreach ($list as $file) {
217 212
 					$this->logger->debug('Processing the cache file [' . $file . ']');
@@ -219,12 +214,10 @@  discard block
 block discarded – undo
219 214
 		      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
220 215
 		      		if(! $data){
221 216
 		      			$this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
222
-		      		}
223
-		      		else if(time() > $data['expire']){
217
+		      		} else if(time() > $data['expire']){
224 218
 		      			$this->logger->info('The cache data for file [' . $file . '] already expired remove it');
225 219
 		      			unlink($file);
226
-		      		}
227
-		      		else{
220
+		      		} else{
228 221
 		      			$this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
229 222
 		      		}
230 223
 				}
@@ -239,8 +232,7 @@  discard block
 block discarded – undo
239 232
 			$list = glob(CACHE_PATH . '*.cache');
240 233
 			if(! $list){
241 234
 				$this->logger->info('No cache files were found skipping');
242
-			}
243
-			else{
235
+			} else{
244 236
 				$this->logger->info('Found [' . count($list) . '] cache files to remove');
245 237
 				foreach ($list as $file) {
246 238
 					$this->logger->debug('Processing the cache file [' . $file . ']');
@@ -267,8 +259,7 @@  discard block
 block discarded – undo
267 259
 				
268 260
 				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
269 261
 				$this->compressCacheData = false;
270
-			}
271
-			else{
262
+			} else{
272 263
 				$this->compressCacheData = $status;
273 264
 			}
274 265
 			return $this;
Please login to merge, or discard this patch.
core/classes/Router.php 3 patches
Indentation   +610 added lines, -610 removed lines patch added patch discarded remove patch
@@ -1,624 +1,624 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
26
-
27
-	class Router {
28
-		/**
29
-		* @var array $pattern: The list of URIs to validate against
30
-		*/
31
-		private $pattern = array();
32
-
33
-		/**
34
-		* @var array $callback: The list of callback to call
35
-		*/
36
-		private $callback = array();
37
-
38
-		/**
39
-		* @var string $uriTrim: The char to remove from the URIs
40
-		*/
41
-		protected $uriTrim = '/\^$';
42
-
43
-		/**
44
-		* @var string $uri: The route URI to use
45
-		*/
46
-		protected $uri = '';
47
-
48
-		/**
49
-		 * The module name of the current request
50
-		 * @var string
51
-		 */
52
-		protected $module = null;
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+
27
+    class Router {
28
+        /**
29
+         * @var array $pattern: The list of URIs to validate against
30
+         */
31
+        private $pattern = array();
32
+
33
+        /**
34
+         * @var array $callback: The list of callback to call
35
+         */
36
+        private $callback = array();
37
+
38
+        /**
39
+         * @var string $uriTrim: The char to remove from the URIs
40
+         */
41
+        protected $uriTrim = '/\^$';
42
+
43
+        /**
44
+         * @var string $uri: The route URI to use
45
+         */
46
+        protected $uri = '';
47
+
48
+        /**
49
+         * The module name of the current request
50
+         * @var string
51
+         */
52
+        protected $module = null;
53 53
 		
54
-		/**
55
-		 * The controller name of the current request
56
-		 * @var string
57
-		 */
58
-		protected $controller = null;
59
-
60
-		/**
61
-		 * The controller path
62
-		 * @var string
63
-		 */
64
-		protected $controllerPath = null;
65
-
66
-		/**
67
-		 * The method name. The default value is "index"
68
-		 * @var string
69
-		 */
70
-		protected $method = 'index';
71
-
72
-		/**
73
-		 * List of argument to pass to the method
74
-		 * @var array
75
-		 */
76
-		protected $args = array();
77
-
78
-		/**
79
-		 * List of routes configurations
80
-		 * @var array
81
-		 */
82
-		protected $routes = array();
83
-
84
-		/**
85
-		 * The segments array for the current request
86
-		 * @var array
87
-		 */
88
-		protected $segments = array();
89
-
90
-		/**
91
-		 * The logger instance
92
-		 * @var Log
93
-		 */
94
-		private $logger;
95
-
96
-		/**
97
-		 * Construct the new Router instance
98
-		 */
99
-		public function __construct(){
100
-			$this->setLoggerFromParamOrCreateNewInstance(null);
54
+        /**
55
+         * The controller name of the current request
56
+         * @var string
57
+         */
58
+        protected $controller = null;
59
+
60
+        /**
61
+         * The controller path
62
+         * @var string
63
+         */
64
+        protected $controllerPath = null;
65
+
66
+        /**
67
+         * The method name. The default value is "index"
68
+         * @var string
69
+         */
70
+        protected $method = 'index';
71
+
72
+        /**
73
+         * List of argument to pass to the method
74
+         * @var array
75
+         */
76
+        protected $args = array();
77
+
78
+        /**
79
+         * List of routes configurations
80
+         * @var array
81
+         */
82
+        protected $routes = array();
83
+
84
+        /**
85
+         * The segments array for the current request
86
+         * @var array
87
+         */
88
+        protected $segments = array();
89
+
90
+        /**
91
+         * The logger instance
92
+         * @var Log
93
+         */
94
+        private $logger;
95
+
96
+        /**
97
+         * Construct the new Router instance
98
+         */
99
+        public function __construct(){
100
+            $this->setLoggerFromParamOrCreateNewInstance(null);
101 101
 			
102
-			//loading routes for module
103
-			$moduleRouteList = array();
104
-			$modulesRoutes = Module::getModulesRoutes();
105
-			if($modulesRoutes && is_array($modulesRoutes)){
106
-				$moduleRouteList = $modulesRoutes;
107
-				unset($modulesRoutes);
108
-			}
109
-			$this->setRouteConfiguration($moduleRouteList);
110
-			$this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
111
-
112
-			//Set route informations
113
-			$this->setRouteConfigurationInfos();
114
-		}
115
-
116
-		/**
117
-		 * Get the route patterns
118
-		 * @return array
119
-		 */
120
-		public function getPattern(){
121
-			return $this->pattern;
122
-		}
123
-
124
-		/**
125
-		 * Get the route callbacks
126
-		 * @return array
127
-		 */
128
-		public function getCallback(){
129
-			return $this->callback;
130
-		}
131
-
132
-	    /**
133
-		 * Get the module name
134
-		 * @return string
135
-		 */
136
-		public function getModule(){
137
-			return $this->module;
138
-		}
102
+            //loading routes for module
103
+            $moduleRouteList = array();
104
+            $modulesRoutes = Module::getModulesRoutes();
105
+            if($modulesRoutes && is_array($modulesRoutes)){
106
+                $moduleRouteList = $modulesRoutes;
107
+                unset($modulesRoutes);
108
+            }
109
+            $this->setRouteConfiguration($moduleRouteList);
110
+            $this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
111
+
112
+            //Set route informations
113
+            $this->setRouteConfigurationInfos();
114
+        }
115
+
116
+        /**
117
+         * Get the route patterns
118
+         * @return array
119
+         */
120
+        public function getPattern(){
121
+            return $this->pattern;
122
+        }
123
+
124
+        /**
125
+         * Get the route callbacks
126
+         * @return array
127
+         */
128
+        public function getCallback(){
129
+            return $this->callback;
130
+        }
131
+
132
+        /**
133
+         * Get the module name
134
+         * @return string
135
+         */
136
+        public function getModule(){
137
+            return $this->module;
138
+        }
139 139
 		
140
-		/**
141
-		 * Get the controller name
142
-		 * @return string
143
-		 */
144
-		public function getController(){
145
-			return $this->controller;
146
-		}
147
-
148
-		/**
149
-		 * Get the controller file path
150
-		 * @return string
151
-		 */
152
-		public function getControllerPath(){
153
-			return $this->controllerPath;
154
-		}
155
-
156
-		/**
157
-		 * Get the controller method
158
-		 * @return string
159
-		 */
160
-		public function getMethod(){
161
-			return $this->method;
162
-		}
163
-
164
-		/**
165
-		 * Get the request arguments
166
-		 * @return array
167
-		 */
168
-		public function getArgs(){
169
-			return $this->args;
170
-		}
171
-
172
-		/**
173
-		 * Get the URL segments array
174
-		 * @return array
175
-		 */
176
-		public function getSegments(){
177
-			return $this->segments;
178
-		}
179
-
180
-		/**
181
-	     * Return the Log instance
182
-	     * @return Log
183
-	     */
184
-	    public function getLogger(){
185
-	      return $this->logger;
186
-	    }
187
-
188
-	    /**
189
-	     * Set the log instance
190
-	     * @param Log $logger the log object
191
-		 * @return object
192
-	     */
193
-	    public function setLogger($logger){
194
-	      $this->logger = $logger;
195
-	      return $this;
196
-	    }
197
-
198
-	    /**
199
-		 * Get the route URI
200
-		 * @return string
201
-		 */
202
-		public function getRouteUri(){
203
-			return $this->uri;
204
-		}
205
-
206
-		/**
207
-		* Add the URI and callback to the list of URIs to validate
208
-		*
209
-		* @param string $uri the request URI
210
-		* @param string $callback the callback function
211
-		*
212
-		* @return object the current instance
213
-		*/
214
-		public function add($uri, $callback) {
215
-			$uri = trim($uri, $this->uriTrim);
216
-			if(in_array($uri, $this->pattern)){
217
-				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
218
-			}
219
-			$this->pattern[] = $uri;
220
-			$this->callback[] = $callback;
221
-			return $this;
222
-		}
223
-
224
-		/**
225
-		* Remove the route configuration
226
-		*
227
-		* @param string $uri the URI
228
-		*
229
-		* @return object the current instance
230
-		*/
231
-		public function removeRoute($uri) {
232
-			$index  = array_search($uri, $this->pattern, true);
233
-			if($index !== false){
234
-				$this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
235
-				unset($this->pattern[$index]);
236
-				unset($this->callback[$index]);
237
-			}
238
-			return $this;
239
-		}
240
-
241
-
242
-		/**
243
-		* Remove all the routes from the configuration
244
-		*
245
-		* @return object the current instance
246
-		*/
247
-		public function removeAllRoute() {
248
-			$this->logger->info('Remove all routes from the configuration');
249
-			$this->pattern  = array();
250
-			$this->callback = array();
251
-			$this->routes = array();
252
-			return $this;
253
-		}
254
-
255
-
256
-		/**
257
-	     * Set the route URI to use later
258
-	     * @param string $uri the route URI, if is empty will determine automatically
259
-	     * @return object
260
-	     */
261
-	    public function setRouteUri($uri = ''){
262
-	    	$routeUri = '';
263
-	    	if(! empty($uri)){
264
-	    		$routeUri = $uri;
265
-	    	}
266
-	    	//if the application is running in CLI mode use the first argument
267
-			else if(IS_CLI && isset($_SERVER['argv'][1])){
268
-				$routeUri = $_SERVER['argv'][1];
269
-			}
270
-			else if(isset($_SERVER['REQUEST_URI'])){
271
-				$routeUri = $_SERVER['REQUEST_URI'];
272
-			}
273
-			$this->logger->debug('Check if URL suffix is enabled in the configuration');
274
-			//remove url suffix from the request URI
275
-			$suffix = get_config('url_suffix');
276
-			if ($suffix) {
277
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
278
-				$routeUri = str_ireplace($suffix, '', $routeUri);
279
-			} 
280
-			if (strpos($routeUri, '?') !== false){
281
-				$routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
282
-			}
283
-			$this->uri = trim($routeUri, $this->uriTrim);
284
-			return $this;
285
-	    }
286
-
287
-	     /**
288
-		 * Set the route segments informations
289
-		 * @param array $segements the route segments information
290
-		 * 
291
-		 * @return object
292
-		 */
293
-		public function setRouteSegments(array $segments = array()){
294
-			if(! empty($segments)){
295
-				$this->segments = $segments;
296
-			} else if (!empty($this->uri)) {
297
-				$this->segments = explode('/', $this->uri);
298
-			}
299
-			$segment = $this->segments;
300
-			$baseUrl = get_config('base_url');
301
-			//check if the app is not in DOCUMENT_ROOT
302
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
303
-				array_shift($segment);
304
-				$this->segments = $segment;
305
-			}
306
-			$this->logger->debug('Check if the request URI contains the front controller');
307
-			if(isset($segment[0]) && $segment[0] == SELF){
308
-				$this->logger->info('The request URI contains the front controller');
309
-				array_shift($segment);
310
-				$this->segments = $segment;
311
-			}
312
-			return $this;
313
-		}
314
-
315
-		/**
316
-		 * Setting the route parameters like module, controller, method, argument
317
-		 * @return object the current instance
318
-		 */
319
-		public function determineRouteParamsInformation() {
320
-			$this->logger->debug('Routing process start ...');
140
+        /**
141
+         * Get the controller name
142
+         * @return string
143
+         */
144
+        public function getController(){
145
+            return $this->controller;
146
+        }
147
+
148
+        /**
149
+         * Get the controller file path
150
+         * @return string
151
+         */
152
+        public function getControllerPath(){
153
+            return $this->controllerPath;
154
+        }
155
+
156
+        /**
157
+         * Get the controller method
158
+         * @return string
159
+         */
160
+        public function getMethod(){
161
+            return $this->method;
162
+        }
163
+
164
+        /**
165
+         * Get the request arguments
166
+         * @return array
167
+         */
168
+        public function getArgs(){
169
+            return $this->args;
170
+        }
171
+
172
+        /**
173
+         * Get the URL segments array
174
+         * @return array
175
+         */
176
+        public function getSegments(){
177
+            return $this->segments;
178
+        }
179
+
180
+        /**
181
+         * Return the Log instance
182
+         * @return Log
183
+         */
184
+        public function getLogger(){
185
+            return $this->logger;
186
+        }
187
+
188
+        /**
189
+         * Set the log instance
190
+         * @param Log $logger the log object
191
+         * @return object
192
+         */
193
+        public function setLogger($logger){
194
+            $this->logger = $logger;
195
+            return $this;
196
+        }
197
+
198
+        /**
199
+         * Get the route URI
200
+         * @return string
201
+         */
202
+        public function getRouteUri(){
203
+            return $this->uri;
204
+        }
205
+
206
+        /**
207
+         * Add the URI and callback to the list of URIs to validate
208
+         *
209
+         * @param string $uri the request URI
210
+         * @param string $callback the callback function
211
+         *
212
+         * @return object the current instance
213
+         */
214
+        public function add($uri, $callback) {
215
+            $uri = trim($uri, $this->uriTrim);
216
+            if(in_array($uri, $this->pattern)){
217
+                $this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
218
+            }
219
+            $this->pattern[] = $uri;
220
+            $this->callback[] = $callback;
221
+            return $this;
222
+        }
223
+
224
+        /**
225
+         * Remove the route configuration
226
+         *
227
+         * @param string $uri the URI
228
+         *
229
+         * @return object the current instance
230
+         */
231
+        public function removeRoute($uri) {
232
+            $index  = array_search($uri, $this->pattern, true);
233
+            if($index !== false){
234
+                $this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
235
+                unset($this->pattern[$index]);
236
+                unset($this->callback[$index]);
237
+            }
238
+            return $this;
239
+        }
240
+
241
+
242
+        /**
243
+         * Remove all the routes from the configuration
244
+         *
245
+         * @return object the current instance
246
+         */
247
+        public function removeAllRoute() {
248
+            $this->logger->info('Remove all routes from the configuration');
249
+            $this->pattern  = array();
250
+            $this->callback = array();
251
+            $this->routes = array();
252
+            return $this;
253
+        }
254
+
255
+
256
+        /**
257
+         * Set the route URI to use later
258
+         * @param string $uri the route URI, if is empty will determine automatically
259
+         * @return object
260
+         */
261
+        public function setRouteUri($uri = ''){
262
+            $routeUri = '';
263
+            if(! empty($uri)){
264
+                $routeUri = $uri;
265
+            }
266
+            //if the application is running in CLI mode use the first argument
267
+            else if(IS_CLI && isset($_SERVER['argv'][1])){
268
+                $routeUri = $_SERVER['argv'][1];
269
+            }
270
+            else if(isset($_SERVER['REQUEST_URI'])){
271
+                $routeUri = $_SERVER['REQUEST_URI'];
272
+            }
273
+            $this->logger->debug('Check if URL suffix is enabled in the configuration');
274
+            //remove url suffix from the request URI
275
+            $suffix = get_config('url_suffix');
276
+            if ($suffix) {
277
+                $this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
278
+                $routeUri = str_ireplace($suffix, '', $routeUri);
279
+            } 
280
+            if (strpos($routeUri, '?') !== false){
281
+                $routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
282
+            }
283
+            $this->uri = trim($routeUri, $this->uriTrim);
284
+            return $this;
285
+        }
286
+
287
+            /**
288
+             * Set the route segments informations
289
+             * @param array $segements the route segments information
290
+             * 
291
+             * @return object
292
+             */
293
+        public function setRouteSegments(array $segments = array()){
294
+            if(! empty($segments)){
295
+                $this->segments = $segments;
296
+            } else if (!empty($this->uri)) {
297
+                $this->segments = explode('/', $this->uri);
298
+            }
299
+            $segment = $this->segments;
300
+            $baseUrl = get_config('base_url');
301
+            //check if the app is not in DOCUMENT_ROOT
302
+            if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
303
+                array_shift($segment);
304
+                $this->segments = $segment;
305
+            }
306
+            $this->logger->debug('Check if the request URI contains the front controller');
307
+            if(isset($segment[0]) && $segment[0] == SELF){
308
+                $this->logger->info('The request URI contains the front controller');
309
+                array_shift($segment);
310
+                $this->segments = $segment;
311
+            }
312
+            return $this;
313
+        }
314
+
315
+        /**
316
+         * Setting the route parameters like module, controller, method, argument
317
+         * @return object the current instance
318
+         */
319
+        public function determineRouteParamsInformation() {
320
+            $this->logger->debug('Routing process start ...');
321 321
 			
322
-			//determine route parameters using the config
323
-			$this->determineRouteParamsFromConfig();
322
+            //determine route parameters using the config
323
+            $this->determineRouteParamsFromConfig();
324 324
 			
325
-			//if can not determine the module/controller/method via the defined routes configuration we will use
326
-			//the URL like http://domain.com/module/controller/method/arg1/arg2
327
-			if(! $this->controller){
328
-				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
329
-				//determine route parameters using the REQUEST_URI param
330
-				$this->determineRouteParamsFromRequestUri();
331
-			}
332
-			//Set the controller file path if not yet set
333
-			$this->setControllerFilePath();
334
-			$this->logger->debug('Routing process end.');
335
-
336
-			return $this;
337
-		}
325
+            //if can not determine the module/controller/method via the defined routes configuration we will use
326
+            //the URL like http://domain.com/module/controller/method/arg1/arg2
327
+            if(! $this->controller){
328
+                $this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
329
+                //determine route parameters using the REQUEST_URI param
330
+                $this->determineRouteParamsFromRequestUri();
331
+            }
332
+            //Set the controller file path if not yet set
333
+            $this->setControllerFilePath();
334
+            $this->logger->debug('Routing process end.');
335
+
336
+            return $this;
337
+        }
338 338
 	
339
-		 /**
340
-		 * Routing the request to the correspondant module/controller/method if exists
341
-		 * otherwise send 404 error.
342
-		 */
343
-	    public function processRequest(){
344
-	    	//Setting the route URI
345
-			$this->setRouteUri();
346
-
347
-			//setting route segments
348
-			$this->setRouteSegments();
349
-
350
-			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
351
-
352
-	    	//determine the route parameters information
353
-	    	$this->determineRouteParamsInformation();
354
-
355
-	    	$e404 = false;
356
-	    	$classFilePath = $this->controllerPath;
357
-	    	$controller = ucfirst($this->controller);
358
-	    	$this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
359
-	    	$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
339
+            /**
340
+             * Routing the request to the correspondant module/controller/method if exists
341
+             * otherwise send 404 error.
342
+             */
343
+        public function processRequest(){
344
+            //Setting the route URI
345
+            $this->setRouteUri();
346
+
347
+            //setting route segments
348
+            $this->setRouteSegments();
349
+
350
+            $this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
351
+
352
+            //determine the route parameters information
353
+            $this->determineRouteParamsInformation();
354
+
355
+            $e404 = false;
356
+            $classFilePath = $this->controllerPath;
357
+            $controller = ucfirst($this->controller);
358
+            $this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
359
+            $this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
360 360
 	    	
361
-			if(file_exists($classFilePath)){
362
-				require_once $classFilePath;
363
-				if(! class_exists($controller, false)){
364
-					$e404 = true;
365
-					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
366
-				}
367
-				else{
368
-					$controllerInstance = new $controller();
369
-					$controllerMethod = $this->getMethod();
370
-					if(! method_exists($controllerInstance, $controllerMethod)){
371
-						$e404 = true;
372
-						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
373
-					}
374
-					else{
375
-						$this->logger->info('Routing data is set correctly now GO!');
376
-						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
377
-						//render the final page to user
378
-						$this->logger->info('Render the final output to the browser');
379
-						get_instance()->response->renderFinalPage();
380
-					}
381
-				}
382
-			}
383
-			else{
384
-				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
385
-				$e404 = true;
386
-			}
387
-			if($e404){
388
-				if(IS_CLI){
389
-					set_http_status_header(404);
390
-					echo 'Error 404: page not found.';
391
-				} else {
392
-					$response =& class_loader('Response', 'classes');
393
-					$response->send404();
394
-				}
395
-			}
396
-	    }
397
-
398
-
399
-	    /**
400
-	    * Setting the route configuration using the configuration file and additional configuration from param
401
-	    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
402
-	    * @param boolean $useConfigFile whether to use route configuration file
403
-		* @return object
404
-	    */
405
-	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
406
-	        $route = array();
407
-	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
408
-	            require_once CONFIG_PATH . 'routes.php';
409
-	        }
410
-	        $route = array_merge($route, $overwriteConfig);
411
-	        $this->routes = $route;
412
-	        //if route is empty remove all configuration
413
-	        if(empty($route)){
414
-	        	$this->removeAllRoute();
415
-	        }
416
-			return $this;
417
-	    }
418
-
419
-	     /**
420
-		 * Get the route configuration
421
-		 * @return array
422
-		 */
423
-		public function getRouteConfiguration(){
424
-			return $this->routes;
425
-		}
361
+            if(file_exists($classFilePath)){
362
+                require_once $classFilePath;
363
+                if(! class_exists($controller, false)){
364
+                    $e404 = true;
365
+                    $this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
366
+                }
367
+                else{
368
+                    $controllerInstance = new $controller();
369
+                    $controllerMethod = $this->getMethod();
370
+                    if(! method_exists($controllerInstance, $controllerMethod)){
371
+                        $e404 = true;
372
+                        $this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
373
+                    }
374
+                    else{
375
+                        $this->logger->info('Routing data is set correctly now GO!');
376
+                        call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
377
+                        //render the final page to user
378
+                        $this->logger->info('Render the final output to the browser');
379
+                        get_instance()->response->renderFinalPage();
380
+                    }
381
+                }
382
+            }
383
+            else{
384
+                $this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
385
+                $e404 = true;
386
+            }
387
+            if($e404){
388
+                if(IS_CLI){
389
+                    set_http_status_header(404);
390
+                    echo 'Error 404: page not found.';
391
+                } else {
392
+                    $response =& class_loader('Response', 'classes');
393
+                    $response->send404();
394
+                }
395
+            }
396
+        }
397
+
398
+
399
+        /**
400
+         * Setting the route configuration using the configuration file and additional configuration from param
401
+         * @param array $overwriteConfig the additional configuration to overwrite with the existing one
402
+         * @param boolean $useConfigFile whether to use route configuration file
403
+         * @return object
404
+         */
405
+        public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
406
+            $route = array();
407
+            if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
408
+                require_once CONFIG_PATH . 'routes.php';
409
+            }
410
+            $route = array_merge($route, $overwriteConfig);
411
+            $this->routes = $route;
412
+            //if route is empty remove all configuration
413
+            if(empty($route)){
414
+                $this->removeAllRoute();
415
+            }
416
+            return $this;
417
+        }
418
+
419
+            /**
420
+             * Get the route configuration
421
+             * @return array
422
+             */
423
+        public function getRouteConfiguration(){
424
+            return $this->routes;
425
+        }
426 426
 
427 427
 	    
428
-	    /**
429
-	     * Set the controller file path if is not set
430
-	     * @param string $path the file path if is null will using the route 
431
-	     * information
432
-	     *
433
-	     * @return object the current instance
434
-	     */
435
-	    public function setControllerFilePath($path = null){
436
-	    	if($path !== null){
437
-	    		$this->controllerPath = $path;
438
-	    		return $this;
439
-	    	}
440
-	    	//did we set the controller, so set the controller path
441
-			if($this->controller && ! $this->controllerPath){
442
-				$this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
443
-				$controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
444
-				//if the controller is in module
445
-				if($this->module){
446
-					$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
447
-					if($path !== false){
448
-						$controllerPath = $path;
449
-					}
450
-				}
451
-				$this->controllerPath = $controllerPath;
452
-			}
453
-			return $this;
454
-	    }
455
-
456
-	    /**
457
-	     * Determine the route parameters from route configuration
458
-	     * @return void
459
-	     */
460
-	    protected function determineRouteParamsFromConfig(){
461
-	    	$uri = implode('/', $this->segments);
462
-	    	/*
428
+        /**
429
+         * Set the controller file path if is not set
430
+         * @param string $path the file path if is null will using the route 
431
+         * information
432
+         *
433
+         * @return object the current instance
434
+         */
435
+        public function setControllerFilePath($path = null){
436
+            if($path !== null){
437
+                $this->controllerPath = $path;
438
+                return $this;
439
+            }
440
+            //did we set the controller, so set the controller path
441
+            if($this->controller && ! $this->controllerPath){
442
+                $this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
443
+                $controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
444
+                //if the controller is in module
445
+                if($this->module){
446
+                    $path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
447
+                    if($path !== false){
448
+                        $controllerPath = $path;
449
+                    }
450
+                }
451
+                $this->controllerPath = $controllerPath;
452
+            }
453
+            return $this;
454
+        }
455
+
456
+        /**
457
+         * Determine the route parameters from route configuration
458
+         * @return void
459
+         */
460
+        protected function determineRouteParamsFromConfig(){
461
+            $uri = implode('/', $this->segments);
462
+            /*
463 463
 	   		* Generics routes patterns
464 464
 	    	*/
465
-			$pattern = array(':num', ':alpha', ':alnum', ':any');
466
-			$replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
467
-
468
-			$this->logger->debug(
469
-									'Begin to loop in the predefined routes configuration ' 
470
-									. 'to check if the current request match'
471
-									);
472
-
473
-			// Cycle through the URIs stored in the array
474
-			foreach ($this->pattern as $index => $uriList) {
475
-				$uriList = str_ireplace($pattern, $replace, $uriList);
476
-				// Check for an existant matching URI
477
-				if (preg_match("#^$uriList$#", $uri, $args)) {
478
-					$this->logger->info(
479
-										'Route found for request URI [' . $uri . '] using the predefined configuration '
480
-										. ' [' . $this->pattern[$index] . '] --> [' . $this->callback[$index] . ']'
481
-									);
482
-					array_shift($args);
483
-					//check if this contains an module
484
-					$moduleControllerMethod = explode('#', $this->callback[$index]);
485
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
486
-						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
487
-						$this->module = $moduleControllerMethod[0];
488
-						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
489
-					}
490
-					else{
491
-						$this->logger->info('The current request does not use the module');
492
-						$moduleControllerMethod = explode('@', $this->callback[$index]);
493
-					}
494
-					if(is_array($moduleControllerMethod)){
495
-						if(isset($moduleControllerMethod[0])){
496
-							$this->controller = $moduleControllerMethod[0];	
497
-						}
498
-						if(isset($moduleControllerMethod[1])){
499
-							$this->method = $moduleControllerMethod[1];
500
-						}
501
-						$this->args = $args;
502
-					}
503
-					// stop here
504
-					break;
505
-				}
506
-			}
507
-
508
-			//first if the controller is not set and the module is set use the module name as the controller
509
-			if(! $this->controller && $this->module){
510
-				$this->logger->info(
511
-									'After loop in predefined routes configuration, 
465
+            $pattern = array(':num', ':alpha', ':alnum', ':any');
466
+            $replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
467
+
468
+            $this->logger->debug(
469
+                                    'Begin to loop in the predefined routes configuration ' 
470
+                                    . 'to check if the current request match'
471
+                                    );
472
+
473
+            // Cycle through the URIs stored in the array
474
+            foreach ($this->pattern as $index => $uriList) {
475
+                $uriList = str_ireplace($pattern, $replace, $uriList);
476
+                // Check for an existant matching URI
477
+                if (preg_match("#^$uriList$#", $uri, $args)) {
478
+                    $this->logger->info(
479
+                                        'Route found for request URI [' . $uri . '] using the predefined configuration '
480
+                                        . ' [' . $this->pattern[$index] . '] --> [' . $this->callback[$index] . ']'
481
+                                    );
482
+                    array_shift($args);
483
+                    //check if this contains an module
484
+                    $moduleControllerMethod = explode('#', $this->callback[$index]);
485
+                    if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
486
+                        $this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
487
+                        $this->module = $moduleControllerMethod[0];
488
+                        $moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
489
+                    }
490
+                    else{
491
+                        $this->logger->info('The current request does not use the module');
492
+                        $moduleControllerMethod = explode('@', $this->callback[$index]);
493
+                    }
494
+                    if(is_array($moduleControllerMethod)){
495
+                        if(isset($moduleControllerMethod[0])){
496
+                            $this->controller = $moduleControllerMethod[0];	
497
+                        }
498
+                        if(isset($moduleControllerMethod[1])){
499
+                            $this->method = $moduleControllerMethod[1];
500
+                        }
501
+                        $this->args = $args;
502
+                    }
503
+                    // stop here
504
+                    break;
505
+                }
506
+            }
507
+
508
+            //first if the controller is not set and the module is set use the module name as the controller
509
+            if(! $this->controller && $this->module){
510
+                $this->logger->info(
511
+                                    'After loop in predefined routes configuration, 
512 512
 									the module name is set but the controller is not set, 
513 513
 									so we will use module as the controller'
514
-								);
515
-				$this->controller = $this->module;
516
-			}
517
-	    }
518
-
519
-	    /**
520
-	     * Determine the route parameters using the server variable "REQUEST_URI"
521
-	     * @return void
522
-	     */
523
-	    protected function determineRouteParamsFromRequestUri(){
524
-	    	$segment = $this->segments;
525
-	    	$nbSegment = count($segment);
526
-			//if segment is null so means no need to perform
527
-			if($nbSegment > 0){
528
-				//get the module list
529
-				$modules = Module::getModuleList();
530
-				//first check if no module
531
-				if(empty($modules)){
532
-					$this->logger->info('No module was loaded will skip the module checking');
533
-					//the application don't use module
534
-					//controller
535
-					if(isset($segment[0])){
536
-						$this->controller = $segment[0];
537
-						array_shift($segment);
538
-					}
539
-					//method
540
-					if(isset($segment[0])){
541
-						$this->method = $segment[0];
542
-						array_shift($segment);
543
-					}
544
-					//args
545
-					$this->args = $segment;
546
-				}
547
-				else{
548
-					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
549
-					if(in_array($segment[0], $modules)){
550
-						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
551
-						$this->module = $segment[0];
552
-						array_shift($segment);
553
-						//check if the second arg is the controller from module
554
-						if(isset($segment[0])){
555
-							$this->controller = $segment[0];
556
-							//check if the request use the same module name and controller
557
-							$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
558
-							if(! $path){
559
-								$this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
560
-								$this->controller = $this->module;
561
-							}
562
-							else{
563
-								$this->controllerPath = $path;
564
-								array_shift($segment);
565
-							}
566
-						}
567
-						//check for method
568
-						if(isset($segment[0])){
569
-							$this->method = $segment[0];
570
-							array_shift($segment);
571
-						}
572
-						//the remaining is for args
573
-						$this->args = $segment;
574
-					}
575
-					else{
576
-						$this->logger->info('The current request information is not found in the module list');
577
-						//controller
578
-						if(isset($segment[0])){
579
-							$this->controller = $segment[0];
580
-							array_shift($segment);
581
-						}
582
-						//method
583
-						if(isset($segment[0])){
584
-							$this->method = $segment[0];
585
-							array_shift($segment);
586
-						}
587
-						//args
588
-						$this->args = $segment;
589
-					}
590
-				}
591
-				if(! $this->controller && $this->module){
592
-					$this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
593
-					$this->controller = $this->module;
594
-				}
595
-			}
596
-	    }
597
-
598
-	    /**
599
-	     * Set the route informations using the configuration
600
-	     *
601
-	     * @return object the current instance
602
-	     */
603
-	    protected function setRouteConfigurationInfos(){
604
-	    	//adding route
605
-			foreach($this->routes as $pattern => $callback){
606
-				$this->add($pattern, $callback);
607
-			}
608
-			return $this;
609
-		}
610
-
611
-		/**
612
-	     * Set the Log instance using argument or create new instance
613
-	     * @param object $logger the Log instance if not null
614
-	     */
615
-	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
616
-	      if ($logger !== null){
617
-	        $this->logger = $logger;
618
-	      }
619
-	      else{
620
-	          $this->logger =& class_loader('Log', 'classes');
621
-	          $this->logger->setLogger('Library::Router');
622
-	      }
623
-	    }
624
-	}
514
+                                );
515
+                $this->controller = $this->module;
516
+            }
517
+        }
518
+
519
+        /**
520
+         * Determine the route parameters using the server variable "REQUEST_URI"
521
+         * @return void
522
+         */
523
+        protected function determineRouteParamsFromRequestUri(){
524
+            $segment = $this->segments;
525
+            $nbSegment = count($segment);
526
+            //if segment is null so means no need to perform
527
+            if($nbSegment > 0){
528
+                //get the module list
529
+                $modules = Module::getModuleList();
530
+                //first check if no module
531
+                if(empty($modules)){
532
+                    $this->logger->info('No module was loaded will skip the module checking');
533
+                    //the application don't use module
534
+                    //controller
535
+                    if(isset($segment[0])){
536
+                        $this->controller = $segment[0];
537
+                        array_shift($segment);
538
+                    }
539
+                    //method
540
+                    if(isset($segment[0])){
541
+                        $this->method = $segment[0];
542
+                        array_shift($segment);
543
+                    }
544
+                    //args
545
+                    $this->args = $segment;
546
+                }
547
+                else{
548
+                    $this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
549
+                    if(in_array($segment[0], $modules)){
550
+                        $this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
551
+                        $this->module = $segment[0];
552
+                        array_shift($segment);
553
+                        //check if the second arg is the controller from module
554
+                        if(isset($segment[0])){
555
+                            $this->controller = $segment[0];
556
+                            //check if the request use the same module name and controller
557
+                            $path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
558
+                            if(! $path){
559
+                                $this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
560
+                                $this->controller = $this->module;
561
+                            }
562
+                            else{
563
+                                $this->controllerPath = $path;
564
+                                array_shift($segment);
565
+                            }
566
+                        }
567
+                        //check for method
568
+                        if(isset($segment[0])){
569
+                            $this->method = $segment[0];
570
+                            array_shift($segment);
571
+                        }
572
+                        //the remaining is for args
573
+                        $this->args = $segment;
574
+                    }
575
+                    else{
576
+                        $this->logger->info('The current request information is not found in the module list');
577
+                        //controller
578
+                        if(isset($segment[0])){
579
+                            $this->controller = $segment[0];
580
+                            array_shift($segment);
581
+                        }
582
+                        //method
583
+                        if(isset($segment[0])){
584
+                            $this->method = $segment[0];
585
+                            array_shift($segment);
586
+                        }
587
+                        //args
588
+                        $this->args = $segment;
589
+                    }
590
+                }
591
+                if(! $this->controller && $this->module){
592
+                    $this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
593
+                    $this->controller = $this->module;
594
+                }
595
+            }
596
+        }
597
+
598
+        /**
599
+         * Set the route informations using the configuration
600
+         *
601
+         * @return object the current instance
602
+         */
603
+        protected function setRouteConfigurationInfos(){
604
+            //adding route
605
+            foreach($this->routes as $pattern => $callback){
606
+                $this->add($pattern, $callback);
607
+            }
608
+            return $this;
609
+        }
610
+
611
+        /**
612
+         * Set the Log instance using argument or create new instance
613
+         * @param object $logger the Log instance if not null
614
+         */
615
+        protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
616
+            if ($logger !== null){
617
+            $this->logger = $logger;
618
+            }
619
+            else{
620
+                $this->logger =& class_loader('Log', 'classes');
621
+                $this->logger->setLogger('Library::Router');
622
+            }
623
+        }
624
+    }
Please login to merge, or discard this patch.
Spacing   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
 		/**
97 97
 		 * Construct the new Router instance
98 98
 		 */
99
-		public function __construct(){
99
+		public function __construct() {
100 100
 			$this->setLoggerFromParamOrCreateNewInstance(null);
101 101
 			
102 102
 			//loading routes for module
103 103
 			$moduleRouteList = array();
104 104
 			$modulesRoutes = Module::getModulesRoutes();
105
-			if($modulesRoutes && is_array($modulesRoutes)){
105
+			if ($modulesRoutes && is_array($modulesRoutes)) {
106 106
 				$moduleRouteList = $modulesRoutes;
107 107
 				unset($modulesRoutes);
108 108
 			}
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 		 * Get the route patterns
118 118
 		 * @return array
119 119
 		 */
120
-		public function getPattern(){
120
+		public function getPattern() {
121 121
 			return $this->pattern;
122 122
 		}
123 123
 
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		 * Get the route callbacks
126 126
 		 * @return array
127 127
 		 */
128
-		public function getCallback(){
128
+		public function getCallback() {
129 129
 			return $this->callback;
130 130
 		}
131 131
 
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		 * Get the module name
134 134
 		 * @return string
135 135
 		 */
136
-		public function getModule(){
136
+		public function getModule() {
137 137
 			return $this->module;
138 138
 		}
139 139
 		
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 		 * Get the controller name
142 142
 		 * @return string
143 143
 		 */
144
-		public function getController(){
144
+		public function getController() {
145 145
 			return $this->controller;
146 146
 		}
147 147
 
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 		 * Get the controller file path
150 150
 		 * @return string
151 151
 		 */
152
-		public function getControllerPath(){
152
+		public function getControllerPath() {
153 153
 			return $this->controllerPath;
154 154
 		}
155 155
 
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 		 * Get the controller method
158 158
 		 * @return string
159 159
 		 */
160
-		public function getMethod(){
160
+		public function getMethod() {
161 161
 			return $this->method;
162 162
 		}
163 163
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		 * Get the request arguments
166 166
 		 * @return array
167 167
 		 */
168
-		public function getArgs(){
168
+		public function getArgs() {
169 169
 			return $this->args;
170 170
 		}
171 171
 
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 		 * Get the URL segments array
174 174
 		 * @return array
175 175
 		 */
176
-		public function getSegments(){
176
+		public function getSegments() {
177 177
 			return $this->segments;
178 178
 		}
179 179
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 	     * Return the Log instance
182 182
 	     * @return Log
183 183
 	     */
184
-	    public function getLogger(){
184
+	    public function getLogger() {
185 185
 	      return $this->logger;
186 186
 	    }
187 187
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 	     * @param Log $logger the log object
191 191
 		 * @return object
192 192
 	     */
193
-	    public function setLogger($logger){
193
+	    public function setLogger($logger) {
194 194
 	      $this->logger = $logger;
195 195
 	      return $this;
196 196
 	    }
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 		 * Get the route URI
200 200
 		 * @return string
201 201
 		 */
202
-		public function getRouteUri(){
202
+		public function getRouteUri() {
203 203
 			return $this->uri;
204 204
 		}
205 205
 
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		*/
214 214
 		public function add($uri, $callback) {
215 215
 			$uri = trim($uri, $this->uriTrim);
216
-			if(in_array($uri, $this->pattern)){
216
+			if (in_array($uri, $this->pattern)) {
217 217
 				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
218 218
 			}
219 219
 			$this->pattern[] = $uri;
@@ -229,8 +229,8 @@  discard block
 block discarded – undo
229 229
 		* @return object the current instance
230 230
 		*/
231 231
 		public function removeRoute($uri) {
232
-			$index  = array_search($uri, $this->pattern, true);
233
-			if($index !== false){
232
+			$index = array_search($uri, $this->pattern, true);
233
+			if ($index !== false) {
234 234
 				$this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
235 235
 				unset($this->pattern[$index]);
236 236
 				unset($this->callback[$index]);
@@ -258,26 +258,26 @@  discard block
 block discarded – undo
258 258
 	     * @param string $uri the route URI, if is empty will determine automatically
259 259
 	     * @return object
260 260
 	     */
261
-	    public function setRouteUri($uri = ''){
261
+	    public function setRouteUri($uri = '') {
262 262
 	    	$routeUri = '';
263
-	    	if(! empty($uri)){
263
+	    	if (!empty($uri)) {
264 264
 	    		$routeUri = $uri;
265 265
 	    	}
266 266
 	    	//if the application is running in CLI mode use the first argument
267
-			else if(IS_CLI && isset($_SERVER['argv'][1])){
267
+			else if (IS_CLI && isset($_SERVER['argv'][1])) {
268 268
 				$routeUri = $_SERVER['argv'][1];
269 269
 			}
270
-			else if(isset($_SERVER['REQUEST_URI'])){
270
+			else if (isset($_SERVER['REQUEST_URI'])) {
271 271
 				$routeUri = $_SERVER['REQUEST_URI'];
272 272
 			}
273 273
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
274 274
 			//remove url suffix from the request URI
275 275
 			$suffix = get_config('url_suffix');
276 276
 			if ($suffix) {
277
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
277
+				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']');
278 278
 				$routeUri = str_ireplace($suffix, '', $routeUri);
279 279
 			} 
280
-			if (strpos($routeUri, '?') !== false){
280
+			if (strpos($routeUri, '?') !== false) {
281 281
 				$routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
282 282
 			}
283 283
 			$this->uri = trim($routeUri, $this->uriTrim);
@@ -290,8 +290,8 @@  discard block
 block discarded – undo
290 290
 		 * 
291 291
 		 * @return object
292 292
 		 */
293
-		public function setRouteSegments(array $segments = array()){
294
-			if(! empty($segments)){
293
+		public function setRouteSegments(array $segments = array()) {
294
+			if (!empty($segments)) {
295 295
 				$this->segments = $segments;
296 296
 			} else if (!empty($this->uri)) {
297 297
 				$this->segments = explode('/', $this->uri);
@@ -299,12 +299,12 @@  discard block
 block discarded – undo
299 299
 			$segment = $this->segments;
300 300
 			$baseUrl = get_config('base_url');
301 301
 			//check if the app is not in DOCUMENT_ROOT
302
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
302
+			if (isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false) {
303 303
 				array_shift($segment);
304 304
 				$this->segments = $segment;
305 305
 			}
306 306
 			$this->logger->debug('Check if the request URI contains the front controller');
307
-			if(isset($segment[0]) && $segment[0] == SELF){
307
+			if (isset($segment[0]) && $segment[0] == SELF) {
308 308
 				$this->logger->info('The request URI contains the front controller');
309 309
 				array_shift($segment);
310 310
 				$this->segments = $segment;
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 			
325 325
 			//if can not determine the module/controller/method via the defined routes configuration we will use
326 326
 			//the URL like http://domain.com/module/controller/method/arg1/arg2
327
-			if(! $this->controller){
327
+			if (!$this->controller) {
328 328
 				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
329 329
 				//determine route parameters using the REQUEST_URI param
330 330
 				$this->determineRouteParamsFromRequestUri();
@@ -340,14 +340,14 @@  discard block
 block discarded – undo
340 340
 		 * Routing the request to the correspondant module/controller/method if exists
341 341
 		 * otherwise send 404 error.
342 342
 		 */
343
-	    public function processRequest(){
343
+	    public function processRequest() {
344 344
 	    	//Setting the route URI
345 345
 			$this->setRouteUri();
346 346
 
347 347
 			//setting route segments
348 348
 			$this->setRouteSegments();
349 349
 
350
-			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
350
+			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']');
351 351
 
352 352
 	    	//determine the route parameters information
353 353
 	    	$this->determineRouteParamsInformation();
@@ -358,20 +358,20 @@  discard block
 block discarded – undo
358 358
 	    	$this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
359 359
 	    	$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
360 360
 	    	
361
-			if(file_exists($classFilePath)){
361
+			if (file_exists($classFilePath)) {
362 362
 				require_once $classFilePath;
363
-				if(! class_exists($controller, false)){
363
+				if (!class_exists($controller, false)) {
364 364
 					$e404 = true;
365
-					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
365
+					$this->logger->warning('The controller file [' . $classFilePath . '] exists but does not contain the class [' . $controller . ']');
366 366
 				}
367
-				else{
367
+				else {
368 368
 					$controllerInstance = new $controller();
369 369
 					$controllerMethod = $this->getMethod();
370
-					if(! method_exists($controllerInstance, $controllerMethod)){
370
+					if (!method_exists($controllerInstance, $controllerMethod)) {
371 371
 						$e404 = true;
372 372
 						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
373 373
 					}
374
-					else{
374
+					else {
375 375
 						$this->logger->info('Routing data is set correctly now GO!');
376 376
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
377 377
 						//render the final page to user
@@ -380,16 +380,16 @@  discard block
 block discarded – undo
380 380
 					}
381 381
 				}
382 382
 			}
383
-			else{
383
+			else {
384 384
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
385 385
 				$e404 = true;
386 386
 			}
387
-			if($e404){
388
-				if(IS_CLI){
387
+			if ($e404) {
388
+				if (IS_CLI) {
389 389
 					set_http_status_header(404);
390 390
 					echo 'Error 404: page not found.';
391 391
 				} else {
392
-					$response =& class_loader('Response', 'classes');
392
+					$response = & class_loader('Response', 'classes');
393 393
 					$response->send404();
394 394
 				}
395 395
 			}
@@ -402,15 +402,15 @@  discard block
 block discarded – undo
402 402
 	    * @param boolean $useConfigFile whether to use route configuration file
403 403
 		* @return object
404 404
 	    */
405
-	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
405
+	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
406 406
 	        $route = array();
407
-	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
407
+	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')) {
408 408
 	            require_once CONFIG_PATH . 'routes.php';
409 409
 	        }
410 410
 	        $route = array_merge($route, $overwriteConfig);
411 411
 	        $this->routes = $route;
412 412
 	        //if route is empty remove all configuration
413
-	        if(empty($route)){
413
+	        if (empty($route)) {
414 414
 	        	$this->removeAllRoute();
415 415
 	        }
416 416
 			return $this;
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 		 * Get the route configuration
421 421
 		 * @return array
422 422
 		 */
423
-		public function getRouteConfiguration(){
423
+		public function getRouteConfiguration() {
424 424
 			return $this->routes;
425 425
 		}
426 426
 
@@ -432,19 +432,19 @@  discard block
 block discarded – undo
432 432
 	     *
433 433
 	     * @return object the current instance
434 434
 	     */
435
-	    public function setControllerFilePath($path = null){
436
-	    	if($path !== null){
435
+	    public function setControllerFilePath($path = null) {
436
+	    	if ($path !== null) {
437 437
 	    		$this->controllerPath = $path;
438 438
 	    		return $this;
439 439
 	    	}
440 440
 	    	//did we set the controller, so set the controller path
441
-			if($this->controller && ! $this->controllerPath){
441
+			if ($this->controller && !$this->controllerPath) {
442 442
 				$this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
443 443
 				$controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
444 444
 				//if the controller is in module
445
-				if($this->module){
445
+				if ($this->module) {
446 446
 					$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
447
-					if($path !== false){
447
+					if ($path !== false) {
448 448
 						$controllerPath = $path;
449 449
 					}
450 450
 				}
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 	     * Determine the route parameters from route configuration
458 458
 	     * @return void
459 459
 	     */
460
-	    protected function determineRouteParamsFromConfig(){
460
+	    protected function determineRouteParamsFromConfig() {
461 461
 	    	$uri = implode('/', $this->segments);
462 462
 	    	/*
463 463
 	   		* Generics routes patterns
@@ -482,20 +482,20 @@  discard block
 block discarded – undo
482 482
 					array_shift($args);
483 483
 					//check if this contains an module
484 484
 					$moduleControllerMethod = explode('#', $this->callback[$index]);
485
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
485
+					if (is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2) {
486 486
 						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
487 487
 						$this->module = $moduleControllerMethod[0];
488 488
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
489 489
 					}
490
-					else{
490
+					else {
491 491
 						$this->logger->info('The current request does not use the module');
492 492
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
493 493
 					}
494
-					if(is_array($moduleControllerMethod)){
495
-						if(isset($moduleControllerMethod[0])){
494
+					if (is_array($moduleControllerMethod)) {
495
+						if (isset($moduleControllerMethod[0])) {
496 496
 							$this->controller = $moduleControllerMethod[0];	
497 497
 						}
498
-						if(isset($moduleControllerMethod[1])){
498
+						if (isset($moduleControllerMethod[1])) {
499 499
 							$this->method = $moduleControllerMethod[1];
500 500
 						}
501 501
 						$this->args = $args;
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 			}
507 507
 
508 508
 			//first if the controller is not set and the module is set use the module name as the controller
509
-			if(! $this->controller && $this->module){
509
+			if (!$this->controller && $this->module) {
510 510
 				$this->logger->info(
511 511
 									'After loop in predefined routes configuration, 
512 512
 									the module name is set but the controller is not set, 
@@ -520,67 +520,67 @@  discard block
 block discarded – undo
520 520
 	     * Determine the route parameters using the server variable "REQUEST_URI"
521 521
 	     * @return void
522 522
 	     */
523
-	    protected function determineRouteParamsFromRequestUri(){
523
+	    protected function determineRouteParamsFromRequestUri() {
524 524
 	    	$segment = $this->segments;
525 525
 	    	$nbSegment = count($segment);
526 526
 			//if segment is null so means no need to perform
527
-			if($nbSegment > 0){
527
+			if ($nbSegment > 0) {
528 528
 				//get the module list
529 529
 				$modules = Module::getModuleList();
530 530
 				//first check if no module
531
-				if(empty($modules)){
531
+				if (empty($modules)) {
532 532
 					$this->logger->info('No module was loaded will skip the module checking');
533 533
 					//the application don't use module
534 534
 					//controller
535
-					if(isset($segment[0])){
535
+					if (isset($segment[0])) {
536 536
 						$this->controller = $segment[0];
537 537
 						array_shift($segment);
538 538
 					}
539 539
 					//method
540
-					if(isset($segment[0])){
540
+					if (isset($segment[0])) {
541 541
 						$this->method = $segment[0];
542 542
 						array_shift($segment);
543 543
 					}
544 544
 					//args
545 545
 					$this->args = $segment;
546 546
 				}
547
-				else{
547
+				else {
548 548
 					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
549
-					if(in_array($segment[0], $modules)){
549
+					if (in_array($segment[0], $modules)) {
550 550
 						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
551 551
 						$this->module = $segment[0];
552 552
 						array_shift($segment);
553 553
 						//check if the second arg is the controller from module
554
-						if(isset($segment[0])){
554
+						if (isset($segment[0])) {
555 555
 							$this->controller = $segment[0];
556 556
 							//check if the request use the same module name and controller
557 557
 							$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
558
-							if(! $path){
558
+							if (!$path) {
559 559
 								$this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
560 560
 								$this->controller = $this->module;
561 561
 							}
562
-							else{
562
+							else {
563 563
 								$this->controllerPath = $path;
564 564
 								array_shift($segment);
565 565
 							}
566 566
 						}
567 567
 						//check for method
568
-						if(isset($segment[0])){
568
+						if (isset($segment[0])) {
569 569
 							$this->method = $segment[0];
570 570
 							array_shift($segment);
571 571
 						}
572 572
 						//the remaining is for args
573 573
 						$this->args = $segment;
574 574
 					}
575
-					else{
575
+					else {
576 576
 						$this->logger->info('The current request information is not found in the module list');
577 577
 						//controller
578
-						if(isset($segment[0])){
578
+						if (isset($segment[0])) {
579 579
 							$this->controller = $segment[0];
580 580
 							array_shift($segment);
581 581
 						}
582 582
 						//method
583
-						if(isset($segment[0])){
583
+						if (isset($segment[0])) {
584 584
 							$this->method = $segment[0];
585 585
 							array_shift($segment);
586 586
 						}
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
 						$this->args = $segment;
589 589
 					}
590 590
 				}
591
-				if(! $this->controller && $this->module){
591
+				if (!$this->controller && $this->module) {
592 592
 					$this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
593 593
 					$this->controller = $this->module;
594 594
 				}
@@ -600,9 +600,9 @@  discard block
 block discarded – undo
600 600
 	     *
601 601
 	     * @return object the current instance
602 602
 	     */
603
-	    protected function setRouteConfigurationInfos(){
603
+	    protected function setRouteConfigurationInfos() {
604 604
 	    	//adding route
605
-			foreach($this->routes as $pattern => $callback){
605
+			foreach ($this->routes as $pattern => $callback) {
606 606
 				$this->add($pattern, $callback);
607 607
 			}
608 608
 			return $this;
@@ -612,12 +612,12 @@  discard block
 block discarded – undo
612 612
 	     * Set the Log instance using argument or create new instance
613 613
 	     * @param object $logger the Log instance if not null
614 614
 	     */
615
-	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
616
-	      if ($logger !== null){
615
+	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
616
+	      if ($logger !== null) {
617 617
 	        $this->logger = $logger;
618 618
 	      }
619
-	      else{
620
-	          $this->logger =& class_loader('Log', 'classes');
619
+	      else {
620
+	          $this->logger = & class_loader('Log', 'classes');
621 621
 	          $this->logger->setLogger('Library::Router');
622 622
 	      }
623 623
 	    }
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -266,8 +266,7 @@  discard block
 block discarded – undo
266 266
 	    	//if the application is running in CLI mode use the first argument
267 267
 			else if(IS_CLI && isset($_SERVER['argv'][1])){
268 268
 				$routeUri = $_SERVER['argv'][1];
269
-			}
270
-			else if(isset($_SERVER['REQUEST_URI'])){
269
+			} else if(isset($_SERVER['REQUEST_URI'])){
271 270
 				$routeUri = $_SERVER['REQUEST_URI'];
272 271
 			}
273 272
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
@@ -363,15 +362,13 @@  discard block
 block discarded – undo
363 362
 				if(! class_exists($controller, false)){
364 363
 					$e404 = true;
365 364
 					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
366
-				}
367
-				else{
365
+				} else{
368 366
 					$controllerInstance = new $controller();
369 367
 					$controllerMethod = $this->getMethod();
370 368
 					if(! method_exists($controllerInstance, $controllerMethod)){
371 369
 						$e404 = true;
372 370
 						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
373
-					}
374
-					else{
371
+					} else{
375 372
 						$this->logger->info('Routing data is set correctly now GO!');
376 373
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
377 374
 						//render the final page to user
@@ -379,8 +376,7 @@  discard block
 block discarded – undo
379 376
 						get_instance()->response->renderFinalPage();
380 377
 					}
381 378
 				}
382
-			}
383
-			else{
379
+			} else{
384 380
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
385 381
 				$e404 = true;
386 382
 			}
@@ -486,8 +482,7 @@  discard block
 block discarded – undo
486 482
 						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
487 483
 						$this->module = $moduleControllerMethod[0];
488 484
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
489
-					}
490
-					else{
485
+					} else{
491 486
 						$this->logger->info('The current request does not use the module');
492 487
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
493 488
 					}
@@ -543,8 +538,7 @@  discard block
 block discarded – undo
543 538
 					}
544 539
 					//args
545 540
 					$this->args = $segment;
546
-				}
547
-				else{
541
+				} else{
548 542
 					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
549 543
 					if(in_array($segment[0], $modules)){
550 544
 						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
@@ -558,8 +552,7 @@  discard block
 block discarded – undo
558 552
 							if(! $path){
559 553
 								$this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
560 554
 								$this->controller = $this->module;
561
-							}
562
-							else{
555
+							} else{
563 556
 								$this->controllerPath = $path;
564 557
 								array_shift($segment);
565 558
 							}
@@ -571,8 +564,7 @@  discard block
 block discarded – undo
571 564
 						}
572 565
 						//the remaining is for args
573 566
 						$this->args = $segment;
574
-					}
575
-					else{
567
+					} else{
576 568
 						$this->logger->info('The current request information is not found in the module list');
577 569
 						//controller
578 570
 						if(isset($segment[0])){
@@ -615,8 +607,7 @@  discard block
 block discarded – undo
615 607
 	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
616 608
 	      if ($logger !== null){
617 609
 	        $this->logger = $logger;
618
-	      }
619
-	      else{
610
+	      } else{
620 611
 	          $this->logger =& class_loader('Log', 'classes');
621 612
 	          $this->logger->setLogger('Library::Router');
622 613
 	      }
Please login to merge, or discard this patch.
core/classes/Security.php 3 patches
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -1,157 +1,157 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Security{
27
+    class Security{
28 28
 		
29
-		/**
30
-		 * The logger instance
31
-		 * @var Log
32
-		 */
33
-		private static $logger;
29
+        /**
30
+         * The logger instance
31
+         * @var Log
32
+         */
33
+        private static $logger;
34 34
 
35
-		/**
36
-		 * Get the logger singleton instance
37
-		 * @return Log the logger instance
38
-		 */
39
-		private static function getLogger(){
40
-			if(self::$logger == null){
41
-				self::$logger[0] =& class_loader('Log', 'classes');
42
-				self::$logger[0]->setLogger('Library::Security');
43
-			}
44
-			return self::$logger[0];
45
-		}
35
+        /**
36
+         * Get the logger singleton instance
37
+         * @return Log the logger instance
38
+         */
39
+        private static function getLogger(){
40
+            if(self::$logger == null){
41
+                self::$logger[0] =& class_loader('Log', 'classes');
42
+                self::$logger[0]->setLogger('Library::Security');
43
+            }
44
+            return self::$logger[0];
45
+        }
46 46
 
47 47
 
48
-		/**
49
-		 * This method is used to generate the CSRF token
50
-		 * @return string the generated CSRF token
51
-		 */
52
-		public static function generateCSRF(){
53
-			$logger = self::getLogger();
54
-			$logger->debug('Generation of CSRF ...');
48
+        /**
49
+         * This method is used to generate the CSRF token
50
+         * @return string the generated CSRF token
51
+         */
52
+        public static function generateCSRF(){
53
+            $logger = self::getLogger();
54
+            $logger->debug('Generation of CSRF ...');
55 55
 			
56
-			$key = get_config('csrf_key', 'csrf_key');
57
-			$expire = get_config('csrf_expire', 60);
58
-			$keyExpire = 'csrf_expire';
59
-			$currentTime = time();
60
-			if(Session::exists($key) && Session::exists($keyExpire) && Session::get($keyExpire) > $currentTime){
61
-				$logger->info('The CSRF token not yet expire just return it');
62
-				return Session::get($key);
63
-			}
64
-			else{
65
-				$newTime = $currentTime + $expire;
66
-				$token = sha1(uniqid()) . sha1(uniqid());
67
-				$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. '], token [' .$token. ']');
68
-				Session::set($keyExpire, $newTime);
69
-				Session::set($key, $token);
70
-				return Session::get($key);
71
-			}
72
-		}
56
+            $key = get_config('csrf_key', 'csrf_key');
57
+            $expire = get_config('csrf_expire', 60);
58
+            $keyExpire = 'csrf_expire';
59
+            $currentTime = time();
60
+            if(Session::exists($key) && Session::exists($keyExpire) && Session::get($keyExpire) > $currentTime){
61
+                $logger->info('The CSRF token not yet expire just return it');
62
+                return Session::get($key);
63
+            }
64
+            else{
65
+                $newTime = $currentTime + $expire;
66
+                $token = sha1(uniqid()) . sha1(uniqid());
67
+                $logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. '], token [' .$token. ']');
68
+                Session::set($keyExpire, $newTime);
69
+                Session::set($key, $token);
70
+                return Session::get($key);
71
+            }
72
+        }
73 73
 
74
-		/**
75
-		 * This method is used to check the CSRF if is valid, not yet expire, etc.
76
-		 * @return boolean true if valid, false if not valid
77
-		 */
78
-		public static function validateCSRF(){
79
-			$logger = self::getLogger();
80
-			$logger->debug('Validation of CSRF ...');
74
+        /**
75
+         * This method is used to check the CSRF if is valid, not yet expire, etc.
76
+         * @return boolean true if valid, false if not valid
77
+         */
78
+        public static function validateCSRF(){
79
+            $logger = self::getLogger();
80
+            $logger->debug('Validation of CSRF ...');
81 81
 				
82
-			$key = get_config('csrf_key', 'csrf_key');
83
-			$expire = get_config('csrf_expire', 60);
84
-			$keyExpire = 'csrf_expire';
85
-			$currentTime = time();
86
-			$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. ']');
87
-			if(! Session::exists($key) || Session::get($keyExpire) <= $currentTime){
88
-				$logger->warning('The CSRF session data is not valide');
89
-				return false;
90
-			}
91
-			//perform form data
92
-			//need use request->query() for best retrieve
93
-			//super instance
94
-			$obj = & get_instance();
95
-			$token = $obj->request->query($key);
96
-			if(! $token || $token !== Session::get($key) || Session::get($keyExpire) <= $currentTime){
97
-				$logger->warning('The CSRF data [' .$token. '] is not valide may be attacker do his job');
98
-				return false;
99
-			}
100
-			$logger->info('The CSRF data [' .$token. '] is valide the form data is safe continue');
101
-			//remove the token from session
102
-			Session::clear($key);
103
-			Session::clear($keyExpire);
104
-			return true;
105
-		}
82
+            $key = get_config('csrf_key', 'csrf_key');
83
+            $expire = get_config('csrf_expire', 60);
84
+            $keyExpire = 'csrf_expire';
85
+            $currentTime = time();
86
+            $logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. ']');
87
+            if(! Session::exists($key) || Session::get($keyExpire) <= $currentTime){
88
+                $logger->warning('The CSRF session data is not valide');
89
+                return false;
90
+            }
91
+            //perform form data
92
+            //need use request->query() for best retrieve
93
+            //super instance
94
+            $obj = & get_instance();
95
+            $token = $obj->request->query($key);
96
+            if(! $token || $token !== Session::get($key) || Session::get($keyExpire) <= $currentTime){
97
+                $logger->warning('The CSRF data [' .$token. '] is not valide may be attacker do his job');
98
+                return false;
99
+            }
100
+            $logger->info('The CSRF data [' .$token. '] is valide the form data is safe continue');
101
+            //remove the token from session
102
+            Session::clear($key);
103
+            Session::clear($keyExpire);
104
+            return true;
105
+        }
106 106
 		
107
-		/**
108
-		 * This method is used to check the whitelist IP address access
109
-		 */
110
-		 public static function checkWhiteListIpAccess(){
111
-			$logger = self::getLogger();
112
-			$logger->debug('Validation of the IP address access ...');
113
-			$logger->debug('Check if whitelist IP access is enabled in the configuration ...');
114
-			$isEnable = get_config('white_list_ip_enable', false);
115
-			if($isEnable){
116
-				$logger->info('Whitelist IP access is enabled in the configuration');
117
-				$list = get_config('white_list_ip_addresses', array());
118
-				if(! empty($list)){
119
-					//Can't use Loader::functions() at this time because teh "Loader" library is loader after the security prossessing
120
-					require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
121
-					$ip = get_ip();
122
-					if((count($list) == 1 && $list[0] == '*') || in_array($ip, $list)){
123
-						$logger->info('IP address ' . $ip . ' allowed using the wildcard "*" or the full IP');
124
-						//wildcard to access all ip address
125
-						return;
126
-					}
127
-					else{
128
-						// go through all whitelisted ips
129
-						foreach ($list as $ipaddr) {
130
-							// find the wild card * in whitelisted ip (f.e. find position in "127.0.*" or "127*")
131
-							$wildcardPosition = strpos($ipaddr, '*');
132
-							if ($wildcardPosition === false) {
133
-								// no wild card in whitelisted ip --continue searching
134
-								continue;
135
-							}
136
-							// cut ip at the position where we got the wild card on the whitelisted ip
137
-							// and add the wold card to get the same pattern
138
-							if (substr($ip, 0, $wildcardPosition) . '*' === $ipaddr) {
139
-								// f.e. we got
140
-								//  ip "127.0.0.1"
141
-								//  whitelisted ip "127.0.*"
142
-								// then we compared "127.0.*" with "127.0.*"
143
-								// return success
144
-								$logger->info('IP address ' . $ip . ' allowed using the wildcard like "x.x.x.*"');
145
-								return;
146
-							}
147
-						}
148
-						$logger->warning('IP address ' . $ip . ' is not allowed to access to this application');
149
-						show_error('Access to this application is not allowed');
150
-					}
151
-				}
152
-			}
153
-			else{
154
-				$logger->info('Whitelist IP access is not enabled in the configuration, ignore checking');
155
-			}
156
-		 }
157
-	}
107
+        /**
108
+         * This method is used to check the whitelist IP address access
109
+         */
110
+            public static function checkWhiteListIpAccess(){
111
+            $logger = self::getLogger();
112
+            $logger->debug('Validation of the IP address access ...');
113
+            $logger->debug('Check if whitelist IP access is enabled in the configuration ...');
114
+            $isEnable = get_config('white_list_ip_enable', false);
115
+            if($isEnable){
116
+                $logger->info('Whitelist IP access is enabled in the configuration');
117
+                $list = get_config('white_list_ip_addresses', array());
118
+                if(! empty($list)){
119
+                    //Can't use Loader::functions() at this time because teh "Loader" library is loader after the security prossessing
120
+                    require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
121
+                    $ip = get_ip();
122
+                    if((count($list) == 1 && $list[0] == '*') || in_array($ip, $list)){
123
+                        $logger->info('IP address ' . $ip . ' allowed using the wildcard "*" or the full IP');
124
+                        //wildcard to access all ip address
125
+                        return;
126
+                    }
127
+                    else{
128
+                        // go through all whitelisted ips
129
+                        foreach ($list as $ipaddr) {
130
+                            // find the wild card * in whitelisted ip (f.e. find position in "127.0.*" or "127*")
131
+                            $wildcardPosition = strpos($ipaddr, '*');
132
+                            if ($wildcardPosition === false) {
133
+                                // no wild card in whitelisted ip --continue searching
134
+                                continue;
135
+                            }
136
+                            // cut ip at the position where we got the wild card on the whitelisted ip
137
+                            // and add the wold card to get the same pattern
138
+                            if (substr($ip, 0, $wildcardPosition) . '*' === $ipaddr) {
139
+                                // f.e. we got
140
+                                //  ip "127.0.0.1"
141
+                                //  whitelisted ip "127.0.*"
142
+                                // then we compared "127.0.*" with "127.0.*"
143
+                                // return success
144
+                                $logger->info('IP address ' . $ip . ' allowed using the wildcard like "x.x.x.*"');
145
+                                return;
146
+                            }
147
+                        }
148
+                        $logger->warning('IP address ' . $ip . ' is not allowed to access to this application');
149
+                        show_error('Access to this application is not allowed');
150
+                    }
151
+                }
152
+            }
153
+            else{
154
+                $logger->info('Whitelist IP access is not enabled in the configuration, ignore checking');
155
+            }
156
+            }
157
+    }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Security{
27
+	class Security {
28 28
 		
29 29
 		/**
30 30
 		 * The logger instance
@@ -36,9 +36,9 @@  discard block
 block discarded – undo
36 36
 		 * Get the logger singleton instance
37 37
 		 * @return Log the logger instance
38 38
 		 */
39
-		private static function getLogger(){
40
-			if(self::$logger == null){
41
-				self::$logger[0] =& class_loader('Log', 'classes');
39
+		private static function getLogger() {
40
+			if (self::$logger == null) {
41
+				self::$logger[0] = & class_loader('Log', 'classes');
42 42
 				self::$logger[0]->setLogger('Library::Security');
43 43
 			}
44 44
 			return self::$logger[0];
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 		 * This method is used to generate the CSRF token
50 50
 		 * @return string the generated CSRF token
51 51
 		 */
52
-		public static function generateCSRF(){
52
+		public static function generateCSRF() {
53 53
 			$logger = self::getLogger();
54 54
 			$logger->debug('Generation of CSRF ...');
55 55
 			
@@ -57,14 +57,14 @@  discard block
 block discarded – undo
57 57
 			$expire = get_config('csrf_expire', 60);
58 58
 			$keyExpire = 'csrf_expire';
59 59
 			$currentTime = time();
60
-			if(Session::exists($key) && Session::exists($keyExpire) && Session::get($keyExpire) > $currentTime){
60
+			if (Session::exists($key) && Session::exists($keyExpire) && Session::get($keyExpire) > $currentTime) {
61 61
 				$logger->info('The CSRF token not yet expire just return it');
62 62
 				return Session::get($key);
63 63
 			}
64
-			else{
64
+			else {
65 65
 				$newTime = $currentTime + $expire;
66 66
 				$token = sha1(uniqid()) . sha1(uniqid());
67
-				$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. '], token [' .$token. ']');
67
+				$logger->info('The CSRF informations are listed below: key [' . $key . '], key expire [' . $keyExpire . '], expire time [' . $expire . '], token [' . $token . ']');
68 68
 				Session::set($keyExpire, $newTime);
69 69
 				Session::set($key, $token);
70 70
 				return Session::get($key);
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 		 * This method is used to check the CSRF if is valid, not yet expire, etc.
76 76
 		 * @return boolean true if valid, false if not valid
77 77
 		 */
78
-		public static function validateCSRF(){
78
+		public static function validateCSRF() {
79 79
 			$logger = self::getLogger();
80 80
 			$logger->debug('Validation of CSRF ...');
81 81
 				
@@ -83,8 +83,8 @@  discard block
 block discarded – undo
83 83
 			$expire = get_config('csrf_expire', 60);
84 84
 			$keyExpire = 'csrf_expire';
85 85
 			$currentTime = time();
86
-			$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. ']');
87
-			if(! Session::exists($key) || Session::get($keyExpire) <= $currentTime){
86
+			$logger->info('The CSRF informations are listed below: key [' . $key . '], key expire [' . $keyExpire . '], expire time [' . $expire . ']');
87
+			if (!Session::exists($key) || Session::get($keyExpire) <= $currentTime) {
88 88
 				$logger->warning('The CSRF session data is not valide');
89 89
 				return false;
90 90
 			}
@@ -93,11 +93,11 @@  discard block
 block discarded – undo
93 93
 			//super instance
94 94
 			$obj = & get_instance();
95 95
 			$token = $obj->request->query($key);
96
-			if(! $token || $token !== Session::get($key) || Session::get($keyExpire) <= $currentTime){
97
-				$logger->warning('The CSRF data [' .$token. '] is not valide may be attacker do his job');
96
+			if (!$token || $token !== Session::get($key) || Session::get($keyExpire) <= $currentTime) {
97
+				$logger->warning('The CSRF data [' . $token . '] is not valide may be attacker do his job');
98 98
 				return false;
99 99
 			}
100
-			$logger->info('The CSRF data [' .$token. '] is valide the form data is safe continue');
100
+			$logger->info('The CSRF data [' . $token . '] is valide the form data is safe continue');
101 101
 			//remove the token from session
102 102
 			Session::clear($key);
103 103
 			Session::clear($keyExpire);
@@ -107,24 +107,24 @@  discard block
 block discarded – undo
107 107
 		/**
108 108
 		 * This method is used to check the whitelist IP address access
109 109
 		 */
110
-		 public static function checkWhiteListIpAccess(){
110
+		 public static function checkWhiteListIpAccess() {
111 111
 			$logger = self::getLogger();
112 112
 			$logger->debug('Validation of the IP address access ...');
113 113
 			$logger->debug('Check if whitelist IP access is enabled in the configuration ...');
114 114
 			$isEnable = get_config('white_list_ip_enable', false);
115
-			if($isEnable){
115
+			if ($isEnable) {
116 116
 				$logger->info('Whitelist IP access is enabled in the configuration');
117 117
 				$list = get_config('white_list_ip_addresses', array());
118
-				if(! empty($list)){
118
+				if (!empty($list)) {
119 119
 					//Can't use Loader::functions() at this time because teh "Loader" library is loader after the security prossessing
120 120
 					require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
121 121
 					$ip = get_ip();
122
-					if((count($list) == 1 && $list[0] == '*') || in_array($ip, $list)){
122
+					if ((count($list) == 1 && $list[0] == '*') || in_array($ip, $list)) {
123 123
 						$logger->info('IP address ' . $ip . ' allowed using the wildcard "*" or the full IP');
124 124
 						//wildcard to access all ip address
125 125
 						return;
126 126
 					}
127
-					else{
127
+					else {
128 128
 						// go through all whitelisted ips
129 129
 						foreach ($list as $ipaddr) {
130 130
 							// find the wild card * in whitelisted ip (f.e. find position in "127.0.*" or "127*")
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 					}
151 151
 				}
152 152
 			}
153
-			else{
153
+			else {
154 154
 				$logger->info('Whitelist IP access is not enabled in the configuration, ignore checking');
155 155
 			}
156 156
 		 }
Please login to merge, or discard this patch.
Braces   +3 added lines, -6 removed lines patch added patch discarded remove patch
@@ -60,8 +60,7 @@  discard block
 block discarded – undo
60 60
 			if(Session::exists($key) && Session::exists($keyExpire) && Session::get($keyExpire) > $currentTime){
61 61
 				$logger->info('The CSRF token not yet expire just return it');
62 62
 				return Session::get($key);
63
-			}
64
-			else{
63
+			} else{
65 64
 				$newTime = $currentTime + $expire;
66 65
 				$token = sha1(uniqid()) . sha1(uniqid());
67 66
 				$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. '], token [' .$token. ']');
@@ -123,8 +122,7 @@  discard block
 block discarded – undo
123 122
 						$logger->info('IP address ' . $ip . ' allowed using the wildcard "*" or the full IP');
124 123
 						//wildcard to access all ip address
125 124
 						return;
126
-					}
127
-					else{
125
+					} else{
128 126
 						// go through all whitelisted ips
129 127
 						foreach ($list as $ipaddr) {
130 128
 							// find the wild card * in whitelisted ip (f.e. find position in "127.0.*" or "127*")
@@ -149,8 +147,7 @@  discard block
 block discarded – undo
149 147
 						show_error('Access to this application is not allowed');
150 148
 					}
151 149
 				}
152
-			}
153
-			else{
150
+			} else{
154 151
 				$logger->info('Whitelist IP access is not enabled in the configuration, ignore checking');
155 152
 			}
156 153
 		 }
Please login to merge, or discard this patch.
core/classes/database/DatabaseQueryBuilder.php 2 patches
Indentation   +388 added lines, -388 removed lines patch added patch discarded remove patch
@@ -1,108 +1,108 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
     defined('ROOT_PATH') || exit('Access denied');
3
-  /**
4
-   * TNH Framework
5
-   *
6
-   * A simple PHP framework using HMVC architecture
7
-   *
8
-   * This content is released under the GNU GPL License (GPL)
9
-   *
10
-   * Copyright (C) 2017 Tony NGUEREZA
11
-   *
12
-   * This program is free software; you can redistribute it and/or
13
-   * modify it under the terms of the GNU General Public License
14
-   * as published by the Free Software Foundation; either version 3
15
-   * of the License, or (at your option) any later version.
16
-   *
17
-   * This program is distributed in the hope that it will be useful,
18
-   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-   * GNU General Public License for more details.
21
-   *
22
-   * You should have received a copy of the GNU General Public License
23
-   * along with this program; if not, write to the Free Software
24
-   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-  */
26
-  class DatabaseQueryBuilder{
27
-  	/**
28
-  	 * The SQL SELECT statment
29
-  	 * @var string
30
-  	*/
31
-  	private $select              = '*';
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+    class DatabaseQueryBuilder{
27
+        /**
28
+         * The SQL SELECT statment
29
+         * @var string
30
+         */
31
+        private $select              = '*';
32 32
   	
33
-  	/**
34
-  	 * The SQL FROM statment
35
-  	 * @var string
36
-  	*/
37
-      private $from              = null;
33
+        /**
34
+         * The SQL FROM statment
35
+         * @var string
36
+         */
37
+        private $from              = null;
38 38
   	
39
-  	/**
40
-  	 * The SQL WHERE statment
41
-  	 * @var string
42
-  	*/
43
-      private $where               = null;
39
+        /**
40
+         * The SQL WHERE statment
41
+         * @var string
42
+         */
43
+        private $where               = null;
44 44
   	
45
-  	/**
46
-  	 * The SQL LIMIT statment
47
-  	 * @var string
48
-  	*/
49
-      private $limit               = null;
45
+        /**
46
+         * The SQL LIMIT statment
47
+         * @var string
48
+         */
49
+        private $limit               = null;
50 50
   	
51
-  	/**
52
-  	 * The SQL JOIN statment
53
-  	 * @var string
54
-  	*/
55
-      private $join                = null;
51
+        /**
52
+         * The SQL JOIN statment
53
+         * @var string
54
+         */
55
+        private $join                = null;
56 56
   	
57
-  	/**
58
-  	 * The SQL ORDER BY statment
59
-  	 * @var string
60
-  	*/
61
-      private $orderBy             = null;
57
+        /**
58
+         * The SQL ORDER BY statment
59
+         * @var string
60
+         */
61
+        private $orderBy             = null;
62 62
   	
63
-  	/**
64
-  	 * The SQL GROUP BY statment
65
-  	 * @var string
66
-  	*/
67
-      private $groupBy             = null;
63
+        /**
64
+         * The SQL GROUP BY statment
65
+         * @var string
66
+         */
67
+        private $groupBy             = null;
68 68
   	
69
-  	/**
70
-  	 * The SQL HAVING statment
71
-  	 * @var string
72
-  	*/
73
-      private $having              = null;
69
+        /**
70
+         * The SQL HAVING statment
71
+         * @var string
72
+         */
73
+        private $having              = null;
74 74
   	
75
-  	/**
76
-  	 * The full SQL query statment after build for each command
77
-  	 * @var string
78
-  	*/
79
-      private $query               = null;
75
+        /**
76
+         * The full SQL query statment after build for each command
77
+         * @var string
78
+         */
79
+        private $query               = null;
80 80
   	
81
-  	/**
82
-  	 * The list of SQL valid operators
83
-  	 * @var array
84
-  	*/
81
+        /**
82
+         * The list of SQL valid operators
83
+         * @var array
84
+         */
85 85
     private $operatorList        = array('=','!=','<','>','<=','>=','<>');
86 86
   	
87 87
 	
88
-	/**
89
-	 * The prefix used in each database table
90
-	 * @var string
91
-	*/
88
+    /**
89
+     * The prefix used in each database table
90
+     * @var string
91
+     */
92 92
     private $prefix              = null;
93 93
     
94 94
 
95 95
     /**
96
-  	 * The PDO instance
97
-  	 * @var object
98
-  	*/
96
+     * The PDO instance
97
+     * @var object
98
+     */
99 99
     private $pdo                 = null;
100 100
 	
101
-  	/**
102
-  	 * The database driver name used
103
-  	 * @var string
104
-  	*/
105
-  	private $driver              = null;
101
+        /**
102
+         * The database driver name used
103
+         * @var string
104
+         */
105
+        private $driver              = null;
106 106
   	
107 107
 	
108 108
     /**
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
      */
112 112
     public function __construct(PDO $pdo = null){
113 113
         if (is_object($pdo)){
114
-          $this->setPdo($pdo);
114
+            $this->setPdo($pdo);
115 115
         }
116 116
     }
117 117
 
@@ -121,16 +121,16 @@  discard block
 block discarded – undo
121 121
      * @return object        the current DatabaseQueryBuilder instance
122 122
      */
123 123
     public function from($table){
124
-	  if (is_array($table)){
124
+        if (is_array($table)){
125 125
         $froms = '';
126 126
         foreach($table as $key){
127
-          $froms .= $this->getPrefix() . $key . ', ';
127
+            $froms .= $this->getPrefix() . $key . ', ';
128 128
         }
129 129
         $this->from = rtrim($froms, ', ');
130
-      } else {
130
+        } else {
131 131
         $this->from = $this->getPrefix() . $table;
132
-      }
133
-      return $this;
132
+        }
133
+        return $this;
134 134
     }
135 135
 
136 136
     /**
@@ -139,9 +139,9 @@  discard block
 block discarded – undo
139 139
      * @return object        the current DatabaseQueryBuilder instance
140 140
      */
141 141
     public function select($fields){
142
-      $select = (is_array($fields) ? implode(', ', $fields) : $fields);
143
-      $this->select = (($this->select == '*' || empty($this->select)) ? $select : $this->select . ', ' . $select);
144
-      return $this;
142
+        $select = (is_array($fields) ? implode(', ', $fields) : $fields);
143
+        $this->select = (($this->select == '*' || empty($this->select)) ? $select : $this->select . ', ' . $select);
144
+        return $this;
145 145
     }
146 146
 
147 147
     /**
@@ -150,19 +150,19 @@  discard block
 block discarded – undo
150 150
      * @return object        the current DatabaseQueryBuilder instance
151 151
      */
152 152
     public function distinct($field){
153
-      $distinct = ' DISTINCT ' . $field;
154
-      $this->select = (($this->select == '*' || empty($this->select)) ? $distinct : $this->select . ', ' . $distinct);
155
-      return $this;
153
+        $distinct = ' DISTINCT ' . $field;
154
+        $this->select = (($this->select == '*' || empty($this->select)) ? $distinct : $this->select . ', ' . $distinct);
155
+        return $this;
156 156
     }
157 157
 
158
-     /**
159
-     * Set the SQL function COUNT in SELECT statment
160
-     * @param  string $field the field name
161
-     * @param  string $name  if is not null represent the alias used for this field in the result
162
-     * @return object        the current DatabaseQueryBuilder instance
163
-     */
158
+        /**
159
+         * Set the SQL function COUNT in SELECT statment
160
+         * @param  string $field the field name
161
+         * @param  string $name  if is not null represent the alias used for this field in the result
162
+         * @return object        the current DatabaseQueryBuilder instance
163
+         */
164 164
     public function count($field = '*', $name = null){
165
-      return $this->select_min_max_sum_count_avg('COUNT', $field, $name);
165
+        return $this->select_min_max_sum_count_avg('COUNT', $field, $name);
166 166
     }
167 167
     
168 168
     /**
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
      * @return object        the current DatabaseQueryBuilder instance
173 173
      */
174 174
     public function min($field, $name = null){
175
-      return $this->select_min_max_sum_count_avg('MIN', $field, $name);
175
+        return $this->select_min_max_sum_count_avg('MIN', $field, $name);
176 176
     }
177 177
 
178 178
     /**
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
      * @return object        the current DatabaseQueryBuilder instance
183 183
      */
184 184
     public function max($field, $name = null){
185
-      return $this->select_min_max_sum_count_avg('MAX', $field, $name);
185
+        return $this->select_min_max_sum_count_avg('MAX', $field, $name);
186 186
     }
187 187
 
188 188
     /**
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
      * @return object        the current DatabaseQueryBuilder instance
193 193
      */
194 194
     public function sum($field, $name = null){
195
-      return $this->select_min_max_sum_count_avg('SUM', $field, $name);
195
+        return $this->select_min_max_sum_count_avg('SUM', $field, $name);
196 196
     }
197 197
 
198 198
     /**
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
      * @return object        the current DatabaseQueryBuilder instance
203 203
      */
204 204
     public function avg($field, $name = null){
205
-      return $this->select_min_max_sum_count_avg('AVG', $field, $name);
205
+        return $this->select_min_max_sum_count_avg('AVG', $field, $name);
206 206
     }
207 207
 
208 208
 
@@ -216,20 +216,20 @@  discard block
 block discarded – undo
216 216
      * @return object        the current DatabaseQueryBuilder instance
217 217
      */
218 218
     public function join($table, $field1 = null, $op = null, $field2 = null, $type = ''){
219
-      $on = $field1;
220
-      $table = $this->getPrefix() . $table;
221
-      if (! is_null($op)){
219
+        $on = $field1;
220
+        $table = $this->getPrefix() . $table;
221
+        if (! is_null($op)){
222 222
         $on = (! in_array($op, $this->operatorList) 
223
-													? ($this->getPrefix() . $field1 . ' = ' . $this->getPrefix() . $op) 
224
-													: ($this->getPrefix() . $field1 . ' ' . $op . ' ' . $this->getPrefix() . $field2));
225
-      }
226
-      if (empty($this->join)){
223
+                                                    ? ($this->getPrefix() . $field1 . ' = ' . $this->getPrefix() . $op) 
224
+                                                    : ($this->getPrefix() . $field1 . ' ' . $op . ' ' . $this->getPrefix() . $field2));
225
+        }
226
+        if (empty($this->join)){
227 227
         $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
228
-      }
229
-      else{
228
+        }
229
+        else{
230 230
         $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
231
-      }
232
-      return $this;
231
+        }
232
+        return $this;
233 233
     }
234 234
 
235 235
     /**
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
      * @return object        the current DatabaseQueryBuilder instance
239 239
      */
240 240
     public function innerJoin($table, $field1, $op = null, $field2 = ''){
241
-      return $this->join($table, $field1, $op, $field2, 'INNER ');
241
+        return $this->join($table, $field1, $op, $field2, 'INNER ');
242 242
     }
243 243
 
244 244
     /**
@@ -247,16 +247,16 @@  discard block
 block discarded – undo
247 247
      * @return object        the current DatabaseQueryBuilder instance
248 248
      */
249 249
     public function leftJoin($table, $field1, $op = null, $field2 = ''){
250
-      return $this->join($table, $field1, $op, $field2, 'LEFT ');
251
-	}
250
+        return $this->join($table, $field1, $op, $field2, 'LEFT ');
251
+    }
252 252
 
253
-	/**
253
+    /**
254 254
      * Set the SQL RIGHT JOIN statment
255 255
      * @see  DatabaseQueryBuilder::join()
256 256
      * @return object        the current DatabaseQueryBuilder instance
257 257
      */
258 258
     public function rightJoin($table, $field1, $op = null, $field2 = ''){
259
-      return $this->join($table, $field1, $op, $field2, 'RIGHT ');
259
+        return $this->join($table, $field1, $op, $field2, 'RIGHT ');
260 260
     }
261 261
 
262 262
     /**
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
      * @return object        the current DatabaseQueryBuilder instance
266 266
      */
267 267
     public function fullOuterJoin($table, $field1, $op = null, $field2 = ''){
268
-    	return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
268
+        return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
269 269
     }
270 270
 
271 271
     /**
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
      * @return object        the current DatabaseQueryBuilder instance
275 275
      */
276 276
     public function leftOuterJoin($table, $field1, $op = null, $field2 = ''){
277
-      return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
277
+        return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
278 278
     }
279 279
 
280 280
     /**
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
      * @return object        the current DatabaseQueryBuilder instance
284 284
      */
285 285
     public function rightOuterJoin($table, $field1, $op = null, $field2 = ''){
286
-      return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
286
+        return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
287 287
     }
288 288
 
289 289
     /**
@@ -293,14 +293,14 @@  discard block
 block discarded – undo
293 293
      * @return object        the current DatabaseQueryBuilder instance
294 294
      */
295 295
     public function whereIsNull($field, $andOr = 'AND'){
296
-      if (is_array($field)){
296
+        if (is_array($field)){
297 297
         foreach($field as $f){
298
-        	$this->whereIsNull($f, $andOr);
298
+            $this->whereIsNull($f, $andOr);
299 299
         }
300
-      } else {
301
-          $this->setWhereStr($field.' IS NULL ', $andOr);
302
-      }
303
-      return $this;
300
+        } else {
301
+            $this->setWhereStr($field.' IS NULL ', $andOr);
302
+        }
303
+        return $this;
304 304
     }
305 305
 
306 306
     /**
@@ -310,14 +310,14 @@  discard block
 block discarded – undo
310 310
      * @return object        the current DatabaseQueryBuilder instance
311 311
      */
312 312
     public function whereIsNotNull($field, $andOr = 'AND'){
313
-      if (is_array($field)){
313
+        if (is_array($field)){
314 314
         foreach($field as $f){
315
-          $this->whereIsNotNull($f, $andOr);
315
+            $this->whereIsNotNull($f, $andOr);
316
+        }
317
+        } else {
318
+            $this->setWhereStr($field.' IS NOT NULL ', $andOr);
316 319
         }
317
-      } else {
318
-          $this->setWhereStr($field.' IS NOT NULL ', $andOr);
319
-      }
320
-      return $this;
320
+        return $this;
321 321
     }
322 322
     
323 323
     /**
@@ -331,19 +331,19 @@  discard block
 block discarded – undo
331 331
      * @return object        the current DatabaseQueryBuilder instance
332 332
      */
333 333
     public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true){
334
-      $whereStr = '';
335
-      if (is_array($where)){
334
+        $whereStr = '';
335
+        if (is_array($where)){
336 336
         $whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
337
-      }
338
-      else{
337
+        }
338
+        else{
339 339
         if (is_array($op)){
340
-          $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
340
+            $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
341 341
         } else {
342
-          $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape);
342
+            $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape);
343
+        }
343 344
         }
344
-      }
345
-      $this->setWhereStr($whereStr, $andOr);
346
-      return $this;
345
+        $this->setWhereStr($whereStr, $andOr);
346
+        return $this;
347 347
     }
348 348
 
349 349
     /**
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
      * @return object        the current DatabaseQueryBuilder instance
353 353
      */
354 354
     public function orWhere($where, $op = null, $val = null, $escape = true){
355
-      return $this->where($where, $op, $val, '', 'OR', $escape);
355
+        return $this->where($where, $op, $val, '', 'OR', $escape);
356 356
     }
357 357
 
358 358
 
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
      * @return object        the current DatabaseQueryBuilder instance
363 363
      */
364 364
     public function notWhere($where, $op = null, $val = null, $escape = true){
365
-      return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
365
+        return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
366 366
     }
367 367
 
368 368
     /**
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
      * @return object        the current DatabaseQueryBuilder instance
372 372
      */
373 373
     public function orNotWhere($where, $op = null, $val = null, $escape = true){
374
-    	return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
374
+        return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
375 375
     }
376 376
 
377 377
     /**
@@ -381,16 +381,16 @@  discard block
 block discarded – undo
381 381
      * @return object        the current DatabaseQueryBuilder instance
382 382
      */
383 383
     public function groupStart($type = '', $andOr = ' AND'){
384
-      if (empty($this->where)){
384
+        if (empty($this->where)){
385 385
         $this->where = $type . ' (';
386
-      } else {
387
-          if (substr(trim($this->where), -1) == '('){
386
+        } else {
387
+            if (substr(trim($this->where), -1) == '('){
388 388
             $this->where .= $type . ' (';
389
-          } else {
390
-          	$this->where .= $andOr . ' ' . $type . ' (';
391
-          }
392
-      }
393
-      return $this;
389
+            } else {
390
+                $this->where .= $andOr . ' ' . $type . ' (';
391
+            }
392
+        }
393
+        return $this;
394 394
     }
395 395
 
396 396
     /**
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
      * @return object        the current DatabaseQueryBuilder instance
400 400
      */
401 401
     public function notGroupStart(){
402
-      return $this->groupStart('NOT');
402
+        return $this->groupStart('NOT');
403 403
     }
404 404
 
405 405
     /**
@@ -408,16 +408,16 @@  discard block
 block discarded – undo
408 408
      * @return object        the current DatabaseQueryBuilder instance
409 409
      */
410 410
     public function orGroupStart(){
411
-      return $this->groupStart('', ' OR');
411
+        return $this->groupStart('', ' OR');
412 412
     }
413 413
 
414
-     /**
415
-     * Set the opened parenthesis for the complex SQL query using OR for separator and NOT for type
416
-     * @see  DatabaseQueryBuilder::groupStart()
417
-     * @return object        the current DatabaseQueryBuilder instance
418
-     */
414
+        /**
415
+         * Set the opened parenthesis for the complex SQL query using OR for separator and NOT for type
416
+         * @see  DatabaseQueryBuilder::groupStart()
417
+         * @return object        the current DatabaseQueryBuilder instance
418
+         */
419 419
     public function orNotGroupStart(){
420
-      return $this->groupStart('NOT', ' OR');
420
+        return $this->groupStart('NOT', ' OR');
421 421
     }
422 422
 
423 423
     /**
@@ -425,8 +425,8 @@  discard block
 block discarded – undo
425 425
      * @return object        the current DatabaseQueryBuilder instance
426 426
      */
427 427
     public function groupEnd(){
428
-      $this->where .= ')';
429
-      return $this;
428
+        $this->where .= ')';
429
+        return $this;
430 430
     }
431 431
 
432 432
     /**
@@ -439,17 +439,17 @@  discard block
 block discarded – undo
439 439
      * @return object        the current DatabaseQueryBuilder instance
440 440
      */
441 441
     public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true){
442
-      $_keys = array();
443
-      foreach ($keys as $k => $v){
442
+        $_keys = array();
443
+        foreach ($keys as $k => $v){
444 444
         if (is_null($v)){
445
-          $v = '';
445
+            $v = '';
446 446
         }
447 447
         $_keys[] = (is_numeric($v) ? $v : $this->escape($v, $escape));
448
-      }
449
-      $keys = implode(', ', $_keys);
450
-      $whereStr = $field . ' ' . $type . ' IN (' . $keys . ')';
451
-      $this->setWhereStr($whereStr, $andOr);
452
-      return $this;
448
+        }
449
+        $keys = implode(', ', $_keys);
450
+        $whereStr = $field . ' ' . $type . ' IN (' . $keys . ')';
451
+        $this->setWhereStr($whereStr, $andOr);
452
+        return $this;
453 453
     }
454 454
 
455 455
     /**
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
      * @return object        the current DatabaseQueryBuilder instance
459 459
      */
460 460
     public function notIn($field, array $keys, $escape = true){
461
-      return $this->in($field, $keys, 'NOT ', 'AND', $escape);
461
+        return $this->in($field, $keys, 'NOT ', 'AND', $escape);
462 462
     }
463 463
 
464 464
     /**
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
      * @return object        the current DatabaseQueryBuilder instance
468 468
      */
469 469
     public function orIn($field, array $keys, $escape = true){
470
-      return $this->in($field, $keys, '', 'OR', $escape);
470
+        return $this->in($field, $keys, '', 'OR', $escape);
471 471
     }
472 472
 
473 473
     /**
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
      * @return object        the current DatabaseQueryBuilder instance
477 477
      */
478 478
     public function orNotIn($field, array $keys, $escape = true){
479
-      return $this->in($field, $keys, 'NOT ', 'OR', $escape);
479
+        return $this->in($field, $keys, 'NOT ', 'OR', $escape);
480 480
     }
481 481
 
482 482
     /**
@@ -490,15 +490,15 @@  discard block
 block discarded – undo
490 490
      * @return object        the current DatabaseQueryBuilder instance
491 491
      */
492 492
     public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true){
493
-      if (is_null($value1)){
493
+        if (is_null($value1)){
494 494
         $value1 = '';
495
-      }
496
-      if (is_null($value2)){
495
+        }
496
+        if (is_null($value2)){
497 497
         $value2 = '';
498
-      }
499
-      $whereStr = $field . ' ' . $type . ' BETWEEN ' . $this->escape($value1, $escape) . ' AND ' . $this->escape($value2, $escape);
500
-      $this->setWhereStr($whereStr, $andOr);
501
-      return $this;
498
+        }
499
+        $whereStr = $field . ' ' . $type . ' BETWEEN ' . $this->escape($value1, $escape) . ' AND ' . $this->escape($value2, $escape);
500
+        $this->setWhereStr($whereStr, $andOr);
501
+        return $this;
502 502
     }
503 503
 
504 504
     /**
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
      * @return object        the current DatabaseQueryBuilder instance
508 508
      */
509 509
     public function notBetween($field, $value1, $value2, $escape = true){
510
-      return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
510
+        return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
511 511
     }
512 512
 
513 513
     /**
@@ -516,7 +516,7 @@  discard block
 block discarded – undo
516 516
      * @return object        the current DatabaseQueryBuilder instance
517 517
      */
518 518
     public function orBetween($field, $value1, $value2, $escape = true){
519
-      return $this->between($field, $value1, $value2, '', 'OR', $escape);
519
+        return $this->between($field, $value1, $value2, '', 'OR', $escape);
520 520
     }
521 521
 
522 522
     /**
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
      * @return object        the current DatabaseQueryBuilder instance
526 526
      */
527 527
     public function orNotBetween($field, $value1, $value2, $escape = true){
528
-      return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
528
+        return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
529 529
     }
530 530
 
531 531
     /**
@@ -538,11 +538,11 @@  discard block
 block discarded – undo
538 538
      * @return object        the current DatabaseQueryBuilder instance
539 539
      */
540 540
     public function like($field, $data, $type = '', $andOr = 'AND', $escape = true){
541
-      if (empty($data)){
541
+        if (empty($data)){
542 542
         $data = '';
543
-      }
544
-      $this->setWhereStr($field . ' ' . $type . ' LIKE ' . ($this->escape($data, $escape)), $andOr);
545
-      return $this;
543
+        }
544
+        $this->setWhereStr($field . ' ' . $type . ' LIKE ' . ($this->escape($data, $escape)), $andOr);
545
+        return $this;
546 546
     }
547 547
 
548 548
     /**
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
      * @return object        the current DatabaseQueryBuilder instance
552 552
      */
553 553
     public function orLike($field, $data, $escape = true){
554
-      return $this->like($field, $data, '', 'OR', $escape);
554
+        return $this->like($field, $data, '', 'OR', $escape);
555 555
     }
556 556
 
557 557
     /**
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
      * @return object        the current DatabaseQueryBuilder instance
561 561
      */
562 562
     public function notLike($field, $data, $escape = true){
563
-      return $this->like($field, $data, 'NOT ', 'AND', $escape);
563
+        return $this->like($field, $data, 'NOT ', 'AND', $escape);
564 564
     }
565 565
 
566 566
     /**
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
      * @return object        the current DatabaseQueryBuilder instance
570 570
      */
571 571
     public function orNotLike($field, $data, $escape = true){
572
-      return $this->like($field, $data, 'NOT ', 'OR', $escape);
572
+        return $this->like($field, $data, 'NOT ', 'OR', $escape);
573 573
     }
574 574
 
575 575
     /**
@@ -580,16 +580,16 @@  discard block
 block discarded – undo
580 580
      * @return object        the current DatabaseQueryBuilder instance
581 581
      */
582 582
     public function limit($limit, $limitEnd = null){
583
-      if (empty($limit)){
583
+        if (empty($limit)){
584 584
         $limit = 0;
585
-      }
586
-      if (! is_null($limitEnd)){
585
+        }
586
+        if (! is_null($limitEnd)){
587 587
         $this->limit = $limit . ', ' . $limitEnd;
588
-      }
589
-      else{
588
+        }
589
+        else{
590 590
         $this->limit = $limit;
591
-      }
592
-      return $this;
591
+        }
592
+        return $this;
593 593
     }
594 594
 
595 595
     /**
@@ -599,15 +599,15 @@  discard block
 block discarded – undo
599 599
      * @return object        the current DatabaseQueryBuilder instance
600 600
      */
601 601
     public function orderBy($orderBy, $orderDir = ' ASC'){
602
-      if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
602
+        if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
603 603
         $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
604
-      }
605
-      else{
604
+        }
605
+        else{
606 606
         $this->orderBy = empty($this->orderBy) 
607
-						? ($orderBy . ' ' . strtoupper($orderDir)) 
608
-						: $this->orderBy . ', ' . $orderBy . ' ' . strtoupper($orderDir);
609
-      }
610
-      return $this;
607
+                        ? ($orderBy . ' ' . strtoupper($orderDir)) 
608
+                        : $this->orderBy . ', ' . $orderBy . ' ' . strtoupper($orderDir);
609
+        }
610
+        return $this;
611 611
     }
612 612
 
613 613
     /**
@@ -616,13 +616,13 @@  discard block
 block discarded – undo
616 616
      * @return object        the current DatabaseQueryBuilder instance
617 617
      */
618 618
     public function groupBy($field){
619
-      if (is_array($field)){
619
+        if (is_array($field)){
620 620
         $this->groupBy = implode(', ', $field);
621
-      }
622
-      else{
621
+        }
622
+        else{
623 623
         $this->groupBy = $field;
624
-      }
625
-      return $this;
624
+        }
625
+        return $this;
626 626
     }
627 627
 
628 628
     /**
@@ -634,22 +634,22 @@  discard block
 block discarded – undo
634 634
      * @return object        the current DatabaseQueryBuilder instance
635 635
      */
636 636
     public function having($field, $op = null, $val = null, $escape = true){
637
-      if (is_array($op)){
637
+        if (is_array($op)){
638 638
         $this->having = $this->getHavingStrIfOperatorIsArray($field, $op, $escape);
639
-      }
640
-      else if (! in_array($op, $this->operatorList)){
639
+        }
640
+        else if (! in_array($op, $this->operatorList)){
641 641
         if (is_null($op)){
642
-          $op = '';
642
+            $op = '';
643 643
         }
644 644
         $this->having = $field . ' > ' . ($this->escape($op, $escape));
645
-      }
646
-      else{
645
+        }
646
+        else{
647 647
         if (is_null($val)){
648
-          $val = '';
648
+            $val = '';
649 649
         }
650 650
         $this->having = $field . ' ' . $op . ' ' . ($this->escape($val, $escape));
651
-      }
652
-      return $this;
651
+        }
652
+        return $this;
653 653
     }
654 654
 
655 655
     /**
@@ -659,12 +659,12 @@  discard block
 block discarded – undo
659 659
      * @return object  the current DatabaseQueryBuilder instance        
660 660
      */
661 661
     public function insert($data = array(), $escape = true){
662
-      $columns = array_keys($data);
663
-      $column = implode(', ', $columns);
664
-      $val = implode(', ', ($escape ? array_map(array($this, 'escape'), $data) : $data));
662
+        $columns = array_keys($data);
663
+        $column = implode(', ', $columns);
664
+        $val = implode(', ', ($escape ? array_map(array($this, 'escape'), $data) : $data));
665 665
 
666
-      $this->query = 'INSERT INTO ' . $this->from . ' (' . $column . ') VALUES (' . $val . ')';
667
-      return $this;
666
+        $this->query = 'INSERT INTO ' . $this->from . ' (' . $column . ') VALUES (' . $val . ')';
667
+        return $this;
668 668
     }
669 669
 
670 670
     /**
@@ -674,25 +674,25 @@  discard block
 block discarded – undo
674 674
      * @return object  the current DatabaseQueryBuilder instance 
675 675
      */
676 676
     public function update($data = array(), $escape = true){
677
-      $query = 'UPDATE ' . $this->from . ' SET ';
678
-      $values = array();
679
-      foreach ($data as $column => $val){
677
+        $query = 'UPDATE ' . $this->from . ' SET ';
678
+        $values = array();
679
+        foreach ($data as $column => $val){
680 680
         $values[] = $column . ' = ' . ($this->escape($val, $escape));
681
-      }
682
-      $query .= implode(', ', $values);
683
-      if (! empty($this->where)){
681
+        }
682
+        $query .= implode(', ', $values);
683
+        if (! empty($this->where)){
684 684
         $query .= ' WHERE ' . $this->where;
685
-      }
685
+        }
686 686
 
687
-      if (! empty($this->orderBy)){
687
+        if (! empty($this->orderBy)){
688 688
         $query .= ' ORDER BY ' . $this->orderBy;
689
-      }
689
+        }
690 690
 
691
-      if (! empty($this->limit)){
691
+        if (! empty($this->limit)){
692 692
         $query .= ' LIMIT ' . $this->limit;
693
-      }
694
-      $this->query = $query;
695
-      return $this;
693
+        }
694
+        $this->query = $query;
695
+        return $this;
696 696
     }
697 697
 
698 698
     /**
@@ -700,25 +700,25 @@  discard block
 block discarded – undo
700 700
      * @return object  the current DatabaseQueryBuilder instance 
701 701
      */
702 702
     public function delete(){
703
-    	$query = 'DELETE FROM ' . $this->from;
704
-      $isTruncate = $query;
705
-    	if (! empty($this->where)){
706
-  		  $query .= ' WHERE ' . $this->where;
707
-    	}
703
+        $query = 'DELETE FROM ' . $this->from;
704
+        $isTruncate = $query;
705
+        if (! empty($this->where)){
706
+            $query .= ' WHERE ' . $this->where;
707
+        }
708 708
 
709
-    	if (! empty($this->orderBy)){
710
-    	  $query .= ' ORDER BY ' . $this->orderBy;
711
-      }
709
+        if (! empty($this->orderBy)){
710
+            $query .= ' ORDER BY ' . $this->orderBy;
711
+        }
712 712
 
713
-    	if (! empty($this->limit)){
714
-    		$query .= ' LIMIT ' . $this->limit;
715
-      }
713
+        if (! empty($this->limit)){
714
+            $query .= ' LIMIT ' . $this->limit;
715
+        }
716 716
 
717
-  		if ($isTruncate == $query && $this->driver != 'sqlite'){  
718
-      	$query = 'TRUNCATE TABLE ' . $this->from;
719
-  		}
720
-	   $this->query = $query;
721
-	   return $this;
717
+            if ($isTruncate == $query && $this->driver != 'sqlite'){  
718
+            $query = 'TRUNCATE TABLE ' . $this->from;
719
+            }
720
+        $this->query = $query;
721
+        return $this;
722 722
     }
723 723
 
724 724
     /**
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
      * @return mixed       the data after escaped or the same data if not
729 729
      */
730 730
     public function escape($data, $escaped = true){
731
-      return $escaped 
731
+        return $escaped 
732 732
                     ? $this->pdo->quote(trim($data)) 
733 733
                     : $data; 
734 734
     }
@@ -739,126 +739,126 @@  discard block
 block discarded – undo
739 739
      * @return string
740 740
      */
741 741
     public function getQuery(){
742
-  	  //INSERT, UPDATE, DELETE already set it, if is the SELECT we need set it now
743
-  	  if(empty($this->query)){
744
-  		  $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
745
-  		  if (! empty($this->join)){
746
-          $query .= $this->join;
747
-  		  }
742
+        //INSERT, UPDATE, DELETE already set it, if is the SELECT we need set it now
743
+        if(empty($this->query)){
744
+            $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
745
+            if (! empty($this->join)){
746
+            $query .= $this->join;
747
+            }
748 748
   		  
749
-  		  if (! empty($this->where)){
750
-          $query .= ' WHERE ' . $this->where;
751
-  		  }
749
+            if (! empty($this->where)){
750
+            $query .= ' WHERE ' . $this->where;
751
+            }
752 752
 
753
-  		  if (! empty($this->groupBy)){
754
-          $query .= ' GROUP BY ' . $this->groupBy;
755
-  		  }
753
+            if (! empty($this->groupBy)){
754
+            $query .= ' GROUP BY ' . $this->groupBy;
755
+            }
756 756
 
757
-  		  if (! empty($this->having)){
758
-          $query .= ' HAVING ' . $this->having;
759
-  		  }
757
+            if (! empty($this->having)){
758
+            $query .= ' HAVING ' . $this->having;
759
+            }
760 760
 
761
-  		  if (! empty($this->orderBy)){
762
-  			  $query .= ' ORDER BY ' . $this->orderBy;
763
-  		  }
761
+            if (! empty($this->orderBy)){
762
+                $query .= ' ORDER BY ' . $this->orderBy;
763
+            }
764 764
 
765
-  		  if (! empty($this->limit)){
766
-          $query .= ' LIMIT ' . $this->limit;
767
-  		  }
768
-  		  $this->query = $query;
769
-  	  }
770
-      return $this->query;
765
+            if (! empty($this->limit)){
766
+            $query .= ' LIMIT ' . $this->limit;
767
+            }
768
+            $this->query = $query;
769
+        }
770
+        return $this->query;
771 771
     }
772 772
 
773 773
 	
774
-	 /**
775
-     * Return the PDO instance
776
-     * @return object
777
-     */
774
+        /**
775
+         * Return the PDO instance
776
+         * @return object
777
+         */
778 778
     public function getPdo(){
779
-      return $this->pdo;
779
+        return $this->pdo;
780 780
     }
781 781
 
782 782
     /**
783 783
      * Set the PDO instance
784 784
      * @param PDO $pdo the pdo object
785
-	   * @return object DatabaseQueryBuilder
785
+     * @return object DatabaseQueryBuilder
786 786
      */
787 787
     public function setPdo(PDO $pdo = null){
788
-      $this->pdo = $pdo;
789
-      return $this;
788
+        $this->pdo = $pdo;
789
+        return $this;
790 790
     }
791 791
 	
792
-   /**
793
-   * Return the database table prefix
794
-   * @return string
795
-   */
792
+    /**
793
+     * Return the database table prefix
794
+     * @return string
795
+     */
796 796
     public function getPrefix(){
797
-      return $this->prefix;
797
+        return $this->prefix;
798 798
     }
799 799
 
800 800
     /**
801 801
      * Set the database table prefix
802 802
      * @param string $prefix the new prefix
803
-	   * @return object DatabaseQueryBuilder
803
+     * @return object DatabaseQueryBuilder
804 804
      */
805 805
     public function setPrefix($prefix){
806
-      $this->prefix = $prefix;
807
-      return $this;
806
+        $this->prefix = $prefix;
807
+        return $this;
808 808
     }
809 809
 	
810
-	   /**
811
-     * Return the database driver
812
-     * @return string
813
-     */
810
+        /**
811
+         * Return the database driver
812
+         * @return string
813
+         */
814 814
     public function getDriver(){
815
-      return $this->driver;
815
+        return $this->driver;
816 816
     }
817 817
 
818 818
     /**
819 819
      * Set the database driver
820 820
      * @param string $driver the new driver
821
-	   * @return object DatabaseQueryBuilder
821
+     * @return object DatabaseQueryBuilder
822 822
      */
823 823
     public function setDriver($driver){
824
-      $this->driver = $driver;
825
-      return $this;
824
+        $this->driver = $driver;
825
+        return $this;
826 826
     }
827 827
 	
828
-	   /**
829
-     * Reset the DatabaseQueryBuilder class attributs to the initial values before each query.
830
-	   * @return object  the current DatabaseQueryBuilder instance 
831
-     */
828
+        /**
829
+         * Reset the DatabaseQueryBuilder class attributs to the initial values before each query.
830
+         * @return object  the current DatabaseQueryBuilder instance 
831
+         */
832 832
     public function reset(){
833
-      $this->select   = '*';
834
-      $this->from     = null;
835
-      $this->where    = null;
836
-      $this->limit    = null;
837
-      $this->orderBy  = null;
838
-      $this->groupBy  = null;
839
-      $this->having   = null;
840
-      $this->join     = null;
841
-      $this->query    = null;
842
-      return $this;
843
-    }
844
-
845
-	   /**
846
-     * Get the SQL HAVING clause when operator argument is an array
847
-     * @see DatabaseQueryBuilder::having
848
-     *
849
-     * @return string
850
-     */
833
+        $this->select   = '*';
834
+        $this->from     = null;
835
+        $this->where    = null;
836
+        $this->limit    = null;
837
+        $this->orderBy  = null;
838
+        $this->groupBy  = null;
839
+        $this->having   = null;
840
+        $this->join     = null;
841
+        $this->query    = null;
842
+        return $this;
843
+    }
844
+
845
+        /**
846
+         * Get the SQL HAVING clause when operator argument is an array
847
+         * @see DatabaseQueryBuilder::having
848
+         *
849
+         * @return string
850
+         */
851 851
     protected function getHavingStrIfOperatorIsArray($field, $op = null, $escape = true){
852 852
         $x = explode('?', $field);
853 853
         $w = '';
854 854
         foreach($x as $k => $v){
855
-  	      if (!empty($v)){
855
+            if (!empty($v)){
856 856
             if (! isset($op[$k])){
857
-              $op[$k] = '';
857
+                $op[$k] = '';
858
+            }
859
+                $w .= $v . (isset($op[$k]) ? $this->escape($op[$k], $escape) : '');
860
+            }
858 861
             }
859
-  	      	$w .= $v . (isset($op[$k]) ? $this->escape($op[$k], $escape) : '');
860
-  	      }
861
-      	}
862 862
         return $w;
863 863
     }
864 864
 
@@ -870,35 +870,35 @@  discard block
 block discarded – undo
870 870
      * @return string
871 871
      */
872 872
     protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true){
873
-      $_where = array();
874
-      foreach ($where as $column => $data){
873
+        $_where = array();
874
+        foreach ($where as $column => $data){
875 875
         if (is_null($data)){
876
-          $data = '';
876
+            $data = '';
877 877
         }
878 878
         $_where[] = $type . $column . ' = ' . ($this->escape($data, $escape));
879
-      }
880
-      $where = implode(' '.$andOr.' ', $_where);
881
-      return $where;
879
+        }
880
+        $where = implode(' '.$andOr.' ', $_where);
881
+        return $where;
882 882
     }
883 883
 
884
-     /**
885
-     * Get the SQL WHERE clause when operator argument is an array
886
-     * @see DatabaseQueryBuilder::where
887
-     *
888
-     * @return string
889
-     */
884
+        /**
885
+         * Get the SQL WHERE clause when operator argument is an array
886
+         * @see DatabaseQueryBuilder::where
887
+         *
888
+         * @return string
889
+         */
890 890
     protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true){
891
-     $x = explode('?', $where);
892
-     $w = '';
893
-      foreach($x as $k => $v){
891
+        $x = explode('?', $where);
892
+        $w = '';
893
+        foreach($x as $k => $v){
894 894
         if (! empty($v)){
895 895
             if (isset($op[$k]) && is_null($op[$k])){
896
-              $op[$k] = '';
896
+                $op[$k] = '';
897 897
             }
898 898
             $w .= $type . $v . (isset($op[$k]) ? ($this->escape($op[$k], $escape)) : '');
899 899
         }
900
-      }
901
-      return $w;
900
+        }
901
+        return $w;
902 902
     }
903 903
 
904 904
     /**
@@ -908,53 +908,53 @@  discard block
 block discarded – undo
908 908
      * @return string
909 909
      */
910 910
     protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true){
911
-       $w = '';
912
-       if (! in_array((string)$op, $this->operatorList)){
913
-          if (is_null($op)){
911
+        $w = '';
912
+        if (! in_array((string)$op, $this->operatorList)){
913
+            if (is_null($op)){
914 914
             $op = '';
915
-          }
916
-          $w = $type . $where . ' = ' . ($this->escape($op, $escape));
915
+            }
916
+            $w = $type . $where . ' = ' . ($this->escape($op, $escape));
917 917
         } else {
918
-          if (is_null($val)){
918
+            if (is_null($val)){
919 919
             $val = '';
920
-          }
921
-          $w = $type . $where . $op . ($this->escape($val, $escape));
920
+            }
921
+            $w = $type . $where . $op . ($this->escape($val, $escape));
922 922
         }
923 923
         return $w;
924
-      }
925
-
926
-      /**
927
-       * Set the $this->where property 
928
-       * @param string $whereStr the WHERE clause string
929
-       * @param  string  $andOr the separator type used 'AND', 'OR', etc.
930
-       */
931
-      protected function setWhereStr($whereStr, $andOr = 'AND'){
924
+        }
925
+
926
+        /**
927
+         * Set the $this->where property 
928
+         * @param string $whereStr the WHERE clause string
929
+         * @param  string  $andOr the separator type used 'AND', 'OR', etc.
930
+         */
931
+        protected function setWhereStr($whereStr, $andOr = 'AND'){
932 932
         if (empty($this->where)){
933
-          $this->where = $whereStr;
933
+            $this->where = $whereStr;
934 934
         } else {
935
-          if (substr(trim($this->where), -1) == '('){
935
+            if (substr(trim($this->where), -1) == '('){
936 936
             $this->where = $this->where . ' ' . $whereStr;
937
-          } else {
937
+            } else {
938 938
             $this->where = $this->where . ' '.$andOr.' ' . $whereStr;
939
-          }
939
+            }
940
+        }
940 941
         }
941
-      }
942 942
 
943 943
 
944
-	 /**
945
-     * Set the SQL SELECT for function MIN, MAX, SUM, AVG, COUNT, AVG
946
-     * @param  string $clause the clause type like MIN, MAX, etc.
947
-     * @see  DatabaseQueryBuilder::min
948
-     * @see  DatabaseQueryBuilder::max
949
-     * @see  DatabaseQueryBuilder::sum
950
-     * @see  DatabaseQueryBuilder::count
951
-     * @see  DatabaseQueryBuilder::avg
952
-     * @return object
953
-     */
944
+        /**
945
+         * Set the SQL SELECT for function MIN, MAX, SUM, AVG, COUNT, AVG
946
+         * @param  string $clause the clause type like MIN, MAX, etc.
947
+         * @see  DatabaseQueryBuilder::min
948
+         * @see  DatabaseQueryBuilder::max
949
+         * @see  DatabaseQueryBuilder::sum
950
+         * @see  DatabaseQueryBuilder::count
951
+         * @see  DatabaseQueryBuilder::avg
952
+         * @return object
953
+         */
954 954
     protected function select_min_max_sum_count_avg($clause, $field, $name = null){
955
-      $clause = strtoupper($clause);
956
-      $func = $clause . '(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
957
-      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
958
-      return $this;
955
+        $clause = strtoupper($clause);
956
+        $func = $clause . '(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
957
+        $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
958
+        return $this;
959 959
     }
960 960
 }
Please login to merge, or discard this patch.
Spacing   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -23,94 +23,94 @@  discard block
 block discarded – undo
23 23
    * along with this program; if not, write to the Free Software
24 24
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
   */
26
-  class DatabaseQueryBuilder{
26
+  class DatabaseQueryBuilder {
27 27
   	/**
28 28
   	 * The SQL SELECT statment
29 29
   	 * @var string
30 30
   	*/
31
-  	private $select              = '*';
31
+  	private $select = '*';
32 32
   	
33 33
   	/**
34 34
   	 * The SQL FROM statment
35 35
   	 * @var string
36 36
   	*/
37
-      private $from              = null;
37
+      private $from = null;
38 38
   	
39 39
   	/**
40 40
   	 * The SQL WHERE statment
41 41
   	 * @var string
42 42
   	*/
43
-      private $where               = null;
43
+      private $where = null;
44 44
   	
45 45
   	/**
46 46
   	 * The SQL LIMIT statment
47 47
   	 * @var string
48 48
   	*/
49
-      private $limit               = null;
49
+      private $limit = null;
50 50
   	
51 51
   	/**
52 52
   	 * The SQL JOIN statment
53 53
   	 * @var string
54 54
   	*/
55
-      private $join                = null;
55
+      private $join = null;
56 56
   	
57 57
   	/**
58 58
   	 * The SQL ORDER BY statment
59 59
   	 * @var string
60 60
   	*/
61
-      private $orderBy             = null;
61
+      private $orderBy = null;
62 62
   	
63 63
   	/**
64 64
   	 * The SQL GROUP BY statment
65 65
   	 * @var string
66 66
   	*/
67
-      private $groupBy             = null;
67
+      private $groupBy = null;
68 68
   	
69 69
   	/**
70 70
   	 * The SQL HAVING statment
71 71
   	 * @var string
72 72
   	*/
73
-      private $having              = null;
73
+      private $having = null;
74 74
   	
75 75
   	/**
76 76
   	 * The full SQL query statment after build for each command
77 77
   	 * @var string
78 78
   	*/
79
-      private $query               = null;
79
+      private $query = null;
80 80
   	
81 81
   	/**
82 82
   	 * The list of SQL valid operators
83 83
   	 * @var array
84 84
   	*/
85
-    private $operatorList        = array('=','!=','<','>','<=','>=','<>');
85
+    private $operatorList = array('=', '!=', '<', '>', '<=', '>=', '<>');
86 86
   	
87 87
 	
88 88
 	/**
89 89
 	 * The prefix used in each database table
90 90
 	 * @var string
91 91
 	*/
92
-    private $prefix              = null;
92
+    private $prefix = null;
93 93
     
94 94
 
95 95
     /**
96 96
   	 * The PDO instance
97 97
   	 * @var object
98 98
   	*/
99
-    private $pdo                 = null;
99
+    private $pdo = null;
100 100
 	
101 101
   	/**
102 102
   	 * The database driver name used
103 103
   	 * @var string
104 104
   	*/
105
-  	private $driver              = null;
105
+  	private $driver = null;
106 106
   	
107 107
 	
108 108
     /**
109 109
      * Construct new DatabaseQueryBuilder
110 110
      * @param object $pdo the PDO object
111 111
      */
112
-    public function __construct(PDO $pdo = null){
113
-        if (is_object($pdo)){
112
+    public function __construct(PDO $pdo = null) {
113
+        if (is_object($pdo)) {
114 114
           $this->setPdo($pdo);
115 115
         }
116 116
     }
@@ -120,10 +120,10 @@  discard block
 block discarded – undo
120 120
      * @param  string|array $table the table name or array of table list
121 121
      * @return object        the current DatabaseQueryBuilder instance
122 122
      */
123
-    public function from($table){
124
-	  if (is_array($table)){
123
+    public function from($table) {
124
+	  if (is_array($table)) {
125 125
         $froms = '';
126
-        foreach($table as $key){
126
+        foreach ($table as $key) {
127 127
           $froms .= $this->getPrefix() . $key . ', ';
128 128
         }
129 129
         $this->from = rtrim($froms, ', ');
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
      * @param  string|array $fields the field name or array of field list
139 139
      * @return object        the current DatabaseQueryBuilder instance
140 140
      */
141
-    public function select($fields){
141
+    public function select($fields) {
142 142
       $select = (is_array($fields) ? implode(', ', $fields) : $fields);
143 143
       $this->select = (($this->select == '*' || empty($this->select)) ? $select : $this->select . ', ' . $select);
144 144
       return $this;
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
      * @param  string $field the field name to distinct
150 150
      * @return object        the current DatabaseQueryBuilder instance
151 151
      */
152
-    public function distinct($field){
152
+    public function distinct($field) {
153 153
       $distinct = ' DISTINCT ' . $field;
154 154
       $this->select = (($this->select == '*' || empty($this->select)) ? $distinct : $this->select . ', ' . $distinct);
155 155
       return $this;
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
      * @param  string $name  if is not null represent the alias used for this field in the result
162 162
      * @return object        the current DatabaseQueryBuilder instance
163 163
      */
164
-    public function count($field = '*', $name = null){
164
+    public function count($field = '*', $name = null) {
165 165
       return $this->select_min_max_sum_count_avg('COUNT', $field, $name);
166 166
     }
167 167
     
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      * @param  string $name  if is not null represent the alias used for this field in the result
172 172
      * @return object        the current DatabaseQueryBuilder instance
173 173
      */
174
-    public function min($field, $name = null){
174
+    public function min($field, $name = null) {
175 175
       return $this->select_min_max_sum_count_avg('MIN', $field, $name);
176 176
     }
177 177
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
      * @param  string $name  if is not null represent the alias used for this field in the result
182 182
      * @return object        the current DatabaseQueryBuilder instance
183 183
      */
184
-    public function max($field, $name = null){
184
+    public function max($field, $name = null) {
185 185
       return $this->select_min_max_sum_count_avg('MAX', $field, $name);
186 186
     }
187 187
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
      * @param  string $name  if is not null represent the alias used for this field in the result
192 192
      * @return object        the current DatabaseQueryBuilder instance
193 193
      */
194
-    public function sum($field, $name = null){
194
+    public function sum($field, $name = null) {
195 195
       return $this->select_min_max_sum_count_avg('SUM', $field, $name);
196 196
     }
197 197
 
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
      * @param  string $name  if is not null represent the alias used for this field in the result
202 202
      * @return object        the current DatabaseQueryBuilder instance
203 203
      */
204
-    public function avg($field, $name = null){
204
+    public function avg($field, $name = null) {
205 205
       return $this->select_min_max_sum_count_avg('AVG', $field, $name);
206 206
     }
207 207
 
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
      * @param  string $type   the type of join (INNER, LEFT, RIGHT)
216 216
      * @return object        the current DatabaseQueryBuilder instance
217 217
      */
218
-    public function join($table, $field1 = null, $op = null, $field2 = null, $type = ''){
218
+    public function join($table, $field1 = null, $op = null, $field2 = null, $type = '') {
219 219
       $on = $field1;
220 220
       $table = $this->getPrefix() . $table;
221
-      if (! is_null($op)){
222
-        $on = (! in_array($op, $this->operatorList) 
221
+      if (!is_null($op)) {
222
+        $on = (!in_array($op, $this->operatorList) 
223 223
 													? ($this->getPrefix() . $field1 . ' = ' . $this->getPrefix() . $op) 
224 224
 													: ($this->getPrefix() . $field1 . ' ' . $op . ' ' . $this->getPrefix() . $field2));
225 225
       }
226
-      if (empty($this->join)){
226
+      if (empty($this->join)) {
227 227
         $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
228 228
       }
229
-      else{
229
+      else {
230 230
         $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
231 231
       }
232 232
       return $this;
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
      * @see  DatabaseQueryBuilder::join()
238 238
      * @return object        the current DatabaseQueryBuilder instance
239 239
      */
240
-    public function innerJoin($table, $field1, $op = null, $field2 = ''){
240
+    public function innerJoin($table, $field1, $op = null, $field2 = '') {
241 241
       return $this->join($table, $field1, $op, $field2, 'INNER ');
242 242
     }
243 243
 
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
      * @see  DatabaseQueryBuilder::join()
247 247
      * @return object        the current DatabaseQueryBuilder instance
248 248
      */
249
-    public function leftJoin($table, $field1, $op = null, $field2 = ''){
249
+    public function leftJoin($table, $field1, $op = null, $field2 = '') {
250 250
       return $this->join($table, $field1, $op, $field2, 'LEFT ');
251 251
 	}
252 252
 
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
      * @see  DatabaseQueryBuilder::join()
256 256
      * @return object        the current DatabaseQueryBuilder instance
257 257
      */
258
-    public function rightJoin($table, $field1, $op = null, $field2 = ''){
258
+    public function rightJoin($table, $field1, $op = null, $field2 = '') {
259 259
       return $this->join($table, $field1, $op, $field2, 'RIGHT ');
260 260
     }
261 261
 
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
      * @see  DatabaseQueryBuilder::join()
265 265
      * @return object        the current DatabaseQueryBuilder instance
266 266
      */
267
-    public function fullOuterJoin($table, $field1, $op = null, $field2 = ''){
267
+    public function fullOuterJoin($table, $field1, $op = null, $field2 = '') {
268 268
     	return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
269 269
     }
270 270
 
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
      * @see  DatabaseQueryBuilder::join()
274 274
      * @return object        the current DatabaseQueryBuilder instance
275 275
      */
276
-    public function leftOuterJoin($table, $field1, $op = null, $field2 = ''){
276
+    public function leftOuterJoin($table, $field1, $op = null, $field2 = '') {
277 277
       return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
278 278
     }
279 279
 
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
      * @see  DatabaseQueryBuilder::join()
283 283
      * @return object        the current DatabaseQueryBuilder instance
284 284
      */
285
-    public function rightOuterJoin($table, $field1, $op = null, $field2 = ''){
285
+    public function rightOuterJoin($table, $field1, $op = null, $field2 = '') {
286 286
       return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
287 287
     }
288 288
 
@@ -292,13 +292,13 @@  discard block
 block discarded – undo
292 292
      * @param  string $andOr the separator type used 'AND', 'OR', etc.
293 293
      * @return object        the current DatabaseQueryBuilder instance
294 294
      */
295
-    public function whereIsNull($field, $andOr = 'AND'){
296
-      if (is_array($field)){
297
-        foreach($field as $f){
295
+    public function whereIsNull($field, $andOr = 'AND') {
296
+      if (is_array($field)) {
297
+        foreach ($field as $f) {
298 298
         	$this->whereIsNull($f, $andOr);
299 299
         }
300 300
       } else {
301
-          $this->setWhereStr($field.' IS NULL ', $andOr);
301
+          $this->setWhereStr($field . ' IS NULL ', $andOr);
302 302
       }
303 303
       return $this;
304 304
     }
@@ -309,13 +309,13 @@  discard block
 block discarded – undo
309 309
      * @param  string $andOr the separator type used 'AND', 'OR', etc.
310 310
      * @return object        the current DatabaseQueryBuilder instance
311 311
      */
312
-    public function whereIsNotNull($field, $andOr = 'AND'){
313
-      if (is_array($field)){
314
-        foreach($field as $f){
312
+    public function whereIsNotNull($field, $andOr = 'AND') {
313
+      if (is_array($field)) {
314
+        foreach ($field as $f) {
315 315
           $this->whereIsNotNull($f, $andOr);
316 316
         }
317 317
       } else {
318
-          $this->setWhereStr($field.' IS NOT NULL ', $andOr);
318
+          $this->setWhereStr($field . ' IS NOT NULL ', $andOr);
319 319
       }
320 320
       return $this;
321 321
     }
@@ -330,13 +330,13 @@  discard block
 block discarded – undo
330 330
      * @param  boolean $escape whether to escape or not the $val
331 331
      * @return object        the current DatabaseQueryBuilder instance
332 332
      */
333
-    public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true){
333
+    public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true) {
334 334
       $whereStr = '';
335
-      if (is_array($where)){
335
+      if (is_array($where)) {
336 336
         $whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
337 337
       }
338
-      else{
339
-        if (is_array($op)){
338
+      else {
339
+        if (is_array($op)) {
340 340
           $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
341 341
         } else {
342 342
           $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape);
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
      * @see  DatabaseQueryBuilder::where()
352 352
      * @return object        the current DatabaseQueryBuilder instance
353 353
      */
354
-    public function orWhere($where, $op = null, $val = null, $escape = true){
354
+    public function orWhere($where, $op = null, $val = null, $escape = true) {
355 355
       return $this->where($where, $op, $val, '', 'OR', $escape);
356 356
     }
357 357
 
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
      * @see  DatabaseQueryBuilder::where()
362 362
      * @return object        the current DatabaseQueryBuilder instance
363 363
      */
364
-    public function notWhere($where, $op = null, $val = null, $escape = true){
364
+    public function notWhere($where, $op = null, $val = null, $escape = true) {
365 365
       return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
366 366
     }
367 367
 
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
      * @see  DatabaseQueryBuilder::where()
371 371
      * @return object        the current DatabaseQueryBuilder instance
372 372
      */
373
-    public function orNotWhere($where, $op = null, $val = null, $escape = true){
373
+    public function orNotWhere($where, $op = null, $val = null, $escape = true) {
374 374
     	return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
375 375
     }
376 376
 
@@ -380,11 +380,11 @@  discard block
 block discarded – undo
380 380
      * @param  string $andOr the multiple conditions separator (AND, OR, etc.)
381 381
      * @return object        the current DatabaseQueryBuilder instance
382 382
      */
383
-    public function groupStart($type = '', $andOr = ' AND'){
384
-      if (empty($this->where)){
383
+    public function groupStart($type = '', $andOr = ' AND') {
384
+      if (empty($this->where)) {
385 385
         $this->where = $type . ' (';
386 386
       } else {
387
-          if (substr(trim($this->where), -1) == '('){
387
+          if (substr(trim($this->where), -1) == '(') {
388 388
             $this->where .= $type . ' (';
389 389
           } else {
390 390
           	$this->where .= $andOr . ' ' . $type . ' (';
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
      * @see  DatabaseQueryBuilder::groupStart()
399 399
      * @return object        the current DatabaseQueryBuilder instance
400 400
      */
401
-    public function notGroupStart(){
401
+    public function notGroupStart() {
402 402
       return $this->groupStart('NOT');
403 403
     }
404 404
 
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
      * @see  DatabaseQueryBuilder::groupStart()
408 408
      * @return object        the current DatabaseQueryBuilder instance
409 409
      */
410
-    public function orGroupStart(){
410
+    public function orGroupStart() {
411 411
       return $this->groupStart('', ' OR');
412 412
     }
413 413
 
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
      * @see  DatabaseQueryBuilder::groupStart()
417 417
      * @return object        the current DatabaseQueryBuilder instance
418 418
      */
419
-    public function orNotGroupStart(){
419
+    public function orNotGroupStart() {
420 420
       return $this->groupStart('NOT', ' OR');
421 421
     }
422 422
 
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
      * Close the parenthesis for the grouped SQL
425 425
      * @return object        the current DatabaseQueryBuilder instance
426 426
      */
427
-    public function groupEnd(){
427
+    public function groupEnd() {
428 428
       $this->where .= ')';
429 429
       return $this;
430 430
     }
@@ -438,10 +438,10 @@  discard block
 block discarded – undo
438 438
      * @param  boolean $escape whether to escape or not the values
439 439
      * @return object        the current DatabaseQueryBuilder instance
440 440
      */
441
-    public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true){
441
+    public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true) {
442 442
       $_keys = array();
443
-      foreach ($keys as $k => $v){
444
-        if (is_null($v)){
443
+      foreach ($keys as $k => $v) {
444
+        if (is_null($v)) {
445 445
           $v = '';
446 446
         }
447 447
         $_keys[] = (is_numeric($v) ? $v : $this->escape($v, $escape));
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
      * @see  DatabaseQueryBuilder::in()
458 458
      * @return object        the current DatabaseQueryBuilder instance
459 459
      */
460
-    public function notIn($field, array $keys, $escape = true){
460
+    public function notIn($field, array $keys, $escape = true) {
461 461
       return $this->in($field, $keys, 'NOT ', 'AND', $escape);
462 462
     }
463 463
 
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
      * @see  DatabaseQueryBuilder::in()
467 467
      * @return object        the current DatabaseQueryBuilder instance
468 468
      */
469
-    public function orIn($field, array $keys, $escape = true){
469
+    public function orIn($field, array $keys, $escape = true) {
470 470
       return $this->in($field, $keys, '', 'OR', $escape);
471 471
     }
472 472
 
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
      * @see  DatabaseQueryBuilder::in()
476 476
      * @return object        the current DatabaseQueryBuilder instance
477 477
      */
478
-    public function orNotIn($field, array $keys, $escape = true){
478
+    public function orNotIn($field, array $keys, $escape = true) {
479 479
       return $this->in($field, $keys, 'NOT ', 'OR', $escape);
480 480
     }
481 481
 
@@ -489,11 +489,11 @@  discard block
 block discarded – undo
489 489
      * @param  boolean $escape whether to escape or not the values
490 490
      * @return object        the current DatabaseQueryBuilder instance
491 491
      */
492
-    public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true){
493
-      if (is_null($value1)){
492
+    public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true) {
493
+      if (is_null($value1)) {
494 494
         $value1 = '';
495 495
       }
496
-      if (is_null($value2)){
496
+      if (is_null($value2)) {
497 497
         $value2 = '';
498 498
       }
499 499
       $whereStr = $field . ' ' . $type . ' BETWEEN ' . $this->escape($value1, $escape) . ' AND ' . $this->escape($value2, $escape);
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
      * @see  DatabaseQueryBuilder::between()
507 507
      * @return object        the current DatabaseQueryBuilder instance
508 508
      */
509
-    public function notBetween($field, $value1, $value2, $escape = true){
509
+    public function notBetween($field, $value1, $value2, $escape = true) {
510 510
       return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
511 511
     }
512 512
 
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
      * @see  DatabaseQueryBuilder::between()
516 516
      * @return object        the current DatabaseQueryBuilder instance
517 517
      */
518
-    public function orBetween($field, $value1, $value2, $escape = true){
518
+    public function orBetween($field, $value1, $value2, $escape = true) {
519 519
       return $this->between($field, $value1, $value2, '', 'OR', $escape);
520 520
     }
521 521
 
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
      * @see  DatabaseQueryBuilder::between()
525 525
      * @return object        the current DatabaseQueryBuilder instance
526 526
      */
527
-    public function orNotBetween($field, $value1, $value2, $escape = true){
527
+    public function orNotBetween($field, $value1, $value2, $escape = true) {
528 528
       return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
529 529
     }
530 530
 
@@ -537,8 +537,8 @@  discard block
 block discarded – undo
537 537
      * @param  boolean $escape whether to escape or not the values
538 538
      * @return object        the current DatabaseQueryBuilder instance
539 539
      */
540
-    public function like($field, $data, $type = '', $andOr = 'AND', $escape = true){
541
-      if (empty($data)){
540
+    public function like($field, $data, $type = '', $andOr = 'AND', $escape = true) {
541
+      if (empty($data)) {
542 542
         $data = '';
543 543
       }
544 544
       $this->setWhereStr($field . ' ' . $type . ' LIKE ' . ($this->escape($data, $escape)), $andOr);
@@ -550,7 +550,7 @@  discard block
 block discarded – undo
550 550
      * @see  DatabaseQueryBuilder::like()
551 551
      * @return object        the current DatabaseQueryBuilder instance
552 552
      */
553
-    public function orLike($field, $data, $escape = true){
553
+    public function orLike($field, $data, $escape = true) {
554 554
       return $this->like($field, $data, '', 'OR', $escape);
555 555
     }
556 556
 
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
      * @see  DatabaseQueryBuilder::like()
560 560
      * @return object        the current DatabaseQueryBuilder instance
561 561
      */
562
-    public function notLike($field, $data, $escape = true){
562
+    public function notLike($field, $data, $escape = true) {
563 563
       return $this->like($field, $data, 'NOT ', 'AND', $escape);
564 564
     }
565 565
 
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
      * @see  DatabaseQueryBuilder::like()
569 569
      * @return object        the current DatabaseQueryBuilder instance
570 570
      */
571
-    public function orNotLike($field, $data, $escape = true){
571
+    public function orNotLike($field, $data, $escape = true) {
572 572
       return $this->like($field, $data, 'NOT ', 'OR', $escape);
573 573
     }
574 574
 
@@ -579,14 +579,14 @@  discard block
 block discarded – undo
579 579
      * @param  int $limitEnd the limit count
580 580
      * @return object        the current DatabaseQueryBuilder instance
581 581
      */
582
-    public function limit($limit, $limitEnd = null){
583
-      if (empty($limit)){
582
+    public function limit($limit, $limitEnd = null) {
583
+      if (empty($limit)) {
584 584
         $limit = 0;
585 585
       }
586
-      if (! is_null($limitEnd)){
586
+      if (!is_null($limitEnd)) {
587 587
         $this->limit = $limit . ', ' . $limitEnd;
588 588
       }
589
-      else{
589
+      else {
590 590
         $this->limit = $limit;
591 591
       }
592 592
       return $this;
@@ -598,11 +598,11 @@  discard block
 block discarded – undo
598 598
      * @param  string $orderDir the order direction (ASC or DESC)
599 599
      * @return object        the current DatabaseQueryBuilder instance
600 600
      */
601
-    public function orderBy($orderBy, $orderDir = ' ASC'){
602
-      if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
601
+    public function orderBy($orderBy, $orderDir = ' ASC') {
602
+      if (stristr($orderBy, ' ') || $orderBy == 'rand()') {
603 603
         $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
604 604
       }
605
-      else{
605
+      else {
606 606
         $this->orderBy = empty($this->orderBy) 
607 607
 						? ($orderBy . ' ' . strtoupper($orderDir)) 
608 608
 						: $this->orderBy . ', ' . $orderBy . ' ' . strtoupper($orderDir);
@@ -615,11 +615,11 @@  discard block
 block discarded – undo
615 615
      * @param  string|array $field the field name used or array of field list
616 616
      * @return object        the current DatabaseQueryBuilder instance
617 617
      */
618
-    public function groupBy($field){
619
-      if (is_array($field)){
618
+    public function groupBy($field) {
619
+      if (is_array($field)) {
620 620
         $this->groupBy = implode(', ', $field);
621 621
       }
622
-      else{
622
+      else {
623 623
         $this->groupBy = $field;
624 624
       }
625 625
       return $this;
@@ -633,18 +633,18 @@  discard block
 block discarded – undo
633 633
      * @param  boolean $escape whether to escape or not the values
634 634
      * @return object        the current DatabaseQueryBuilder instance
635 635
      */
636
-    public function having($field, $op = null, $val = null, $escape = true){
637
-      if (is_array($op)){
636
+    public function having($field, $op = null, $val = null, $escape = true) {
637
+      if (is_array($op)) {
638 638
         $this->having = $this->getHavingStrIfOperatorIsArray($field, $op, $escape);
639 639
       }
640
-      else if (! in_array($op, $this->operatorList)){
641
-        if (is_null($op)){
640
+      else if (!in_array($op, $this->operatorList)) {
641
+        if (is_null($op)) {
642 642
           $op = '';
643 643
         }
644 644
         $this->having = $field . ' > ' . ($this->escape($op, $escape));
645 645
       }
646
-      else{
647
-        if (is_null($val)){
646
+      else {
647
+        if (is_null($val)) {
648 648
           $val = '';
649 649
         }
650 650
         $this->having = $field . ' ' . $op . ' ' . ($this->escape($val, $escape));
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
      * @param  boolean $escape  whether to escape or not the values
659 659
      * @return object  the current DatabaseQueryBuilder instance        
660 660
      */
661
-    public function insert($data = array(), $escape = true){
661
+    public function insert($data = array(), $escape = true) {
662 662
       $columns = array_keys($data);
663 663
       $column = implode(', ', $columns);
664 664
       $val = implode(', ', ($escape ? array_map(array($this, 'escape'), $data) : $data));
@@ -673,22 +673,22 @@  discard block
 block discarded – undo
673 673
      * @param  boolean $escape  whether to escape or not the values
674 674
      * @return object  the current DatabaseQueryBuilder instance 
675 675
      */
676
-    public function update($data = array(), $escape = true){
676
+    public function update($data = array(), $escape = true) {
677 677
       $query = 'UPDATE ' . $this->from . ' SET ';
678 678
       $values = array();
679
-      foreach ($data as $column => $val){
679
+      foreach ($data as $column => $val) {
680 680
         $values[] = $column . ' = ' . ($this->escape($val, $escape));
681 681
       }
682 682
       $query .= implode(', ', $values);
683
-      if (! empty($this->where)){
683
+      if (!empty($this->where)) {
684 684
         $query .= ' WHERE ' . $this->where;
685 685
       }
686 686
 
687
-      if (! empty($this->orderBy)){
687
+      if (!empty($this->orderBy)) {
688 688
         $query .= ' ORDER BY ' . $this->orderBy;
689 689
       }
690 690
 
691
-      if (! empty($this->limit)){
691
+      if (!empty($this->limit)) {
692 692
         $query .= ' LIMIT ' . $this->limit;
693 693
       }
694 694
       $this->query = $query;
@@ -699,22 +699,22 @@  discard block
 block discarded – undo
699 699
      * Delete the record in database
700 700
      * @return object  the current DatabaseQueryBuilder instance 
701 701
      */
702
-    public function delete(){
702
+    public function delete() {
703 703
     	$query = 'DELETE FROM ' . $this->from;
704 704
       $isTruncate = $query;
705
-    	if (! empty($this->where)){
705
+    	if (!empty($this->where)) {
706 706
   		  $query .= ' WHERE ' . $this->where;
707 707
     	}
708 708
 
709
-    	if (! empty($this->orderBy)){
709
+    	if (!empty($this->orderBy)) {
710 710
     	  $query .= ' ORDER BY ' . $this->orderBy;
711 711
       }
712 712
 
713
-    	if (! empty($this->limit)){
713
+    	if (!empty($this->limit)) {
714 714
     		$query .= ' LIMIT ' . $this->limit;
715 715
       }
716 716
 
717
-  		if ($isTruncate == $query && $this->driver != 'sqlite'){  
717
+  		if ($isTruncate == $query && $this->driver != 'sqlite') {  
718 718
       	$query = 'TRUNCATE TABLE ' . $this->from;
719 719
   		}
720 720
 	   $this->query = $query;
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
      * @param boolean $escaped whether we can do escape of not 
728 728
      * @return mixed       the data after escaped or the same data if not
729 729
      */
730
-    public function escape($data, $escaped = true){
730
+    public function escape($data, $escaped = true) {
731 731
       return $escaped 
732 732
                     ? $this->pdo->quote(trim($data)) 
733 733
                     : $data; 
@@ -738,31 +738,31 @@  discard block
 block discarded – undo
738 738
      * Return the current SQL query string
739 739
      * @return string
740 740
      */
741
-    public function getQuery(){
741
+    public function getQuery() {
742 742
   	  //INSERT, UPDATE, DELETE already set it, if is the SELECT we need set it now
743
-  	  if(empty($this->query)){
743
+  	  if (empty($this->query)) {
744 744
   		  $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
745
-  		  if (! empty($this->join)){
745
+  		  if (!empty($this->join)) {
746 746
           $query .= $this->join;
747 747
   		  }
748 748
   		  
749
-  		  if (! empty($this->where)){
749
+  		  if (!empty($this->where)) {
750 750
           $query .= ' WHERE ' . $this->where;
751 751
   		  }
752 752
 
753
-  		  if (! empty($this->groupBy)){
753
+  		  if (!empty($this->groupBy)) {
754 754
           $query .= ' GROUP BY ' . $this->groupBy;
755 755
   		  }
756 756
 
757
-  		  if (! empty($this->having)){
757
+  		  if (!empty($this->having)) {
758 758
           $query .= ' HAVING ' . $this->having;
759 759
   		  }
760 760
 
761
-  		  if (! empty($this->orderBy)){
761
+  		  if (!empty($this->orderBy)) {
762 762
   			  $query .= ' ORDER BY ' . $this->orderBy;
763 763
   		  }
764 764
 
765
-  		  if (! empty($this->limit)){
765
+  		  if (!empty($this->limit)) {
766 766
           $query .= ' LIMIT ' . $this->limit;
767 767
   		  }
768 768
   		  $this->query = $query;
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
      * Return the PDO instance
776 776
      * @return object
777 777
      */
778
-    public function getPdo(){
778
+    public function getPdo() {
779 779
       return $this->pdo;
780 780
     }
781 781
 
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
      * @param PDO $pdo the pdo object
785 785
 	   * @return object DatabaseQueryBuilder
786 786
      */
787
-    public function setPdo(PDO $pdo = null){
787
+    public function setPdo(PDO $pdo = null) {
788 788
       $this->pdo = $pdo;
789 789
       return $this;
790 790
     }
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
    * Return the database table prefix
794 794
    * @return string
795 795
    */
796
-    public function getPrefix(){
796
+    public function getPrefix() {
797 797
       return $this->prefix;
798 798
     }
799 799
 
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
      * @param string $prefix the new prefix
803 803
 	   * @return object DatabaseQueryBuilder
804 804
      */
805
-    public function setPrefix($prefix){
805
+    public function setPrefix($prefix) {
806 806
       $this->prefix = $prefix;
807 807
       return $this;
808 808
     }
@@ -811,7 +811,7 @@  discard block
 block discarded – undo
811 811
      * Return the database driver
812 812
      * @return string
813 813
      */
814
-    public function getDriver(){
814
+    public function getDriver() {
815 815
       return $this->driver;
816 816
     }
817 817
 
@@ -820,7 +820,7 @@  discard block
 block discarded – undo
820 820
      * @param string $driver the new driver
821 821
 	   * @return object DatabaseQueryBuilder
822 822
      */
823
-    public function setDriver($driver){
823
+    public function setDriver($driver) {
824 824
       $this->driver = $driver;
825 825
       return $this;
826 826
     }
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
      * Reset the DatabaseQueryBuilder class attributs to the initial values before each query.
830 830
 	   * @return object  the current DatabaseQueryBuilder instance 
831 831
      */
832
-    public function reset(){
832
+    public function reset() {
833 833
       $this->select   = '*';
834 834
       $this->from     = null;
835 835
       $this->where    = null;
@@ -848,12 +848,12 @@  discard block
 block discarded – undo
848 848
      *
849 849
      * @return string
850 850
      */
851
-    protected function getHavingStrIfOperatorIsArray($field, $op = null, $escape = true){
851
+    protected function getHavingStrIfOperatorIsArray($field, $op = null, $escape = true) {
852 852
         $x = explode('?', $field);
853 853
         $w = '';
854
-        foreach($x as $k => $v){
855
-  	      if (!empty($v)){
856
-            if (! isset($op[$k])){
854
+        foreach ($x as $k => $v) {
855
+  	      if (!empty($v)) {
856
+            if (!isset($op[$k])) {
857 857
               $op[$k] = '';
858 858
             }
859 859
   	      	$w .= $v . (isset($op[$k]) ? $this->escape($op[$k], $escape) : '');
@@ -869,15 +869,15 @@  discard block
 block discarded – undo
869 869
      *
870 870
      * @return string
871 871
      */
872
-    protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true){
872
+    protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true) {
873 873
       $_where = array();
874
-      foreach ($where as $column => $data){
875
-        if (is_null($data)){
874
+      foreach ($where as $column => $data) {
875
+        if (is_null($data)) {
876 876
           $data = '';
877 877
         }
878 878
         $_where[] = $type . $column . ' = ' . ($this->escape($data, $escape));
879 879
       }
880
-      $where = implode(' '.$andOr.' ', $_where);
880
+      $where = implode(' ' . $andOr . ' ', $_where);
881 881
       return $where;
882 882
     }
883 883
 
@@ -887,12 +887,12 @@  discard block
 block discarded – undo
887 887
      *
888 888
      * @return string
889 889
      */
890
-    protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true){
890
+    protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true) {
891 891
      $x = explode('?', $where);
892 892
      $w = '';
893
-      foreach($x as $k => $v){
894
-        if (! empty($v)){
895
-            if (isset($op[$k]) && is_null($op[$k])){
893
+      foreach ($x as $k => $v) {
894
+        if (!empty($v)) {
895
+            if (isset($op[$k]) && is_null($op[$k])) {
896 896
               $op[$k] = '';
897 897
             }
898 898
             $w .= $type . $v . (isset($op[$k]) ? ($this->escape($op[$k], $escape)) : '');
@@ -907,15 +907,15 @@  discard block
 block discarded – undo
907 907
      *
908 908
      * @return string
909 909
      */
910
-    protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true){
910
+    protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true) {
911 911
        $w = '';
912
-       if (! in_array((string)$op, $this->operatorList)){
913
-          if (is_null($op)){
912
+       if (!in_array((string) $op, $this->operatorList)) {
913
+          if (is_null($op)) {
914 914
             $op = '';
915 915
           }
916 916
           $w = $type . $where . ' = ' . ($this->escape($op, $escape));
917 917
         } else {
918
-          if (is_null($val)){
918
+          if (is_null($val)) {
919 919
             $val = '';
920 920
           }
921 921
           $w = $type . $where . $op . ($this->escape($val, $escape));
@@ -928,14 +928,14 @@  discard block
 block discarded – undo
928 928
        * @param string $whereStr the WHERE clause string
929 929
        * @param  string  $andOr the separator type used 'AND', 'OR', etc.
930 930
        */
931
-      protected function setWhereStr($whereStr, $andOr = 'AND'){
932
-        if (empty($this->where)){
931
+      protected function setWhereStr($whereStr, $andOr = 'AND') {
932
+        if (empty($this->where)) {
933 933
           $this->where = $whereStr;
934 934
         } else {
935
-          if (substr(trim($this->where), -1) == '('){
935
+          if (substr(trim($this->where), -1) == '(') {
936 936
             $this->where = $this->where . ' ' . $whereStr;
937 937
           } else {
938
-            $this->where = $this->where . ' '.$andOr.' ' . $whereStr;
938
+            $this->where = $this->where . ' ' . $andOr . ' ' . $whereStr;
939 939
           }
940 940
         }
941 941
       }
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
      * @see  DatabaseQueryBuilder::avg
952 952
      * @return object
953 953
      */
954
-    protected function select_min_max_sum_count_avg($clause, $field, $name = null){
954
+    protected function select_min_max_sum_count_avg($clause, $field, $name = null) {
955 955
       $clause = strtoupper($clause);
956 956
       $func = $clause . '(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
957 957
       $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
Please login to merge, or discard this patch.
core/classes/database/Database.php 2 patches
Indentation   +329 added lines, -329 removed lines patch added patch discarded remove patch
@@ -1,119 +1,119 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
     defined('ROOT_PATH') || exit('Access denied');
3
-  /**
4
-   * TNH Framework
5
-   *
6
-   * A simple PHP framework using HMVC architecture
7
-   *
8
-   * This content is released under the GNU GPL License (GPL)
9
-   *
10
-   * Copyright (C) 2017 Tony NGUEREZA
11
-   *
12
-   * This program is free software; you can redistribute it and/or
13
-   * modify it under the terms of the GNU General Public License
14
-   * as published by the Free Software Foundation; either version 3
15
-   * of the License, or (at your option) any later version.
16
-   *
17
-   * This program is distributed in the hope that it will be useful,
18
-   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-   * GNU General Public License for more details.
21
-   *
22
-   * You should have received a copy of the GNU General Public License
23
-   * along with this program; if not, write to the Free Software
24
-   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-  */
26
-  class Database{
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+    class Database{
27 27
 	
28
-  	/**
29
-  	 * The PDO instance
30
-  	 * @var object
31
-  	*/
28
+        /**
29
+         * The PDO instance
30
+         * @var object
31
+         */
32 32
     private $pdo                 = null;
33 33
     
34
-  	/**
35
-  	 * The database name used for the application
36
-  	 * @var string
37
-  	*/
38
-	  private $databaseName        = null;
34
+        /**
35
+         * The database name used for the application
36
+         * @var string
37
+         */
38
+        private $databaseName        = null;
39 39
 	
40
-  	/**
41
-  	 * The number of rows returned by the last query
42
-  	 * @var int
43
-  	*/
40
+        /**
41
+         * The number of rows returned by the last query
42
+         * @var int
43
+         */
44 44
     private $numRows             = 0;
45 45
 	
46
-  	/**
47
-  	 * The last insert id for the primary key column that have auto increment or sequence
48
-  	 * @var mixed
49
-  	*/
46
+        /**
47
+         * The last insert id for the primary key column that have auto increment or sequence
48
+         * @var mixed
49
+         */
50 50
     private $insertId            = null;
51 51
 	
52
-  	/**
53
-  	 * The full SQL query statment after build for each command
54
-  	 * @var string
55
-  	*/
52
+        /**
53
+         * The full SQL query statment after build for each command
54
+         * @var string
55
+         */
56 56
     private $query               = null;
57 57
 	
58
-  	/**
59
-  	 * The result returned for the last query
60
-  	 * @var mixed
61
-  	*/
58
+        /**
59
+         * The result returned for the last query
60
+         * @var mixed
61
+         */
62 62
     private $result              = array();
63 63
 	
64
-  	/**
65
-  	 * The cache default time to live in second. 0 means no need to use the cache feature
66
-  	 * @var int
67
-  	*/
68
-  	private $cacheTtl             = 0;
64
+        /**
65
+         * The cache default time to live in second. 0 means no need to use the cache feature
66
+         * @var int
67
+         */
68
+        private $cacheTtl             = 0;
69 69
 	
70
-  	/**
71
-  	 * The cache current time to live. 0 means no need to use the cache feature
72
-  	 * @var int
73
-  	*/
70
+        /**
71
+         * The cache current time to live. 0 means no need to use the cache feature
72
+         * @var int
73
+         */
74 74
     private $temporaryCacheTtl   = 0;
75 75
 	
76
-  	/**
77
-  	 * The number of executed query for the current request
78
-  	 * @var int
79
-  	*/
76
+        /**
77
+         * The number of executed query for the current request
78
+         * @var int
79
+         */
80 80
     private $queryCount          = 0;
81 81
 	
82
-  	/**
83
-  	 * The default data to be used in the statments query INSERT, UPDATE
84
-  	 * @var array
85
-  	*/
82
+        /**
83
+         * The default data to be used in the statments query INSERT, UPDATE
84
+         * @var array
85
+         */
86 86
     private $data                = array();
87 87
 	
88
-  	/**
89
-  	 * The database configuration
90
-  	 * @var array
91
-  	*/
88
+        /**
89
+         * The database configuration
90
+         * @var array
91
+         */
92 92
     private $config              = array();
93 93
 	
94
-  	/**
95
-  	 * The logger instance
96
-  	 * @var object
97
-  	 */
94
+        /**
95
+         * The logger instance
96
+         * @var object
97
+         */
98 98
     private $logger              = null;
99 99
 
100 100
     /**
101
-    * The cache instance
102
-    * @var object
103
-    */
101
+     * The cache instance
102
+     * @var object
103
+     */
104 104
     private $cacheInstance       = null;
105 105
 
106 106
     
107
-  	/**
108
-    * The DatabaseQueryBuilder instance
109
-    * @var object
110
-    */
107
+        /**
108
+         * The DatabaseQueryBuilder instance
109
+         * @var object
110
+         */
111 111
     private $queryBuilder        = null;
112 112
     
113 113
     /**
114
-    * The DatabaseQueryRunner instance
115
-    * @var object
116
-    */
114
+     * The DatabaseQueryRunner instance
115
+     * @var object
116
+     */
117 117
     private $queryRunner         = null;
118 118
 
119 119
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
         //Set Log instance to use
126 126
         $this->setLoggerFromParamOrCreateNewInstance(null);
127 127
 		
128
-    		//Set DatabaseQueryBuilder instance to use
129
-    		$this->setQueryBuilderFromParamOrCreateNewInstance(null);
128
+            //Set DatabaseQueryBuilder instance to use
129
+            $this->setQueryBuilderFromParamOrCreateNewInstance(null);
130 130
 
131 131
         //Set DatabaseQueryRunner instance to use
132 132
         $this->setQueryRunnerFromParamOrCreateNewInstance(null);
@@ -143,22 +143,22 @@  discard block
 block discarded – undo
143 143
      * @return bool 
144 144
      */
145 145
     public function connect(){
146
-      $config = $this->getDatabaseConfiguration();
147
-      if (! empty($config)){
146
+        $config = $this->getDatabaseConfiguration();
147
+        if (! empty($config)){
148 148
         try{
149 149
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
150 150
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
151 151
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
152 152
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
153 153
             return true;
154
-          }
155
-          catch (PDOException $e){
154
+            }
155
+            catch (PDOException $e){
156 156
             $this->logger->fatal($e->getMessage());
157 157
             show_error('Cannot connect to Database.');
158 158
             return false;
159
-          }
160
-      }
161
-      return false;
159
+            }
160
+        }
161
+        return false;
162 162
     }
163 163
 
164 164
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
      * @return int
168 168
      */
169 169
     public function numRows(){
170
-      return $this->numRows;
170
+        return $this->numRows;
171 171
     }
172 172
 
173 173
     /**
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
      * @return mixed
176 176
      */
177 177
     public function insertId(){
178
-      return $this->insertId;
178
+        return $this->insertId;
179 179
     }
180 180
 
181 181
 
@@ -186,13 +186,13 @@  discard block
 block discarded – undo
186 186
      * @return mixed       the query SQL string or the record result
187 187
      */
188 188
     public function get($returnSQLQueryOrResultType = false){
189
-      $this->getQueryBuilder()->limit(1);
190
-      $query = $this->getAll(true);
191
-      if ($returnSQLQueryOrResultType === true){
189
+        $this->getQueryBuilder()->limit(1);
190
+        $query = $this->getAll(true);
191
+        if ($returnSQLQueryOrResultType === true){
192 192
         return $query;
193
-      } else {
193
+        } else {
194 194
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
195
-      }
195
+        }
196 196
     }
197 197
 
198 198
     /**
@@ -202,11 +202,11 @@  discard block
 block discarded – undo
202 202
      * @return mixed       the query SQL string or the record result
203 203
      */
204 204
     public function getAll($returnSQLQueryOrResultType = false){
205
-	   $query = $this->getQueryBuilder()->getQuery();
206
-	   if ($returnSQLQueryOrResultType === true){
207
-      	return $query;
208
-      }
209
-      return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
205
+        $query = $this->getQueryBuilder()->getQuery();
206
+        if ($returnSQLQueryOrResultType === true){
207
+            return $query;
208
+        }
209
+        return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
210 210
     }
211 211
 
212 212
     /**
@@ -216,19 +216,19 @@  discard block
 block discarded – undo
216 216
      * @return mixed          the insert id of the new record or null
217 217
      */
218 218
     public function insert($data = array(), $escape = true){
219
-      if (empty($data) && $this->getData()){
219
+        if (empty($data) && $this->getData()){
220 220
         //as when using $this->setData() may be the data already escaped
221 221
         $escape = false;
222 222
         $data = $this->getData();
223
-      }
224
-      $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
225
-      $result = $this->query($query);
226
-      if ($result){
223
+        }
224
+        $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
225
+        $result = $this->query($query);
226
+        if ($result){
227 227
         $this->insertId = $this->pdo->lastInsertId();
228
-		    //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
228
+            //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
229 229
         return ! $this->insertId() ? true : $this->insertId();
230
-      }
231
-      return false;
230
+        }
231
+        return false;
232 232
     }
233 233
 
234 234
     /**
@@ -238,13 +238,13 @@  discard block
 block discarded – undo
238 238
      * @return mixed          the update status
239 239
      */
240 240
     public function update($data = array(), $escape = true){
241
-      if (empty($data) && $this->getData()){
241
+        if (empty($data) && $this->getData()){
242 242
         //as when using $this->setData() may be the data already escaped
243 243
         $escape = false;
244 244
         $data = $this->getData();
245
-      }
246
-      $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
247
-      return $this->query($query);
245
+        }
246
+        $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
247
+        return $this->query($query);
248 248
     }
249 249
 
250 250
     /**
@@ -252,8 +252,8 @@  discard block
 block discarded – undo
252 252
      * @return mixed the delete status
253 253
      */
254 254
     public function delete(){
255
-		$query = $this->getQueryBuilder()->delete()->getQuery();
256
-    	return $this->query($query);
255
+        $query = $this->getQueryBuilder()->delete()->getQuery();
256
+        return $this->query($query);
257 257
     }
258 258
 
259 259
     /**
@@ -262,21 +262,21 @@  discard block
 block discarded – undo
262 262
      * @return object        the current Database instance
263 263
      */
264 264
     public function setCache($ttl = 0){
265
-      if ($ttl > 0){
265
+        if ($ttl > 0){
266 266
         $this->cacheTtl = $ttl;
267 267
         $this->temporaryCacheTtl = $ttl;
268
-      }
269
-      return $this;
268
+        }
269
+        return $this;
270 270
     }
271 271
 	
272
-	/**
273
-	 * Enabled cache temporary for the current query not globally	
274
-	 * @param  integer $ttl the cache time to live in second
275
-	 * @return object        the current Database instance
276
-	 */
277
-  	public function cached($ttl = 0){
272
+    /**
273
+     * Enabled cache temporary for the current query not globally	
274
+     * @param  integer $ttl the cache time to live in second
275
+     * @return object        the current Database instance
276
+     */
277
+        public function cached($ttl = 0){
278 278
         if ($ttl > 0){
279
-          $this->temporaryCacheTtl = $ttl;
279
+            $this->temporaryCacheTtl = $ttl;
280 280
         }
281 281
         return $this;
282 282
     }
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
      * @return mixed       the data after escaped or the same data if not
289 289
      */
290 290
     public function escape($data, $escaped = true){
291
-      return $escaped ? 
291
+        return $escaped ? 
292 292
                       $this->pdo->quote(trim($data)) 
293 293
                       : $data; 
294 294
     }
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
      * @return int
299 299
      */
300 300
     public function queryCount(){
301
-      return $this->queryCount;
301
+        return $this->queryCount;
302 302
     }
303 303
 
304 304
     /**
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
      * @return string
307 307
      */
308 308
     public function getQuery(){
309
-      return $this->query;
309
+        return $this->query;
310 310
     }
311 311
 
312 312
     /**
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
      * @return string
315 315
      */
316 316
     public function getDatabaseName(){
317
-      return $this->databaseName;
317
+        return $this->databaseName;
318 318
     }
319 319
 
320 320
     /**
@@ -322,17 +322,17 @@  discard block
 block discarded – undo
322 322
      * @return object
323 323
      */
324 324
     public function getPdo(){
325
-      return $this->pdo;
325
+        return $this->pdo;
326 326
     }
327 327
 
328 328
     /**
329 329
      * Set the PDO instance
330 330
      * @param object $pdo the pdo object
331
-	 * @return object Database
331
+     * @return object Database
332 332
      */
333 333
     public function setPdo(PDO $pdo){
334
-      $this->pdo = $pdo;
335
-      return $this;
334
+        $this->pdo = $pdo;
335
+        return $this;
336 336
     }
337 337
 
338 338
 
@@ -341,44 +341,44 @@  discard block
 block discarded – undo
341 341
      * @return Log
342 342
      */
343 343
     public function getLogger(){
344
-      return $this->logger;
344
+        return $this->logger;
345 345
     }
346 346
 
347 347
     /**
348 348
      * Set the log instance
349 349
      * @param Log $logger the log object
350
-	 * @return object Database
350
+     * @return object Database
351 351
      */
352 352
     public function setLogger($logger){
353
-      $this->logger = $logger;
354
-      return $this;
353
+        $this->logger = $logger;
354
+        return $this;
355 355
     }
356 356
 
357
-     /**
358
-     * Return the cache instance
359
-     * @return CacheInterface
360
-     */
357
+        /**
358
+         * Return the cache instance
359
+         * @return CacheInterface
360
+         */
361 361
     public function getCacheInstance(){
362
-      return $this->cacheInstance;
362
+        return $this->cacheInstance;
363 363
     }
364 364
 
365 365
     /**
366 366
      * Set the cache instance
367 367
      * @param CacheInterface $cache the cache object
368
-	 * @return object Database
368
+     * @return object Database
369 369
      */
370 370
     public function setCacheInstance($cache){
371
-      $this->cacheInstance = $cache;
372
-      return $this;
371
+        $this->cacheInstance = $cache;
372
+        return $this;
373 373
     }
374 374
 	
375 375
 	
376
-	   /**
377
-     * Return the DatabaseQueryBuilder instance
378
-     * @return object DatabaseQueryBuilder
379
-     */
376
+        /**
377
+         * Return the DatabaseQueryBuilder instance
378
+         * @return object DatabaseQueryBuilder
379
+         */
380 380
     public function getQueryBuilder(){
381
-      return $this->queryBuilder;
381
+        return $this->queryBuilder;
382 382
     }
383 383
 
384 384
     /**
@@ -386,8 +386,8 @@  discard block
 block discarded – undo
386 386
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
387 387
      */
388 388
     public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
389
-      $this->queryBuilder = $queryBuilder;
390
-      return $this;
389
+        $this->queryBuilder = $queryBuilder;
390
+        return $this;
391 391
     }
392 392
     
393 393
     /**
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
      * @return object DatabaseQueryRunner
396 396
      */
397 397
     public function getQueryRunner(){
398
-      return $this->queryRunner;
398
+        return $this->queryRunner;
399 399
     }
400 400
 
401 401
     /**
@@ -403,8 +403,8 @@  discard block
 block discarded – undo
403 403
      * @param object DatabaseQueryRunner $queryRunner the DatabaseQueryRunner object
404 404
      */
405 405
     public function setQueryRunner(DatabaseQueryRunner $queryRunner){
406
-      $this->queryRunner = $queryRunner;
407
-      return $this;
406
+        $this->queryRunner = $queryRunner;
407
+        return $this;
408 408
     }
409 409
 
410 410
     /**
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
      * @return array
413 413
      */
414 414
     public function getData(){
415
-      return $this->data;
415
+        return $this->data;
416 416
     }
417 417
 
418 418
     /**
@@ -423,56 +423,56 @@  discard block
 block discarded – undo
423 423
      * @return object        the current Database instance
424 424
      */
425 425
     public function setData($key, $value = null, $escape = true){
426
-  	  if(is_array($key)){
427
-    		foreach($key as $k => $v){
428
-    			$this->setData($k, $v, $escape);
429
-    		}	
430
-  	  } else {
426
+        if(is_array($key)){
427
+            foreach($key as $k => $v){
428
+                $this->setData($k, $v, $escape);
429
+            }	
430
+        } else {
431 431
         $this->data[$key] = $this->escape($value, $escape);
432
-  	  }
433
-      return $this;
432
+        }
433
+        return $this;
434 434
     }
435 435
 
436
-     /**
437
-     * Execute an SQL query
438
-     * @param  string  $query the query SQL string
439
-     * @param  boolean $returnAsList  indicate whether to return all record or just one row 
440
-     * @param  boolean $returnAsArray return the result as array or not
441
-     * @return mixed         the query result
442
-     */
436
+        /**
437
+         * Execute an SQL query
438
+         * @param  string  $query the query SQL string
439
+         * @param  boolean $returnAsList  indicate whether to return all record or just one row 
440
+         * @param  boolean $returnAsArray return the result as array or not
441
+         * @return mixed         the query result
442
+         */
443 443
     public function query($query, $returnAsList = true, $returnAsArray = false){
444
-      $this->reset();
445
-      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
446
-      //If is the SELECT query
447
-      $isSqlSELECTQuery = stristr($this->query, 'SELECT');
444
+        $this->reset();
445
+        $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
446
+        //If is the SELECT query
447
+        $isSqlSELECTQuery = stristr($this->query, 'SELECT');
448 448
 
449
-      //cache expire time
450
-      $cacheExpire = $this->temporaryCacheTtl;
449
+        //cache expire time
450
+        $cacheExpire = $this->temporaryCacheTtl;
451 451
       
452
-      //return to the initial cache time
453
-      $this->temporaryCacheTtl = $this->cacheTtl;
452
+        //return to the initial cache time
453
+        $this->temporaryCacheTtl = $this->cacheTtl;
454 454
       
455
-      //config for cache
456
-      $cacheEnable = get_config('cache_enable');
455
+        //config for cache
456
+        $cacheEnable = get_config('cache_enable');
457 457
       
458
-      //the database cache content
459
-      $cacheContent = null;
458
+        //the database cache content
459
+        $cacheContent = null;
460 460
 
461
-      //if can use cache feature for this query
462
-      $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
461
+        //if can use cache feature for this query
462
+        $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
463 463
     
464
-      if ($dbCacheStatus && $isSqlSELECTQuery){
465
-          $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
466
-          $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
467
-      }
464
+        if ($dbCacheStatus && $isSqlSELECTQuery){
465
+            $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
466
+            $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
467
+        }
468 468
       
469
-      if (!$cacheContent){
470
-  	   	//count the number of query execution to server
469
+        if (!$cacheContent){
470
+                //count the number of query execution to server
471 471
         $this->queryCount++;
472 472
         
473 473
         $this->queryRunner->setQuery($query)
474
-                          ->setReturnType($returnAsList)
475
-                          ->setReturnAsArray($returnAsArray);
474
+                            ->setReturnType($returnAsList)
475
+                            ->setReturnAsArray($returnAsArray);
476 476
         
477 477
         $queryResult = $this->queryRunner->execute();
478 478
         if (is_object($queryResult)){
@@ -482,33 +482,33 @@  discard block
 block discarded – undo
482 482
                 $key = $this->getCacheKeyForQuery($this->query, $returnAsList, $returnAsArray);
483 483
                 $this->setCacheContentForQuery($this->query, $key, $this->result, $cacheExpire);
484 484
             if (! $this->result){
485
-              $this->logger->info('No result where found for the query [' . $query . ']');
485
+                $this->logger->info('No result where found for the query [' . $query . ']');
486 486
             }
487
-          }
487
+            }
488
+        }
489
+        } else if ($isSqlSELECTQuery){
490
+            $this->logger->info('The result for query [' .$this->query. '] already cached use it');
491
+            $this->result = $cacheContent;
492
+            $this->numRows = count($this->result);
488 493
         }
489
-      } else if ($isSqlSELECTQuery){
490
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
491
-          $this->result = $cacheContent;
492
-          $this->numRows = count($this->result);
493
-      }
494
-      return $this->result;
494
+        return $this->result;
495 495
     }
496 496
 	
497 497
 	
498
-	 /**
499
-	 * Return the database configuration
500
-	 * @return array
501
-	 */
502
-  	public  function getDatabaseConfiguration(){
503
-  	  return $this->config;
504
-  	}
505
-
506
-   /**
507
-    * Setting the database configuration using the configuration file and additional configuration from param
508
-    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
509
-    * @param boolean $useConfigFile whether to use database configuration file
510
-	  * @return object Database
511
-    */
498
+        /**
499
+         * Return the database configuration
500
+         * @return array
501
+         */
502
+        public  function getDatabaseConfiguration(){
503
+        return $this->config;
504
+        }
505
+
506
+    /**
507
+     * Setting the database configuration using the configuration file and additional configuration from param
508
+     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
509
+     * @param boolean $useConfigFile whether to use database configuration file
510
+     * @return object Database
511
+     */
512 512
     public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
513 513
         $db = array();
514 514
         if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
@@ -521,50 +521,50 @@  discard block
 block discarded – undo
521 521
         
522 522
         //default configuration
523 523
         $config = array(
524
-          'driver' => 'mysql',
525
-          'username' => 'root',
526
-          'password' => '',
527
-          'database' => '',
528
-          'hostname' => 'localhost',
529
-          'charset' => 'utf8',
530
-          'collation' => 'utf8_general_ci',
531
-          'prefix' => '',
532
-          'port' => ''
524
+            'driver' => 'mysql',
525
+            'username' => 'root',
526
+            'password' => '',
527
+            'database' => '',
528
+            'hostname' => 'localhost',
529
+            'charset' => 'utf8',
530
+            'collation' => 'utf8_general_ci',
531
+            'prefix' => '',
532
+            'port' => ''
533 533
         );
534 534
 		
535
-    	$config = array_merge($config, $db);
536
-    	//determine the port using the hostname like localhost:3307
537
-      //hostname will be "localhost", and port "3307"
538
-      $p = explode(':', $config['hostname']);
539
-  	  if (count($p) >= 2){
540
-  		  $config['hostname'] = $p[0];
541
-  		  $config['port'] = $p[1];
542
-  		}
535
+        $config = array_merge($config, $db);
536
+        //determine the port using the hostname like localhost:3307
537
+        //hostname will be "localhost", and port "3307"
538
+        $p = explode(':', $config['hostname']);
539
+        if (count($p) >= 2){
540
+            $config['hostname'] = $p[0];
541
+            $config['port'] = $p[1];
542
+            }
543 543
 		
544
-		 $this->databaseName = $config['database'];
545
-		 $this->config = $config;
546
-		 $this->logger->info(
547
-								'The database configuration are listed below: ' 
548
-								. stringfy_vars(array_merge(
549
-															$this->config, 
550
-															array('password' => string_hidden($this->config['password']))
551
-												))
552
-							);
544
+            $this->databaseName = $config['database'];
545
+            $this->config = $config;
546
+            $this->logger->info(
547
+                                'The database configuration are listed below: ' 
548
+                                . stringfy_vars(array_merge(
549
+                                                            $this->config, 
550
+                                                            array('password' => string_hidden($this->config['password']))
551
+                                                ))
552
+                            );
553 553
 	  
554
-		 //Now connect to the database
555
-		 $this->connect();
554
+            //Now connect to the database
555
+            $this->connect();
556 556
 		 
557
-     //do update of QueryRunner and Builder
558
-     $this->updateQueryBuilderAndRunnerProperties();
557
+        //do update of QueryRunner and Builder
558
+        $this->updateQueryBuilderAndRunnerProperties();
559 559
 
560
-		 return $this;
560
+            return $this;
561 561
     }
562 562
 
563 563
     /**
564 564
      * Close the connexion
565 565
      */
566 566
     public function close(){
567
-      $this->pdo = null;
567
+        $this->pdo = null;
568 568
     }
569 569
 
570 570
     /**
@@ -572,18 +572,18 @@  discard block
 block discarded – undo
572 572
      * @return void
573 573
      */
574 574
     protected function updateQueryBuilderAndRunnerProperties(){
575
-       //update queryBuilder with some properties needed
576
-     if(is_object($this->queryBuilder)){
575
+        //update queryBuilder with some properties needed
576
+        if(is_object($this->queryBuilder)){
577 577
         $this->queryBuilder->setDriver($this->config['driver'])
578
-                           ->setPrefix($this->config['prefix'])
579
-                           ->setPdo($this->pdo);
580
-     }
578
+                            ->setPrefix($this->config['prefix'])
579
+                            ->setPdo($this->pdo);
580
+        }
581 581
 
582
-      //update queryRunner with some properties needed
583
-     if(is_object($this->queryRunner)){
582
+        //update queryRunner with some properties needed
583
+        if(is_object($this->queryRunner)){
584 584
         $this->queryRunner->setDriver($this->config['driver'])
585
-                          ->setPdo($this->pdo);
586
-     }
585
+                            ->setPdo($this->pdo);
586
+        }
587 587
     }
588 588
 	
589 589
 
@@ -592,24 +592,24 @@  discard block
 block discarded – undo
592 592
      * @return string the DSN string
593 593
      */
594 594
     protected function getDsnFromDriver(){
595
-      $config = $this->getDatabaseConfiguration();
596
-      if (! empty($config)){
595
+        $config = $this->getDatabaseConfiguration();
596
+        if (! empty($config)){
597 597
         $driver = $config['driver'];
598 598
         $driverDsnMap = array(
599
-                              'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
600
-                                          . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
601
-                                          . 'dbname=' . $config['database'],
602
-                              'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
603
-                                          . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
604
-                                          . 'dbname=' . $config['database'],
605
-                              'sqlite' => 'sqlite:' . $config['database'],
606
-                              'oracle' => 'oci:dbname=' . $config['hostname'] 
599
+                                'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
600
+                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
601
+                                            . 'dbname=' . $config['database'],
602
+                                'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
603
+                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
604
+                                            . 'dbname=' . $config['database'],
605
+                                'sqlite' => 'sqlite:' . $config['database'],
606
+                                'oracle' => 'oci:dbname=' . $config['hostname'] 
607 607
                                             . (($config['port']) != '' ? ':' . $config['port'] : '')
608 608
                                             . '/' . $config['database']
609
-                              );
609
+                                );
610 610
         return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : '';
611
-      }                   
612
-      return null;
611
+        }                   
612
+        return null;
613 613
     }
614 614
 
615 615
     /**
@@ -621,11 +621,11 @@  discard block
 block discarded – undo
621 621
     protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray){
622 622
         $cacheKey = $this->getCacheKeyForQuery($query, $returnAsList, $returnAsArray);
623 623
         if (! is_object($this->cacheInstance)){
624
-    			//can not call method with reference in argument
625
-    			//like $this->setCacheInstance(& get_instance()->cache);
626
-    			//use temporary variable
627
-    			$instance = & get_instance()->cache;
628
-    			$this->cacheInstance = $instance;
624
+                //can not call method with reference in argument
625
+                //like $this->setCacheInstance(& get_instance()->cache);
626
+                //use temporary variable
627
+                $instance = & get_instance()->cache;
628
+                $this->cacheInstance = $instance;
629 629
         }
630 630
         return $this->cacheInstance->get($cacheKey);
631 631
     }
@@ -637,87 +637,87 @@  discard block
 block discarded – undo
637 637
      * @param mixed $result the query result to save
638 638
      * @param int $expire the cache TTL
639 639
      */
640
-     protected function setCacheContentForQuery($query, $key, $result, $expire){
640
+        protected function setCacheContentForQuery($query, $key, $result, $expire){
641 641
         $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
642 642
         if (! is_object($this->cacheInstance)){
643
-  				//can not call method with reference in argument
644
-  				//like $this->setCacheInstance(& get_instance()->cache);
645
-  				//use temporary variable
646
-  				$instance = & get_instance()->cache;
647
-  				$this->cacheInstance = $instance;
648
-  			}
643
+                    //can not call method with reference in argument
644
+                    //like $this->setCacheInstance(& get_instance()->cache);
645
+                    //use temporary variable
646
+                    $instance = & get_instance()->cache;
647
+                    $this->cacheInstance = $instance;
648
+                }
649 649
         $this->cacheInstance->set($key, $result, $expire);
650
-     }
650
+        }
651 651
 
652 652
     
653
-	 /**
654
-     * Return the cache key for the given query
655
-     * @see Database::query
656
-     * 
657
-     *  @return string
658
-     */
653
+        /**
654
+         * Return the cache key for the given query
655
+         * @see Database::query
656
+         * 
657
+         *  @return string
658
+         */
659 659
     protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray){
660
-      return md5($query . $returnAsList . $returnAsArray);
660
+        return md5($query . $returnAsList . $returnAsArray);
661 661
     }
662 662
     
663
-	   /**
664
-     * Set the Log instance using argument or create new instance
665
-     * @param object $logger the Log instance if not null
666
-     */
663
+        /**
664
+         * Set the Log instance using argument or create new instance
665
+         * @param object $logger the Log instance if not null
666
+         */
667 667
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
668
-      if ($logger !== null){
668
+        if ($logger !== null){
669 669
         $this->logger = $logger;
670
-      }
671
-      else{
672
-          $this->logger =& class_loader('Log', 'classes');
673
-          $this->logger->setLogger('Library::Database');
674
-      }
670
+        }
671
+        else{
672
+            $this->logger =& class_loader('Log', 'classes');
673
+            $this->logger->setLogger('Library::Database');
674
+        }
675 675
     }
676 676
 	
677
-   /**
678
-   * Set the DatabaseQueryBuilder instance using argument or create new instance
679
-   * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
680
-   */
681
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
682
-	  if ($queryBuilder !== null){
677
+    /**
678
+     * Set the DatabaseQueryBuilder instance using argument or create new instance
679
+     * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
680
+     */
681
+    protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
682
+        if ($queryBuilder !== null){
683 683
         $this->queryBuilder = $queryBuilder;
684
-	  }
685
-	  else{
686
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
687
-	  }
688
-	}
689
-
690
-  /**
691
-   * Set the DatabaseQueryRunner instance using argument or create new instance
692
-   * @param object $queryRunner the DatabaseQueryRunner instance if not null
693
-   */
694
-  protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
684
+        }
685
+        else{
686
+            $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
687
+        }
688
+    }
689
+
690
+    /**
691
+     * Set the DatabaseQueryRunner instance using argument or create new instance
692
+     * @param object $queryRunner the DatabaseQueryRunner instance if not null
693
+     */
694
+    protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
695 695
     if ($queryRunner !== null){
696 696
         $this->queryRunner = $queryRunner;
697 697
     }
698 698
     else{
699
-      $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
699
+        $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
700
+    }
700 701
     }
701
-  }
702 702
 
703 703
     /**
704 704
      * Reset the database class attributs to the initail values before each query.
705 705
      */
706 706
     private function reset(){
707
-	   //query builder reset
708
-      $this->getQueryBuilder()->reset();
709
-      $this->numRows  = 0;
710
-      $this->insertId = null;
711
-      $this->query    = null;
712
-      $this->result   = array();
713
-      $this->data     = array();
707
+        //query builder reset
708
+        $this->getQueryBuilder()->reset();
709
+        $this->numRows  = 0;
710
+        $this->insertId = null;
711
+        $this->query    = null;
712
+        $this->result   = array();
713
+        $this->data     = array();
714 714
     }
715 715
 
716 716
     /**
717 717
      * The class destructor
718 718
      */
719 719
     public function __destruct(){
720
-      $this->pdo = null;
720
+        $this->pdo = null;
721 721
     }
722 722
 
723 723
 }
Please login to merge, or discard this patch.
Spacing   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -23,105 +23,105 @@  discard block
 block discarded – undo
23 23
    * along with this program; if not, write to the Free Software
24 24
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
   */
26
-  class Database{
26
+  class Database {
27 27
 	
28 28
   	/**
29 29
   	 * The PDO instance
30 30
   	 * @var object
31 31
   	*/
32
-    private $pdo                 = null;
32
+    private $pdo = null;
33 33
     
34 34
   	/**
35 35
   	 * The database name used for the application
36 36
   	 * @var string
37 37
   	*/
38
-	  private $databaseName        = null;
38
+	  private $databaseName = null;
39 39
 	
40 40
   	/**
41 41
   	 * The number of rows returned by the last query
42 42
   	 * @var int
43 43
   	*/
44
-    private $numRows             = 0;
44
+    private $numRows = 0;
45 45
 	
46 46
   	/**
47 47
   	 * The last insert id for the primary key column that have auto increment or sequence
48 48
   	 * @var mixed
49 49
   	*/
50
-    private $insertId            = null;
50
+    private $insertId = null;
51 51
 	
52 52
   	/**
53 53
   	 * The full SQL query statment after build for each command
54 54
   	 * @var string
55 55
   	*/
56
-    private $query               = null;
56
+    private $query = null;
57 57
 	
58 58
   	/**
59 59
   	 * The result returned for the last query
60 60
   	 * @var mixed
61 61
   	*/
62
-    private $result              = array();
62
+    private $result = array();
63 63
 	
64 64
   	/**
65 65
   	 * The cache default time to live in second. 0 means no need to use the cache feature
66 66
   	 * @var int
67 67
   	*/
68
-  	private $cacheTtl             = 0;
68
+  	private $cacheTtl = 0;
69 69
 	
70 70
   	/**
71 71
   	 * The cache current time to live. 0 means no need to use the cache feature
72 72
   	 * @var int
73 73
   	*/
74
-    private $temporaryCacheTtl   = 0;
74
+    private $temporaryCacheTtl = 0;
75 75
 	
76 76
   	/**
77 77
   	 * The number of executed query for the current request
78 78
   	 * @var int
79 79
   	*/
80
-    private $queryCount          = 0;
80
+    private $queryCount = 0;
81 81
 	
82 82
   	/**
83 83
   	 * The default data to be used in the statments query INSERT, UPDATE
84 84
   	 * @var array
85 85
   	*/
86
-    private $data                = array();
86
+    private $data = array();
87 87
 	
88 88
   	/**
89 89
   	 * The database configuration
90 90
   	 * @var array
91 91
   	*/
92
-    private $config              = array();
92
+    private $config = array();
93 93
 	
94 94
   	/**
95 95
   	 * The logger instance
96 96
   	 * @var object
97 97
   	 */
98
-    private $logger              = null;
98
+    private $logger = null;
99 99
 
100 100
     /**
101 101
     * The cache instance
102 102
     * @var object
103 103
     */
104
-    private $cacheInstance       = null;
104
+    private $cacheInstance = null;
105 105
 
106 106
     
107 107
   	/**
108 108
     * The DatabaseQueryBuilder instance
109 109
     * @var object
110 110
     */
111
-    private $queryBuilder        = null;
111
+    private $queryBuilder = null;
112 112
     
113 113
     /**
114 114
     * The DatabaseQueryRunner instance
115 115
     * @var object
116 116
     */
117
-    private $queryRunner         = null;
117
+    private $queryRunner = null;
118 118
 
119 119
 
120 120
     /**
121 121
      * Construct new database
122 122
      * @param array $overwriteConfig the config to overwrite with the config set in database.php
123 123
      */
124
-    public function __construct($overwriteConfig = array()){
124
+    public function __construct($overwriteConfig = array()) {
125 125
         //Set Log instance to use
126 126
         $this->setLoggerFromParamOrCreateNewInstance(null);
127 127
 		
@@ -142,17 +142,17 @@  discard block
 block discarded – undo
142 142
      * This is used to connect to database
143 143
      * @return bool 
144 144
      */
145
-    public function connect(){
145
+    public function connect() {
146 146
       $config = $this->getDatabaseConfiguration();
147
-      if (! empty($config)){
148
-        try{
147
+      if (!empty($config)) {
148
+        try {
149 149
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
150 150
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
151 151
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
152 152
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
153 153
             return true;
154 154
           }
155
-          catch (PDOException $e){
155
+          catch (PDOException $e) {
156 156
             $this->logger->fatal($e->getMessage());
157 157
             show_error('Cannot connect to Database.');
158 158
             return false;
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
      * Return the number of rows returned by the current query
167 167
      * @return int
168 168
      */
169
-    public function numRows(){
169
+    public function numRows() {
170 170
       return $this->numRows;
171 171
     }
172 172
 
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
      * Return the last insert id value
175 175
      * @return mixed
176 176
      */
177
-    public function insertId(){
177
+    public function insertId() {
178 178
       return $this->insertId;
179 179
     }
180 180
 
@@ -185,10 +185,10 @@  discard block
 block discarded – undo
185 185
      * If is string will determine the result type "array" or "object"
186 186
      * @return mixed       the query SQL string or the record result
187 187
      */
188
-    public function get($returnSQLQueryOrResultType = false){
188
+    public function get($returnSQLQueryOrResultType = false) {
189 189
       $this->getQueryBuilder()->limit(1);
190 190
       $query = $this->getAll(true);
191
-      if ($returnSQLQueryOrResultType === true){
191
+      if ($returnSQLQueryOrResultType === true) {
192 192
         return $query;
193 193
       } else {
194 194
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
@@ -201,9 +201,9 @@  discard block
 block discarded – undo
201 201
      * If is string will determine the result type "array" or "object"
202 202
      * @return mixed       the query SQL string or the record result
203 203
      */
204
-    public function getAll($returnSQLQueryOrResultType = false){
204
+    public function getAll($returnSQLQueryOrResultType = false) {
205 205
 	   $query = $this->getQueryBuilder()->getQuery();
206
-	   if ($returnSQLQueryOrResultType === true){
206
+	   if ($returnSQLQueryOrResultType === true) {
207 207
       	return $query;
208 208
       }
209 209
       return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
      * @param  boolean $escape  whether to escape or not the values
216 216
      * @return mixed          the insert id of the new record or null
217 217
      */
218
-    public function insert($data = array(), $escape = true){
219
-      if (empty($data) && $this->getData()){
218
+    public function insert($data = array(), $escape = true) {
219
+      if (empty($data) && $this->getData()) {
220 220
         //as when using $this->setData() may be the data already escaped
221 221
         $escape = false;
222 222
         $data = $this->getData();
223 223
       }
224 224
       $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
225 225
       $result = $this->query($query);
226
-      if ($result){
226
+      if ($result) {
227 227
         $this->insertId = $this->pdo->lastInsertId();
228 228
 		    //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
229
-        return ! $this->insertId() ? true : $this->insertId();
229
+        return !$this->insertId() ? true : $this->insertId();
230 230
       }
231 231
       return false;
232 232
     }
@@ -237,8 +237,8 @@  discard block
 block discarded – undo
237 237
      * @param  boolean $escape  whether to escape or not the values
238 238
      * @return mixed          the update status
239 239
      */
240
-    public function update($data = array(), $escape = true){
241
-      if (empty($data) && $this->getData()){
240
+    public function update($data = array(), $escape = true) {
241
+      if (empty($data) && $this->getData()) {
242 242
         //as when using $this->setData() may be the data already escaped
243 243
         $escape = false;
244 244
         $data = $this->getData();
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
      * Delete the record in database
252 252
      * @return mixed the delete status
253 253
      */
254
-    public function delete(){
254
+    public function delete() {
255 255
 		$query = $this->getQueryBuilder()->delete()->getQuery();
256 256
     	return $this->query($query);
257 257
     }
@@ -261,8 +261,8 @@  discard block
 block discarded – undo
261 261
      * @param integer $ttl the cache time to live in second
262 262
      * @return object        the current Database instance
263 263
      */
264
-    public function setCache($ttl = 0){
265
-      if ($ttl > 0){
264
+    public function setCache($ttl = 0) {
265
+      if ($ttl > 0) {
266 266
         $this->cacheTtl = $ttl;
267 267
         $this->temporaryCacheTtl = $ttl;
268 268
       }
@@ -274,8 +274,8 @@  discard block
 block discarded – undo
274 274
 	 * @param  integer $ttl the cache time to live in second
275 275
 	 * @return object        the current Database instance
276 276
 	 */
277
-  	public function cached($ttl = 0){
278
-        if ($ttl > 0){
277
+  	public function cached($ttl = 0) {
278
+        if ($ttl > 0) {
279 279
           $this->temporaryCacheTtl = $ttl;
280 280
         }
281 281
         return $this;
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
      * @param boolean $escaped whether we can do escape of not 
288 288
      * @return mixed       the data after escaped or the same data if not
289 289
      */
290
-    public function escape($data, $escaped = true){
290
+    public function escape($data, $escaped = true) {
291 291
       return $escaped ? 
292 292
                       $this->pdo->quote(trim($data)) 
293 293
                       : $data; 
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
      * Return the number query executed count for the current request
298 298
      * @return int
299 299
      */
300
-    public function queryCount(){
300
+    public function queryCount() {
301 301
       return $this->queryCount;
302 302
     }
303 303
 
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
      * Return the current query SQL string
306 306
      * @return string
307 307
      */
308
-    public function getQuery(){
308
+    public function getQuery() {
309 309
       return $this->query;
310 310
     }
311 311
 
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
      * Return the application database name
314 314
      * @return string
315 315
      */
316
-    public function getDatabaseName(){
316
+    public function getDatabaseName() {
317 317
       return $this->databaseName;
318 318
     }
319 319
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
      * Return the PDO instance
322 322
      * @return object
323 323
      */
324
-    public function getPdo(){
324
+    public function getPdo() {
325 325
       return $this->pdo;
326 326
     }
327 327
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
      * @param object $pdo the pdo object
331 331
 	 * @return object Database
332 332
      */
333
-    public function setPdo(PDO $pdo){
333
+    public function setPdo(PDO $pdo) {
334 334
       $this->pdo = $pdo;
335 335
       return $this;
336 336
     }
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
      * Return the Log instance
341 341
      * @return Log
342 342
      */
343
-    public function getLogger(){
343
+    public function getLogger() {
344 344
       return $this->logger;
345 345
     }
346 346
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
      * @param Log $logger the log object
350 350
 	 * @return object Database
351 351
      */
352
-    public function setLogger($logger){
352
+    public function setLogger($logger) {
353 353
       $this->logger = $logger;
354 354
       return $this;
355 355
     }
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
      * Return the cache instance
359 359
      * @return CacheInterface
360 360
      */
361
-    public function getCacheInstance(){
361
+    public function getCacheInstance() {
362 362
       return $this->cacheInstance;
363 363
     }
364 364
 
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
      * @param CacheInterface $cache the cache object
368 368
 	 * @return object Database
369 369
      */
370
-    public function setCacheInstance($cache){
370
+    public function setCacheInstance($cache) {
371 371
       $this->cacheInstance = $cache;
372 372
       return $this;
373 373
     }
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
      * Return the DatabaseQueryBuilder instance
378 378
      * @return object DatabaseQueryBuilder
379 379
      */
380
-    public function getQueryBuilder(){
380
+    public function getQueryBuilder() {
381 381
       return $this->queryBuilder;
382 382
     }
383 383
 
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
      * Set the DatabaseQueryBuilder instance
386 386
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
387 387
      */
388
-    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
388
+    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder) {
389 389
       $this->queryBuilder = $queryBuilder;
390 390
       return $this;
391 391
     }
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
      * Return the DatabaseQueryRunner instance
395 395
      * @return object DatabaseQueryRunner
396 396
      */
397
-    public function getQueryRunner(){
397
+    public function getQueryRunner() {
398 398
       return $this->queryRunner;
399 399
     }
400 400
 
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
      * Set the DatabaseQueryRunner instance
403 403
      * @param object DatabaseQueryRunner $queryRunner the DatabaseQueryRunner object
404 404
      */
405
-    public function setQueryRunner(DatabaseQueryRunner $queryRunner){
405
+    public function setQueryRunner(DatabaseQueryRunner $queryRunner) {
406 406
       $this->queryRunner = $queryRunner;
407 407
       return $this;
408 408
     }
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
      * Return the data to be used for insert, update, etc.
412 412
      * @return array
413 413
      */
414
-    public function getData(){
414
+    public function getData() {
415 415
       return $this->data;
416 416
     }
417 417
 
@@ -422,9 +422,9 @@  discard block
 block discarded – undo
422 422
      * @param boolean $escape whether to escape or not the $value
423 423
      * @return object        the current Database instance
424 424
      */
425
-    public function setData($key, $value = null, $escape = true){
426
-  	  if(is_array($key)){
427
-    		foreach($key as $k => $v){
425
+    public function setData($key, $value = null, $escape = true) {
426
+  	  if (is_array($key)) {
427
+    		foreach ($key as $k => $v) {
428 428
     			$this->setData($k, $v, $escape);
429 429
     		}	
430 430
   	  } else {
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
      * @param  boolean $returnAsArray return the result as array or not
441 441
      * @return mixed         the query result
442 442
      */
443
-    public function query($query, $returnAsList = true, $returnAsArray = false){
443
+    public function query($query, $returnAsList = true, $returnAsArray = false) {
444 444
       $this->reset();
445 445
       $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
446 446
       //If is the SELECT query
@@ -461,12 +461,12 @@  discard block
 block discarded – undo
461 461
       //if can use cache feature for this query
462 462
       $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
463 463
     
464
-      if ($dbCacheStatus && $isSqlSELECTQuery){
464
+      if ($dbCacheStatus && $isSqlSELECTQuery) {
465 465
           $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
466 466
           $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
467 467
       }
468 468
       
469
-      if (!$cacheContent){
469
+      if (!$cacheContent) {
470 470
   	   	//count the number of query execution to server
471 471
         $this->queryCount++;
472 472
         
@@ -475,19 +475,19 @@  discard block
 block discarded – undo
475 475
                           ->setReturnAsArray($returnAsArray);
476 476
         
477 477
         $queryResult = $this->queryRunner->execute();
478
-        if (is_object($queryResult)){
478
+        if (is_object($queryResult)) {
479 479
             $this->result  = $queryResult->getResult();
480 480
             $this->numRows = $queryResult->getNumRows();
481
-            if ($isSqlSELECTQuery && $dbCacheStatus){
481
+            if ($isSqlSELECTQuery && $dbCacheStatus) {
482 482
                 $key = $this->getCacheKeyForQuery($this->query, $returnAsList, $returnAsArray);
483 483
                 $this->setCacheContentForQuery($this->query, $key, $this->result, $cacheExpire);
484
-            if (! $this->result){
484
+            if (!$this->result) {
485 485
               $this->logger->info('No result where found for the query [' . $query . ']');
486 486
             }
487 487
           }
488 488
         }
489
-      } else if ($isSqlSELECTQuery){
490
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
489
+      } else if ($isSqlSELECTQuery) {
490
+          $this->logger->info('The result for query [' . $this->query . '] already cached use it');
491 491
           $this->result = $cacheContent;
492 492
           $this->numRows = count($this->result);
493 493
       }
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 	 * Return the database configuration
500 500
 	 * @return array
501 501
 	 */
502
-  	public  function getDatabaseConfiguration(){
502
+  	public  function getDatabaseConfiguration() {
503 503
   	  return $this->config;
504 504
   	}
505 505
 
@@ -509,9 +509,9 @@  discard block
 block discarded – undo
509 509
     * @param boolean $useConfigFile whether to use database configuration file
510 510
 	  * @return object Database
511 511
     */
512
-    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
512
+    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
513 513
         $db = array();
514
-        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
514
+        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')) {
515 515
             //here don't use require_once because somewhere user can create database instance directly
516 516
             require CONFIG_PATH . 'database.php';
517 517
         }
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
     	//determine the port using the hostname like localhost:3307
537 537
       //hostname will be "localhost", and port "3307"
538 538
       $p = explode(':', $config['hostname']);
539
-  	  if (count($p) >= 2){
539
+  	  if (count($p) >= 2) {
540 540
   		  $config['hostname'] = $p[0];
541 541
   		  $config['port'] = $p[1];
542 542
   		}
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
     /**
564 564
      * Close the connexion
565 565
      */
566
-    public function close(){
566
+    public function close() {
567 567
       $this->pdo = null;
568 568
     }
569 569
 
@@ -571,16 +571,16 @@  discard block
 block discarded – undo
571 571
      * Update the DatabaseQueryBuilder and DatabaseQueryRunner properties
572 572
      * @return void
573 573
      */
574
-    protected function updateQueryBuilderAndRunnerProperties(){
574
+    protected function updateQueryBuilderAndRunnerProperties() {
575 575
        //update queryBuilder with some properties needed
576
-     if(is_object($this->queryBuilder)){
576
+     if (is_object($this->queryBuilder)) {
577 577
         $this->queryBuilder->setDriver($this->config['driver'])
578 578
                            ->setPrefix($this->config['prefix'])
579 579
                            ->setPdo($this->pdo);
580 580
      }
581 581
 
582 582
       //update queryRunner with some properties needed
583
-     if(is_object($this->queryRunner)){
583
+     if (is_object($this->queryRunner)) {
584 584
         $this->queryRunner->setDriver($this->config['driver'])
585 585
                           ->setPdo($this->pdo);
586 586
      }
@@ -591,9 +591,9 @@  discard block
 block discarded – undo
591 591
      * This method is used to get the PDO DSN string using the configured driver
592 592
      * @return string the DSN string
593 593
      */
594
-    protected function getDsnFromDriver(){
594
+    protected function getDsnFromDriver() {
595 595
       $config = $this->getDatabaseConfiguration();
596
-      if (! empty($config)){
596
+      if (!empty($config)) {
597 597
         $driver = $config['driver'];
598 598
         $driverDsnMap = array(
599 599
                               'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
@@ -618,9 +618,9 @@  discard block
 block discarded – undo
618 618
      *      
619 619
      * @return mixed
620 620
      */
621
-    protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray){
621
+    protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray) {
622 622
         $cacheKey = $this->getCacheKeyForQuery($query, $returnAsList, $returnAsArray);
623
-        if (! is_object($this->cacheInstance)){
623
+        if (!is_object($this->cacheInstance)) {
624 624
     			//can not call method with reference in argument
625 625
     			//like $this->setCacheInstance(& get_instance()->cache);
626 626
     			//use temporary variable
@@ -637,9 +637,9 @@  discard block
 block discarded – undo
637 637
      * @param mixed $result the query result to save
638 638
      * @param int $expire the cache TTL
639 639
      */
640
-     protected function setCacheContentForQuery($query, $key, $result, $expire){
641
-        $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
642
-        if (! is_object($this->cacheInstance)){
640
+     protected function setCacheContentForQuery($query, $key, $result, $expire) {
641
+        $this->logger->info('Save the result for query [' . $query . '] into cache for future use');
642
+        if (!is_object($this->cacheInstance)) {
643 643
   				//can not call method with reference in argument
644 644
   				//like $this->setCacheInstance(& get_instance()->cache);
645 645
   				//use temporary variable
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
      * 
657 657
      *  @return string
658 658
      */
659
-    protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray){
659
+    protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray) {
660 660
       return md5($query . $returnAsList . $returnAsArray);
661 661
     }
662 662
     
@@ -664,12 +664,12 @@  discard block
 block discarded – undo
664 664
      * Set the Log instance using argument or create new instance
665 665
      * @param object $logger the Log instance if not null
666 666
      */
667
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
668
-      if ($logger !== null){
667
+    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
668
+      if ($logger !== null) {
669 669
         $this->logger = $logger;
670 670
       }
671
-      else{
672
-          $this->logger =& class_loader('Log', 'classes');
671
+      else {
672
+          $this->logger = & class_loader('Log', 'classes');
673 673
           $this->logger->setLogger('Library::Database');
674 674
       }
675 675
     }
@@ -678,12 +678,12 @@  discard block
 block discarded – undo
678 678
    * Set the DatabaseQueryBuilder instance using argument or create new instance
679 679
    * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
680 680
    */
681
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
682
-	  if ($queryBuilder !== null){
681
+	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null) {
682
+	  if ($queryBuilder !== null) {
683 683
         $this->queryBuilder = $queryBuilder;
684 684
 	  }
685
-	  else{
686
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
685
+	  else {
686
+		  $this->queryBuilder = & class_loader('DatabaseQueryBuilder', 'classes/database');
687 687
 	  }
688 688
 	}
689 689
 
@@ -691,19 +691,19 @@  discard block
 block discarded – undo
691 691
    * Set the DatabaseQueryRunner instance using argument or create new instance
692 692
    * @param object $queryRunner the DatabaseQueryRunner instance if not null
693 693
    */
694
-  protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
695
-    if ($queryRunner !== null){
694
+  protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null) {
695
+    if ($queryRunner !== null) {
696 696
         $this->queryRunner = $queryRunner;
697 697
     }
698
-    else{
699
-      $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
698
+    else {
699
+      $this->queryRunner = & class_loader('DatabaseQueryRunner', 'classes/database');
700 700
     }
701 701
   }
702 702
 
703 703
     /**
704 704
      * Reset the database class attributs to the initail values before each query.
705 705
      */
706
-    private function reset(){
706
+    private function reset() {
707 707
 	   //query builder reset
708 708
       $this->getQueryBuilder()->reset();
709 709
       $this->numRows  = 0;
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
     /**
717 717
      * The class destructor
718 718
      */
719
-    public function __destruct(){
719
+    public function __destruct() {
720 720
       $this->pdo = null;
721 721
     }
722 722
 
Please login to merge, or discard this patch.
core/classes/Response.php 3 patches
Indentation   +401 added lines, -401 removed lines patch added patch discarded remove patch
@@ -1,441 +1,441 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Response{
27
+    class Response{
28 28
 
29
-		/**
30
-		 * The list of request header to send with response
31
-		 * @var array
32
-		 */
33
-		private static $headers = array();
29
+        /**
30
+         * The list of request header to send with response
31
+         * @var array
32
+         */
33
+        private static $headers = array();
34 34
 
35
-		/**
36
-		 * The logger instance
37
-		 * @var Log
38
-		 */
39
-		private static $logger;
35
+        /**
36
+         * The logger instance
37
+         * @var Log
38
+         */
39
+        private static $logger;
40 40
 		
41
-		/**
42
-		 * The final page content to display to user
43
-		 * @var string
44
-		 */
45
-		private $_pageRender = null;
41
+        /**
42
+         * The final page content to display to user
43
+         * @var string
44
+         */
45
+        private $_pageRender = null;
46 46
 		
47
-		/**
48
-		 * The current request URL
49
-		 * @var string
50
-		 */
51
-		private $_currentUrl = null;
47
+        /**
48
+         * The current request URL
49
+         * @var string
50
+         */
51
+        private $_currentUrl = null;
52 52
 		
53
-		/**
54
-		 * The current request URL cache key
55
-		 * @var string
56
-		 */
57
-		private $_currentUrlCacheKey = null;
53
+        /**
54
+         * The current request URL cache key
55
+         * @var string
56
+         */
57
+        private $_currentUrlCacheKey = null;
58 58
 		
59
-		/**
60
-		* Whether we can compress the output using Gzip
61
-		* @var boolean
62
-		*/
63
-		private static $_canCompressOutput = false;
59
+        /**
60
+         * Whether we can compress the output using Gzip
61
+         * @var boolean
62
+         */
63
+        private static $_canCompressOutput = false;
64 64
 		
65
-		/**
66
-		 * Construct new response instance
67
-		 */
68
-		public function __construct(){
69
-			$currentUrl = '';
70
-			if (! empty($_SERVER['REQUEST_URI'])){
71
-				$currentUrl = $_SERVER['REQUEST_URI'];
72
-			}
73
-			if (! empty($_SERVER['QUERY_STRING'])){
74
-				$currentUrl .= '?' . $_SERVER['QUERY_STRING'];
75
-			}
76
-			$this->_currentUrl =  $currentUrl;
65
+        /**
66
+         * Construct new response instance
67
+         */
68
+        public function __construct(){
69
+            $currentUrl = '';
70
+            if (! empty($_SERVER['REQUEST_URI'])){
71
+                $currentUrl = $_SERVER['REQUEST_URI'];
72
+            }
73
+            if (! empty($_SERVER['QUERY_STRING'])){
74
+                $currentUrl .= '?' . $_SERVER['QUERY_STRING'];
75
+            }
76
+            $this->_currentUrl =  $currentUrl;
77 77
 					
78
-			$this->_currentUrlCacheKey = md5($this->_currentUrl);
78
+            $this->_currentUrlCacheKey = md5($this->_currentUrl);
79 79
 			
80
-			self::$_canCompressOutput = get_config('compress_output')
81
-										  && isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
82
-										  && stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false 
83
-										  && extension_loaded('zlib')
84
-										  && (bool) ini_get('zlib.output_compression') === false;
85
-		}
80
+            self::$_canCompressOutput = get_config('compress_output')
81
+                                          && isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
82
+                                          && stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false 
83
+                                          && extension_loaded('zlib')
84
+                                          && (bool) ini_get('zlib.output_compression') === false;
85
+        }
86 86
 
87
-		/**
88
-		 * Get the logger singleton instance
89
-		 * @return Log the logger instance
90
-		 */
91
-		private static function getLogger(){
92
-			if(self::$logger == null){
93
-				self::$logger[0] =& class_loader('Log', 'classes');
94
-				self::$logger[0]->setLogger('Library::Response');
95
-			}
96
-			return self::$logger[0];
97
-		}
87
+        /**
88
+         * Get the logger singleton instance
89
+         * @return Log the logger instance
90
+         */
91
+        private static function getLogger(){
92
+            if(self::$logger == null){
93
+                self::$logger[0] =& class_loader('Log', 'classes');
94
+                self::$logger[0]->setLogger('Library::Response');
95
+            }
96
+            return self::$logger[0];
97
+        }
98 98
 
99
-		/**
100
-		 * Send the HTTP Response headers
101
-		 * @param  integer $httpCode the HTTP status code
102
-		 * @param  array   $headers   the additional headers to add to the existing headers list
103
-		 */
104
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
105
-			set_http_status_header($httpCode);
106
-			self::setHeaders($headers);
107
-			if(! headers_sent()){
108
-				foreach(self::getHeaders() as $key => $value){
109
-					header($key .': '.$value);
110
-				}
111
-			}
112
-		}
99
+        /**
100
+         * Send the HTTP Response headers
101
+         * @param  integer $httpCode the HTTP status code
102
+         * @param  array   $headers   the additional headers to add to the existing headers list
103
+         */
104
+        public static function sendHeaders($httpCode = 200, array $headers = array()){
105
+            set_http_status_header($httpCode);
106
+            self::setHeaders($headers);
107
+            if(! headers_sent()){
108
+                foreach(self::getHeaders() as $key => $value){
109
+                    header($key .': '.$value);
110
+                }
111
+            }
112
+        }
113 113
 
114
-		/**
115
-		 * Get the list of the headers
116
-		 * @return array the headers list
117
-		 */
118
-		public static function getHeaders(){
119
-			return self::$headers;
120
-		}
114
+        /**
115
+         * Get the list of the headers
116
+         * @return array the headers list
117
+         */
118
+        public static function getHeaders(){
119
+            return self::$headers;
120
+        }
121 121
 
122
-		/**
123
-		 * Get the header value for the given name
124
-		 * @param  string $name the header name
125
-		 * @return string       the header value
126
-		 */
127
-		public static function getHeader($name){
128
-			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
129
-		}
122
+        /**
123
+         * Get the header value for the given name
124
+         * @param  string $name the header name
125
+         * @return string       the header value
126
+         */
127
+        public static function getHeader($name){
128
+            return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
129
+        }
130 130
 
131 131
 
132
-		/**
133
-		 * Set the header value for the specified name
134
-		 * @param string $name  the header name
135
-		 * @param string $value the header value to be set
136
-		 */
137
-		public static function setHeader($name, $value){
138
-			self::$headers[$name] = $value;
139
-		}
132
+        /**
133
+         * Set the header value for the specified name
134
+         * @param string $name  the header name
135
+         * @param string $value the header value to be set
136
+         */
137
+        public static function setHeader($name, $value){
138
+            self::$headers[$name] = $value;
139
+        }
140 140
 
141
-		/**
142
-		 * Set the headers using array
143
-		 * @param array $headers the list of the headers to set. 
144
-		 * Note: this will merge with the existing headers
145
-		 */
146
-		public static function setHeaders(array $headers){
147
-			self::$headers = array_merge(self::getHeaders(), $headers);
148
-		}
141
+        /**
142
+         * Set the headers using array
143
+         * @param array $headers the list of the headers to set. 
144
+         * Note: this will merge with the existing headers
145
+         */
146
+        public static function setHeaders(array $headers){
147
+            self::$headers = array_merge(self::getHeaders(), $headers);
148
+        }
149 149
 		
150
-		/**
151
-		 * Redirect user in the specified page
152
-		 * @param  string $path the URL or URI to be redirect to
153
-		 */
154
-		public static function redirect($path = ''){
155
-			$logger = self::getLogger();
156
-			$url = Url::site_url($path);
157
-			$logger->info('Redirect to URL [' .$url. ']');
158
-			if(! headers_sent()){
159
-				header('Location: '.$url);
160
-				exit;
161
-			}
162
-			else{
163
-				echo '<script>
150
+        /**
151
+         * Redirect user in the specified page
152
+         * @param  string $path the URL or URI to be redirect to
153
+         */
154
+        public static function redirect($path = ''){
155
+            $logger = self::getLogger();
156
+            $url = Url::site_url($path);
157
+            $logger->info('Redirect to URL [' .$url. ']');
158
+            if(! headers_sent()){
159
+                header('Location: '.$url);
160
+                exit;
161
+            }
162
+            else{
163
+                echo '<script>
164 164
 						location.href = "'.$url.'";
165 165
 					</script>';
166
-			}
167
-		}
166
+            }
167
+        }
168 168
 
169
-		/**
170
-		 * Render the view to display later or return the content
171
-		 * @param  string  $view   the view name or path
172
-		 * @param  array|object   $data   the variable data to use in the view
173
-		 * @param  boolean $return whether to return the view generated content or display it directly
174
-		 * @return void|string          if $return is true will return the view content otherwise
175
-		 * will display the view content.
176
-		 */
177
-		public function render($view, $data = null, $return = false){
178
-			$logger = self::getLogger();
179
-			//convert data to an array
180
-			$data = ! is_array($data) ? (array) $data : $data;
181
-			$view = str_ireplace('.php', '', $view);
182
-			$view = trim($view, '/\\');
183
-			$viewFile = $view . '.php';
184
-			$path = APPS_VIEWS_PATH . $viewFile;
169
+        /**
170
+         * Render the view to display later or return the content
171
+         * @param  string  $view   the view name or path
172
+         * @param  array|object   $data   the variable data to use in the view
173
+         * @param  boolean $return whether to return the view generated content or display it directly
174
+         * @return void|string          if $return is true will return the view content otherwise
175
+         * will display the view content.
176
+         */
177
+        public function render($view, $data = null, $return = false){
178
+            $logger = self::getLogger();
179
+            //convert data to an array
180
+            $data = ! is_array($data) ? (array) $data : $data;
181
+            $view = str_ireplace('.php', '', $view);
182
+            $view = trim($view, '/\\');
183
+            $viewFile = $view . '.php';
184
+            $path = APPS_VIEWS_PATH . $viewFile;
185 185
 			
186
-			//super instance
187
-			$obj = & get_instance();
186
+            //super instance
187
+            $obj = & get_instance();
188 188
 			
189
-			if(Module::hasModule()){
190
-				//check in module first
191
-				$logger->debug('Checking the view [' . $view . '] from module list ...');
192
-				$mod = null;
193
-				//check if the request class contains module name
194
-				if(strpos($view, '/') !== false){
195
-					$viewPath = explode('/', $view);
196
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
197
-						$mod = $viewPath[0];
198
-						array_shift($viewPath);
199
-						$view = implode('/', $viewPath);
200
-						$viewFile = $view . '.php';
201
-					}
202
-				}
203
-				if(! $mod && !empty($obj->moduleName)){
204
-					$mod = $obj->moduleName;
205
-				}
206
-				if($mod){
207
-					$moduleViewPath = Module::findViewFullPath($view, $mod);
208
-					if($moduleViewPath){
209
-						$path = $moduleViewPath;
210
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
211
-					}
212
-					else{
213
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
214
-					}
215
-				}
216
-				else{
217
-					$logger->info('The current request does not use module using the default location.');
218
-				}
219
-			}
220
-			$logger->info('The view file path to be loaded is [' . $path . ']');
221
-			$found = false;
222
-			if(file_exists($path)){
223
-				foreach(get_object_vars($obj) as $key => $value){
224
-					if(! isset($this->{$key})){
225
-						$this->{$key} = & $obj->{$key};
226
-					}
227
-				}
228
-				ob_start();
229
-				extract($data);
230
-				//need use require() instead of require_once because can load this view many time
231
-				require $path;
232
-				$content = ob_get_clean();
233
-				if($return){
234
-					return $content;
235
-				}
236
-				$this->_pageRender .= $content;
237
-				$found = true;
238
-			}
239
-			if(! $found){
240
-				show_error('Unable to find view [' .$view . ']');
241
-			}
242
-		}
189
+            if(Module::hasModule()){
190
+                //check in module first
191
+                $logger->debug('Checking the view [' . $view . '] from module list ...');
192
+                $mod = null;
193
+                //check if the request class contains module name
194
+                if(strpos($view, '/') !== false){
195
+                    $viewPath = explode('/', $view);
196
+                    if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
197
+                        $mod = $viewPath[0];
198
+                        array_shift($viewPath);
199
+                        $view = implode('/', $viewPath);
200
+                        $viewFile = $view . '.php';
201
+                    }
202
+                }
203
+                if(! $mod && !empty($obj->moduleName)){
204
+                    $mod = $obj->moduleName;
205
+                }
206
+                if($mod){
207
+                    $moduleViewPath = Module::findViewFullPath($view, $mod);
208
+                    if($moduleViewPath){
209
+                        $path = $moduleViewPath;
210
+                        $logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
211
+                    }
212
+                    else{
213
+                        $logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
214
+                    }
215
+                }
216
+                else{
217
+                    $logger->info('The current request does not use module using the default location.');
218
+                }
219
+            }
220
+            $logger->info('The view file path to be loaded is [' . $path . ']');
221
+            $found = false;
222
+            if(file_exists($path)){
223
+                foreach(get_object_vars($obj) as $key => $value){
224
+                    if(! isset($this->{$key})){
225
+                        $this->{$key} = & $obj->{$key};
226
+                    }
227
+                }
228
+                ob_start();
229
+                extract($data);
230
+                //need use require() instead of require_once because can load this view many time
231
+                require $path;
232
+                $content = ob_get_clean();
233
+                if($return){
234
+                    return $content;
235
+                }
236
+                $this->_pageRender .= $content;
237
+                $found = true;
238
+            }
239
+            if(! $found){
240
+                show_error('Unable to find view [' .$view . ']');
241
+            }
242
+        }
243 243
 		
244
-		/**
245
-		* Send the final page output to user
246
-		*/
247
-		public function renderFinalPage(){
248
-			$logger = self::getLogger();
249
-			$obj = & get_instance();
250
-			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
251
-			$dispatcher = $obj->eventdispatcher;
252
-			$content = $this->_pageRender;
253
-			if(! $content){
254
-				$logger->warning('The final view content is empty.');
255
-				return;
256
-			}
257
-			//dispatch
258
-			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
259
-			$content = ! empty($event->payload) ? $event->payload : null;
260
-			if(empty($content)){
261
-				$logger->warning('The view content is empty after dispatch to event listeners.');
262
-			}
244
+        /**
245
+         * Send the final page output to user
246
+         */
247
+        public function renderFinalPage(){
248
+            $logger = self::getLogger();
249
+            $obj = & get_instance();
250
+            $cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
251
+            $dispatcher = $obj->eventdispatcher;
252
+            $content = $this->_pageRender;
253
+            if(! $content){
254
+                $logger->warning('The final view content is empty.');
255
+                return;
256
+            }
257
+            //dispatch
258
+            $event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
259
+            $content = ! empty($event->payload) ? $event->payload : null;
260
+            if(empty($content)){
261
+                $logger->warning('The view content is empty after dispatch to event listeners.');
262
+            }
263 263
 			
264
-			//check whether need save the page into cache.
265
-			if($cachePageStatus){
266
-				//current page URL
267
-				$url = $this->_currentUrl;
268
-				//Cache view Time to live in second
269
-				$viewCacheTtl = get_config('cache_ttl');
270
-				if (!empty($obj->view_cache_ttl)){
271
-					$viewCacheTtl = $obj->view_cache_ttl;
272
-				}
273
-				//the cache handler instance
274
-				$cacheInstance = $obj->cache;
275
-				//the current page cache key for identification
276
-				$cacheKey = $this->_currentUrlCacheKey;
264
+            //check whether need save the page into cache.
265
+            if($cachePageStatus){
266
+                //current page URL
267
+                $url = $this->_currentUrl;
268
+                //Cache view Time to live in second
269
+                $viewCacheTtl = get_config('cache_ttl');
270
+                if (!empty($obj->view_cache_ttl)){
271
+                    $viewCacheTtl = $obj->view_cache_ttl;
272
+                }
273
+                //the cache handler instance
274
+                $cacheInstance = $obj->cache;
275
+                //the current page cache key for identification
276
+                $cacheKey = $this->_currentUrlCacheKey;
277 277
 				
278
-				$logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
279
-				$cacheInstance->set($cacheKey, $content, $viewCacheTtl);
278
+                $logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
279
+                $cacheInstance->set($cacheKey, $content, $viewCacheTtl);
280 280
 				
281
-				//get the cache information to prepare header to send to browser
282
-				$cacheInfo = $cacheInstance->getInfo($cacheKey);
283
-				if($cacheInfo){
284
-					$lastModified = $cacheInfo['mtime'];
285
-					$expire = $cacheInfo['expire'];
286
-					$maxAge = $expire - time();
287
-					self::setHeader('Pragma', 'public');
288
-					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
289
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
290
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
291
-				}
292
-			}
281
+                //get the cache information to prepare header to send to browser
282
+                $cacheInfo = $cacheInstance->getInfo($cacheKey);
283
+                if($cacheInfo){
284
+                    $lastModified = $cacheInfo['mtime'];
285
+                    $expire = $cacheInfo['expire'];
286
+                    $maxAge = $expire - time();
287
+                    self::setHeader('Pragma', 'public');
288
+                    self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
289
+                    self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
290
+                    self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
291
+                }
292
+            }
293 293
 			
294
-			// Parse out the elapsed time and memory usage,
295
-			// then swap the pseudo-variables with the data
296
-			$elapsedTime = $obj->benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
297
-			$memoryUsage	= round($obj->benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
298
-			$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
294
+            // Parse out the elapsed time and memory usage,
295
+            // then swap the pseudo-variables with the data
296
+            $elapsedTime = $obj->benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
297
+            $memoryUsage	= round($obj->benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
298
+            $content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
299 299
 			
300
-			//compress the output if is available
301
-			$type = null;
302
-			if (self::$_canCompressOutput){
303
-				$type = 'ob_gzhandler';
304
-			}
305
-			ob_start($type);
306
-			self::sendHeaders(200);
307
-			echo $content;
308
-			ob_end_flush();
309
-		}
300
+            //compress the output if is available
301
+            $type = null;
302
+            if (self::$_canCompressOutput){
303
+                $type = 'ob_gzhandler';
304
+            }
305
+            ob_start($type);
306
+            self::sendHeaders(200);
307
+            echo $content;
308
+            ob_end_flush();
309
+        }
310 310
 		
311
-		/**
312
-		* Send the final page output to user if is cached
313
-		*/
314
-		public function renderFinalPageFromCache(&$cache){
315
-			$logger = self::getLogger();
316
-			$url = $this->_currentUrl;					
317
-			//the current page cache key for identification
318
-			$pageCacheKey = $this->_currentUrlCacheKey;
311
+        /**
312
+         * Send the final page output to user if is cached
313
+         */
314
+        public function renderFinalPageFromCache(&$cache){
315
+            $logger = self::getLogger();
316
+            $url = $this->_currentUrl;					
317
+            //the current page cache key for identification
318
+            $pageCacheKey = $this->_currentUrlCacheKey;
319 319
 			
320
-			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
321
-			//get the cache information to prepare header to send to browser
322
-			$cacheInfo = $cache->getInfo($pageCacheKey);
323
-			if($cacheInfo){
324
-				$lastModified = $cacheInfo['mtime'];
325
-				$expire = $cacheInfo['expire'];
326
-				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
327
-				self::setHeader('Pragma', 'public');
328
-				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
329
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
330
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
331
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
332
-					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
333
-					self::sendHeaders(304);
334
-					return;
335
-				}
336
-				$logger->info('The cache page content is expired or the browser doesn\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
337
-				self::sendHeaders(200);
338
-				//get the cache content
339
-				$content = $cache->get($pageCacheKey);
340
-				if($content){
341
-					$logger->info('The page content for the URL [' . $url . '] already cached just display it');
342
-					//load benchmark class
343
-					$benchmark = & class_loader('Benchmark');
320
+            $logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
321
+            //get the cache information to prepare header to send to browser
322
+            $cacheInfo = $cache->getInfo($pageCacheKey);
323
+            if($cacheInfo){
324
+                $lastModified = $cacheInfo['mtime'];
325
+                $expire = $cacheInfo['expire'];
326
+                $maxAge = $expire - $_SERVER['REQUEST_TIME'];
327
+                self::setHeader('Pragma', 'public');
328
+                self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
329
+                self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
330
+                self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
331
+                if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
332
+                    $logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
333
+                    self::sendHeaders(304);
334
+                    return;
335
+                }
336
+                $logger->info('The cache page content is expired or the browser doesn\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
337
+                self::sendHeaders(200);
338
+                //get the cache content
339
+                $content = $cache->get($pageCacheKey);
340
+                if($content){
341
+                    $logger->info('The page content for the URL [' . $url . '] already cached just display it');
342
+                    //load benchmark class
343
+                    $benchmark = & class_loader('Benchmark');
344 344
 					
345
-					// Parse out the elapsed time and memory usage,
346
-					// then swap the pseudo-variables with the data
347
-					$elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
348
-					$memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
349
-					$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
345
+                    // Parse out the elapsed time and memory usage,
346
+                    // then swap the pseudo-variables with the data
347
+                    $elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
348
+                    $memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
349
+                    $content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
350 350
 					
351
-					///display the final output
352
-					//compress the output if is available
353
-					$type = null;
354
-					if (self::$_canCompressOutput){
355
-						$type = 'ob_gzhandler';
356
-					}
357
-					ob_start($type);
358
-					echo $content;
359
-					ob_end_flush();
360
-					return;
361
-				}
362
-				else{
363
-					$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
364
-					$cache->delete($pageCacheKey);
365
-				}
351
+                    ///display the final output
352
+                    //compress the output if is available
353
+                    $type = null;
354
+                    if (self::$_canCompressOutput){
355
+                        $type = 'ob_gzhandler';
356
+                    }
357
+                    ob_start($type);
358
+                    echo $content;
359
+                    ob_end_flush();
360
+                    return;
361
+                }
362
+                else{
363
+                    $logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
364
+                    $cache->delete($pageCacheKey);
365
+                }
366 366
 				
367
-			}
368
-		}
367
+            }
368
+        }
369 369
 		
370
-		/**
371
-		* Get the final page to be rendered
372
-		* @return string
373
-		*/
374
-		public function getFinalPageRendered(){
375
-			return $this->_pageRender;
376
-		}
370
+        /**
371
+         * Get the final page to be rendered
372
+         * @return string
373
+         */
374
+        public function getFinalPageRendered(){
375
+            return $this->_pageRender;
376
+        }
377 377
 
378
-		/**
379
-		 * Send the HTTP 404 error if can not found the 
380
-		 * routing information for the current request
381
-		 */
382
-		public static function send404(){
383
-			/********* for logs **************/
384
-			//can't use $obj = & get_instance()  here because the global super object will be available until
385
-			//the main controller is loaded even for Loader::library('xxxx');
386
-			$logger = self::getLogger();
387
-			$request =& class_loader('Request', 'classes');
388
-			$userAgent =& class_loader('Browser');
389
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
378
+        /**
379
+         * Send the HTTP 404 error if can not found the 
380
+         * routing information for the current request
381
+         */
382
+        public static function send404(){
383
+            /********* for logs **************/
384
+            //can't use $obj = & get_instance()  here because the global super object will be available until
385
+            //the main controller is loaded even for Loader::library('xxxx');
386
+            $logger = self::getLogger();
387
+            $request =& class_loader('Request', 'classes');
388
+            $userAgent =& class_loader('Browser');
389
+            $browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
390 390
 			
391
-			//here can't use Loader::functions just include the helper manually
392
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
391
+            //here can't use Loader::functions just include the helper manually
392
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
393 393
 
394
-			$str = '[404 page not found] : ';
395
-			$str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
396
-			$logger->error($str);
397
-			/***********************************/
398
-			$path = CORE_VIEWS_PATH . '404.php';
399
-			if(file_exists($path)){
400
-				//compress the output if is available
401
-				$type = null;
402
-				if (self::$_canCompressOutput){
403
-					$type = 'ob_gzhandler';
404
-				}
405
-				ob_start($type);
406
-				require_once $path;
407
-				$output = ob_get_clean();
408
-				self::sendHeaders(404);
409
-				echo $output;
410
-			}
411
-			else{
412
-				show_error('The 404 view [' .$path. '] does not exist');
413
-			}
414
-		}
394
+            $str = '[404 page not found] : ';
395
+            $str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
396
+            $logger->error($str);
397
+            /***********************************/
398
+            $path = CORE_VIEWS_PATH . '404.php';
399
+            if(file_exists($path)){
400
+                //compress the output if is available
401
+                $type = null;
402
+                if (self::$_canCompressOutput){
403
+                    $type = 'ob_gzhandler';
404
+                }
405
+                ob_start($type);
406
+                require_once $path;
407
+                $output = ob_get_clean();
408
+                self::sendHeaders(404);
409
+                echo $output;
410
+            }
411
+            else{
412
+                show_error('The 404 view [' .$path. '] does not exist');
413
+            }
414
+        }
415 415
 
416
-		/**
417
-		 * Display the error to user
418
-		 * @param  array  $data the error information
419
-		 */
420
-		public static function sendError(array $data = array()){
421
-			$path = CORE_VIEWS_PATH . 'errors.php';
422
-			if(file_exists($path)){
423
-				//compress the output if is available
424
-				$type = null;
425
-				if (self::$_canCompressOutput){
426
-					$type = 'ob_gzhandler';
427
-				}
428
-				ob_start($type);
429
-				extract($data);
430
-				require_once $path;
431
-				$output = ob_get_clean();
432
-				self::sendHeaders(503);
433
-				echo $output;
434
-			}
435
-			else{
436
-				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
437
-				set_http_status_header(503);
438
-				echo 'The error view [' . $path . '] does not exist';
439
-			}
440
-		}
441
-	}
416
+        /**
417
+         * Display the error to user
418
+         * @param  array  $data the error information
419
+         */
420
+        public static function sendError(array $data = array()){
421
+            $path = CORE_VIEWS_PATH . 'errors.php';
422
+            if(file_exists($path)){
423
+                //compress the output if is available
424
+                $type = null;
425
+                if (self::$_canCompressOutput){
426
+                    $type = 'ob_gzhandler';
427
+                }
428
+                ob_start($type);
429
+                extract($data);
430
+                require_once $path;
431
+                $output = ob_get_clean();
432
+                self::sendHeaders(503);
433
+                echo $output;
434
+            }
435
+            else{
436
+                //can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
437
+                set_http_status_header(503);
438
+                echo 'The error view [' . $path . '] does not exist';
439
+            }
440
+        }
441
+    }
Please login to merge, or discard this patch.
Spacing   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Response{
27
+	class Response {
28 28
 
29 29
 		/**
30 30
 		 * The list of request header to send with response
@@ -65,15 +65,15 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Construct new response instance
67 67
 		 */
68
-		public function __construct(){
68
+		public function __construct() {
69 69
 			$currentUrl = '';
70
-			if (! empty($_SERVER['REQUEST_URI'])){
70
+			if (!empty($_SERVER['REQUEST_URI'])) {
71 71
 				$currentUrl = $_SERVER['REQUEST_URI'];
72 72
 			}
73
-			if (! empty($_SERVER['QUERY_STRING'])){
73
+			if (!empty($_SERVER['QUERY_STRING'])) {
74 74
 				$currentUrl .= '?' . $_SERVER['QUERY_STRING'];
75 75
 			}
76
-			$this->_currentUrl =  $currentUrl;
76
+			$this->_currentUrl = $currentUrl;
77 77
 					
78 78
 			$this->_currentUrlCacheKey = md5($this->_currentUrl);
79 79
 			
@@ -88,9 +88,9 @@  discard block
 block discarded – undo
88 88
 		 * Get the logger singleton instance
89 89
 		 * @return Log the logger instance
90 90
 		 */
91
-		private static function getLogger(){
92
-			if(self::$logger == null){
93
-				self::$logger[0] =& class_loader('Log', 'classes');
91
+		private static function getLogger() {
92
+			if (self::$logger == null) {
93
+				self::$logger[0] = & class_loader('Log', 'classes');
94 94
 				self::$logger[0]->setLogger('Library::Response');
95 95
 			}
96 96
 			return self::$logger[0];
@@ -101,12 +101,12 @@  discard block
 block discarded – undo
101 101
 		 * @param  integer $httpCode the HTTP status code
102 102
 		 * @param  array   $headers   the additional headers to add to the existing headers list
103 103
 		 */
104
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
104
+		public static function sendHeaders($httpCode = 200, array $headers = array()) {
105 105
 			set_http_status_header($httpCode);
106 106
 			self::setHeaders($headers);
107
-			if(! headers_sent()){
108
-				foreach(self::getHeaders() as $key => $value){
109
-					header($key .': '.$value);
107
+			if (!headers_sent()) {
108
+				foreach (self::getHeaders() as $key => $value) {
109
+					header($key . ': ' . $value);
110 110
 				}
111 111
 			}
112 112
 		}
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 		 * Get the list of the headers
116 116
 		 * @return array the headers list
117 117
 		 */
118
-		public static function getHeaders(){
118
+		public static function getHeaders() {
119 119
 			return self::$headers;
120 120
 		}
121 121
 
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 		 * @param  string $name the header name
125 125
 		 * @return string       the header value
126 126
 		 */
127
-		public static function getHeader($name){
127
+		public static function getHeader($name) {
128 128
 			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
129 129
 		}
130 130
 
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 		 * @param string $name  the header name
135 135
 		 * @param string $value the header value to be set
136 136
 		 */
137
-		public static function setHeader($name, $value){
137
+		public static function setHeader($name, $value) {
138 138
 			self::$headers[$name] = $value;
139 139
 		}
140 140
 
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 		 * @param array $headers the list of the headers to set. 
144 144
 		 * Note: this will merge with the existing headers
145 145
 		 */
146
-		public static function setHeaders(array $headers){
146
+		public static function setHeaders(array $headers) {
147 147
 			self::$headers = array_merge(self::getHeaders(), $headers);
148 148
 		}
149 149
 		
@@ -151,17 +151,17 @@  discard block
 block discarded – undo
151 151
 		 * Redirect user in the specified page
152 152
 		 * @param  string $path the URL or URI to be redirect to
153 153
 		 */
154
-		public static function redirect($path = ''){
154
+		public static function redirect($path = '') {
155 155
 			$logger = self::getLogger();
156 156
 			$url = Url::site_url($path);
157
-			$logger->info('Redirect to URL [' .$url. ']');
158
-			if(! headers_sent()){
159
-				header('Location: '.$url);
157
+			$logger->info('Redirect to URL [' . $url . ']');
158
+			if (!headers_sent()) {
159
+				header('Location: ' . $url);
160 160
 				exit;
161 161
 			}
162
-			else{
162
+			else {
163 163
 				echo '<script>
164
-						location.href = "'.$url.'";
164
+						location.href = "'.$url . '";
165 165
 					</script>';
166 166
 			}
167 167
 		}
@@ -174,10 +174,10 @@  discard block
 block discarded – undo
174 174
 		 * @return void|string          if $return is true will return the view content otherwise
175 175
 		 * will display the view content.
176 176
 		 */
177
-		public function render($view, $data = null, $return = false){
177
+		public function render($view, $data = null, $return = false) {
178 178
 			$logger = self::getLogger();
179 179
 			//convert data to an array
180
-			$data = ! is_array($data) ? (array) $data : $data;
180
+			$data = !is_array($data) ? (array) $data : $data;
181 181
 			$view = str_ireplace('.php', '', $view);
182 182
 			$view = trim($view, '/\\');
183 183
 			$viewFile = $view . '.php';
@@ -186,42 +186,42 @@  discard block
 block discarded – undo
186 186
 			//super instance
187 187
 			$obj = & get_instance();
188 188
 			
189
-			if(Module::hasModule()){
189
+			if (Module::hasModule()) {
190 190
 				//check in module first
191 191
 				$logger->debug('Checking the view [' . $view . '] from module list ...');
192 192
 				$mod = null;
193 193
 				//check if the request class contains module name
194
-				if(strpos($view, '/') !== false){
194
+				if (strpos($view, '/') !== false) {
195 195
 					$viewPath = explode('/', $view);
196
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
196
+					if (isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())) {
197 197
 						$mod = $viewPath[0];
198 198
 						array_shift($viewPath);
199 199
 						$view = implode('/', $viewPath);
200 200
 						$viewFile = $view . '.php';
201 201
 					}
202 202
 				}
203
-				if(! $mod && !empty($obj->moduleName)){
203
+				if (!$mod && !empty($obj->moduleName)) {
204 204
 					$mod = $obj->moduleName;
205 205
 				}
206
-				if($mod){
206
+				if ($mod) {
207 207
 					$moduleViewPath = Module::findViewFullPath($view, $mod);
208
-					if($moduleViewPath){
208
+					if ($moduleViewPath) {
209 209
 						$path = $moduleViewPath;
210
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
210
+						$logger->info('Found view [' . $view . '] in module [' . $mod . '], the file path is [' . $moduleViewPath . '] we will used it');
211 211
 					}
212
-					else{
213
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
212
+					else {
213
+						$logger->info('Cannot find view [' . $view . '] in module [' . $mod . '] using the default location');
214 214
 					}
215 215
 				}
216
-				else{
216
+				else {
217 217
 					$logger->info('The current request does not use module using the default location.');
218 218
 				}
219 219
 			}
220 220
 			$logger->info('The view file path to be loaded is [' . $path . ']');
221 221
 			$found = false;
222
-			if(file_exists($path)){
223
-				foreach(get_object_vars($obj) as $key => $value){
224
-					if(! isset($this->{$key})){
222
+			if (file_exists($path)) {
223
+				foreach (get_object_vars($obj) as $key => $value) {
224
+					if (!isset($this->{$key})) {
225 225
 						$this->{$key} = & $obj->{$key};
226 226
 					}
227 227
 				}
@@ -230,44 +230,44 @@  discard block
 block discarded – undo
230 230
 				//need use require() instead of require_once because can load this view many time
231 231
 				require $path;
232 232
 				$content = ob_get_clean();
233
-				if($return){
233
+				if ($return) {
234 234
 					return $content;
235 235
 				}
236 236
 				$this->_pageRender .= $content;
237 237
 				$found = true;
238 238
 			}
239
-			if(! $found){
240
-				show_error('Unable to find view [' .$view . ']');
239
+			if (!$found) {
240
+				show_error('Unable to find view [' . $view . ']');
241 241
 			}
242 242
 		}
243 243
 		
244 244
 		/**
245 245
 		* Send the final page output to user
246 246
 		*/
247
-		public function renderFinalPage(){
247
+		public function renderFinalPage() {
248 248
 			$logger = self::getLogger();
249 249
 			$obj = & get_instance();
250 250
 			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
251 251
 			$dispatcher = $obj->eventdispatcher;
252 252
 			$content = $this->_pageRender;
253
-			if(! $content){
253
+			if (!$content) {
254 254
 				$logger->warning('The final view content is empty.');
255 255
 				return;
256 256
 			}
257 257
 			//dispatch
258 258
 			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
259
-			$content = ! empty($event->payload) ? $event->payload : null;
260
-			if(empty($content)){
259
+			$content = !empty($event->payload) ? $event->payload : null;
260
+			if (empty($content)) {
261 261
 				$logger->warning('The view content is empty after dispatch to event listeners.');
262 262
 			}
263 263
 			
264 264
 			//check whether need save the page into cache.
265
-			if($cachePageStatus){
265
+			if ($cachePageStatus) {
266 266
 				//current page URL
267 267
 				$url = $this->_currentUrl;
268 268
 				//Cache view Time to live in second
269 269
 				$viewCacheTtl = get_config('cache_ttl');
270
-				if (!empty($obj->view_cache_ttl)){
270
+				if (!empty($obj->view_cache_ttl)) {
271 271
 					$viewCacheTtl = $obj->view_cache_ttl;
272 272
 				}
273 273
 				//the cache handler instance
@@ -280,14 +280,14 @@  discard block
 block discarded – undo
280 280
 				
281 281
 				//get the cache information to prepare header to send to browser
282 282
 				$cacheInfo = $cacheInstance->getInfo($cacheKey);
283
-				if($cacheInfo){
283
+				if ($cacheInfo) {
284 284
 					$lastModified = $cacheInfo['mtime'];
285 285
 					$expire = $cacheInfo['expire'];
286 286
 					$maxAge = $expire - time();
287 287
 					self::setHeader('Pragma', 'public');
288 288
 					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
289
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
290
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
289
+					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
290
+					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');	
291 291
 				}
292 292
 			}
293 293
 			
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 			
300 300
 			//compress the output if is available
301 301
 			$type = null;
302
-			if (self::$_canCompressOutput){
302
+			if (self::$_canCompressOutput) {
303 303
 				$type = 'ob_gzhandler';
304 304
 			}
305 305
 			ob_start($type);
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 		/**
312 312
 		* Send the final page output to user if is cached
313 313
 		*/
314
-		public function renderFinalPageFromCache(&$cache){
314
+		public function renderFinalPageFromCache(&$cache) {
315 315
 			$logger = self::getLogger();
316 316
 			$url = $this->_currentUrl;					
317 317
 			//the current page cache key for identification
@@ -320,15 +320,15 @@  discard block
 block discarded – undo
320 320
 			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
321 321
 			//get the cache information to prepare header to send to browser
322 322
 			$cacheInfo = $cache->getInfo($pageCacheKey);
323
-			if($cacheInfo){
323
+			if ($cacheInfo) {
324 324
 				$lastModified = $cacheInfo['mtime'];
325 325
 				$expire = $cacheInfo['expire'];
326 326
 				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
327 327
 				self::setHeader('Pragma', 'public');
328 328
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
329
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
330
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
331
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
329
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
330
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
331
+				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
332 332
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
333 333
 					self::sendHeaders(304);
334 334
 					return;
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 				self::sendHeaders(200);
338 338
 				//get the cache content
339 339
 				$content = $cache->get($pageCacheKey);
340
-				if($content){
340
+				if ($content) {
341 341
 					$logger->info('The page content for the URL [' . $url . '] already cached just display it');
342 342
 					//load benchmark class
343 343
 					$benchmark = & class_loader('Benchmark');
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
 					///display the final output
352 352
 					//compress the output if is available
353 353
 					$type = null;
354
-					if (self::$_canCompressOutput){
354
+					if (self::$_canCompressOutput) {
355 355
 						$type = 'ob_gzhandler';
356 356
 					}
357 357
 					ob_start($type);
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
 					ob_end_flush();
360 360
 					return;
361 361
 				}
362
-				else{
362
+				else {
363 363
 					$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
364 364
 					$cache->delete($pageCacheKey);
365 365
 				}
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 		* Get the final page to be rendered
372 372
 		* @return string
373 373
 		*/
374
-		public function getFinalPageRendered(){
374
+		public function getFinalPageRendered() {
375 375
 			return $this->_pageRender;
376 376
 		}
377 377
 
@@ -379,14 +379,14 @@  discard block
 block discarded – undo
379 379
 		 * Send the HTTP 404 error if can not found the 
380 380
 		 * routing information for the current request
381 381
 		 */
382
-		public static function send404(){
382
+		public static function send404() {
383 383
 			/********* for logs **************/
384 384
 			//can't use $obj = & get_instance()  here because the global super object will be available until
385 385
 			//the main controller is loaded even for Loader::library('xxxx');
386 386
 			$logger = self::getLogger();
387
-			$request =& class_loader('Request', 'classes');
388
-			$userAgent =& class_loader('Browser');
389
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
387
+			$request = & class_loader('Request', 'classes');
388
+			$userAgent = & class_loader('Browser');
389
+			$browser = $userAgent->getPlatform() . ', ' . $userAgent->getBrowser() . ' ' . $userAgent->getVersion();
390 390
 			
391 391
 			//here can't use Loader::functions just include the helper manually
392 392
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
@@ -396,10 +396,10 @@  discard block
 block discarded – undo
396 396
 			$logger->error($str);
397 397
 			/***********************************/
398 398
 			$path = CORE_VIEWS_PATH . '404.php';
399
-			if(file_exists($path)){
399
+			if (file_exists($path)) {
400 400
 				//compress the output if is available
401 401
 				$type = null;
402
-				if (self::$_canCompressOutput){
402
+				if (self::$_canCompressOutput) {
403 403
 					$type = 'ob_gzhandler';
404 404
 				}
405 405
 				ob_start($type);
@@ -408,8 +408,8 @@  discard block
 block discarded – undo
408 408
 				self::sendHeaders(404);
409 409
 				echo $output;
410 410
 			}
411
-			else{
412
-				show_error('The 404 view [' .$path. '] does not exist');
411
+			else {
412
+				show_error('The 404 view [' . $path . '] does not exist');
413 413
 			}
414 414
 		}
415 415
 
@@ -417,12 +417,12 @@  discard block
 block discarded – undo
417 417
 		 * Display the error to user
418 418
 		 * @param  array  $data the error information
419 419
 		 */
420
-		public static function sendError(array $data = array()){
420
+		public static function sendError(array $data = array()) {
421 421
 			$path = CORE_VIEWS_PATH . 'errors.php';
422
-			if(file_exists($path)){
422
+			if (file_exists($path)) {
423 423
 				//compress the output if is available
424 424
 				$type = null;
425
-				if (self::$_canCompressOutput){
425
+				if (self::$_canCompressOutput) {
426 426
 					$type = 'ob_gzhandler';
427 427
 				}
428 428
 				ob_start($type);
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 				self::sendHeaders(503);
433 433
 				echo $output;
434 434
 			}
435
-			else{
435
+			else {
436 436
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
437 437
 				set_http_status_header(503);
438 438
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Braces   +6 added lines, -12 removed lines patch added patch discarded remove patch
@@ -158,8 +158,7 @@  discard block
 block discarded – undo
158 158
 			if(! headers_sent()){
159 159
 				header('Location: '.$url);
160 160
 				exit;
161
-			}
162
-			else{
161
+			} else{
163 162
 				echo '<script>
164 163
 						location.href = "'.$url.'";
165 164
 					</script>';
@@ -208,12 +207,10 @@  discard block
 block discarded – undo
208 207
 					if($moduleViewPath){
209 208
 						$path = $moduleViewPath;
210 209
 						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
211
-					}
212
-					else{
210
+					} else{
213 211
 						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
214 212
 					}
215
-				}
216
-				else{
213
+				} else{
217 214
 					$logger->info('The current request does not use module using the default location.');
218 215
 				}
219 216
 			}
@@ -358,8 +355,7 @@  discard block
 block discarded – undo
358 355
 					echo $content;
359 356
 					ob_end_flush();
360 357
 					return;
361
-				}
362
-				else{
358
+				} else{
363 359
 					$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
364 360
 					$cache->delete($pageCacheKey);
365 361
 				}
@@ -407,8 +403,7 @@  discard block
 block discarded – undo
407 403
 				$output = ob_get_clean();
408 404
 				self::sendHeaders(404);
409 405
 				echo $output;
410
-			}
411
-			else{
406
+			} else{
412 407
 				show_error('The 404 view [' .$path. '] does not exist');
413 408
 			}
414 409
 		}
@@ -431,8 +426,7 @@  discard block
 block discarded – undo
431 426
 				$output = ob_get_clean();
432 427
 				self::sendHeaders(503);
433 428
 				echo $output;
434
-			}
435
-			else{
429
+			} else{
436 430
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
437 431
 				set_http_status_header(503);
438 432
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
core/classes/Log.php 2 patches
Indentation   +251 added lines, -251 removed lines patch added patch discarded remove patch
@@ -1,279 +1,279 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Log{
27
+    class Log{
28 28
 		
29
-		/**
30
-		 * The defined constante for Log level
31
-		 */
32
-		const NONE = 99999999;
33
-		const FATAL = 500;
34
-		const ERROR = 400;
35
-		const WARNING = 300;
36
-		const INFO = 200;
37
-		const DEBUG = 100;
38
-		const ALL = -99999999;
29
+        /**
30
+         * The defined constante for Log level
31
+         */
32
+        const NONE = 99999999;
33
+        const FATAL = 500;
34
+        const ERROR = 400;
35
+        const WARNING = 300;
36
+        const INFO = 200;
37
+        const DEBUG = 100;
38
+        const ALL = -99999999;
39 39
 
40
-		/**
41
-		 * The logger name
42
-		 * @var string
43
-		 */
44
-		private $logger = 'ROOT_LOGGER';
40
+        /**
41
+         * The logger name
42
+         * @var string
43
+         */
44
+        private $logger = 'ROOT_LOGGER';
45 45
 		
46
-		/**
47
-		 * List of valid log level to be checked for the configuration
48
-		 * @var array
49
-		 */
50
-		private static $validConfigLevel = array('off', 'none', 'fatal', 'error', 'warning', 'warn', 'info', 'debug', 'all');
46
+        /**
47
+         * List of valid log level to be checked for the configuration
48
+         * @var array
49
+         */
50
+        private static $validConfigLevel = array('off', 'none', 'fatal', 'error', 'warning', 'warn', 'info', 'debug', 'all');
51 51
 
52
-		/**
53
-		 * Create new Log instance
54
-		 */
55
-		public function __construct(){
56
-		}
52
+        /**
53
+         * Create new Log instance
54
+         */
55
+        public function __construct(){
56
+        }
57 57
 
58
-		/**
59
-		 * Set the logger to identify each message in the log
60
-		 * @param string $logger the logger name
61
-		 */
62
-		public  function setLogger($logger){
63
-			$this->logger = $logger;
64
-		}
58
+        /**
59
+         * Set the logger to identify each message in the log
60
+         * @param string $logger the logger name
61
+         */
62
+        public  function setLogger($logger){
63
+            $this->logger = $logger;
64
+        }
65 65
 
66
-		/**
67
-		 * Save the fatal message in the log
68
-		 * @see Log::writeLog for more detail
69
-		 * @param  string $message the log message to save
70
-		 */
71
-		public function fatal($message){
72
-			$this->writeLog($message, self::FATAL);
73
-		} 
66
+        /**
67
+         * Save the fatal message in the log
68
+         * @see Log::writeLog for more detail
69
+         * @param  string $message the log message to save
70
+         */
71
+        public function fatal($message){
72
+            $this->writeLog($message, self::FATAL);
73
+        } 
74 74
 		
75
-		/**
76
-		 * Save the error message in the log
77
-		 * @see Log::writeLog for more detail
78
-		 * @param  string $message the log message to save
79
-		 */
80
-		public function error($message){
81
-			$this->writeLog($message, self::ERROR);
82
-		} 
75
+        /**
76
+         * Save the error message in the log
77
+         * @see Log::writeLog for more detail
78
+         * @param  string $message the log message to save
79
+         */
80
+        public function error($message){
81
+            $this->writeLog($message, self::ERROR);
82
+        } 
83 83
 
84
-		/**
85
-		 * Save the warning message in the log
86
-		 * @see Log::writeLog for more detail
87
-		 * @param  string $message the log message to save
88
-		 */
89
-		public function warning($message){
90
-			$this->writeLog($message, self::WARNING);
91
-		} 
84
+        /**
85
+         * Save the warning message in the log
86
+         * @see Log::writeLog for more detail
87
+         * @param  string $message the log message to save
88
+         */
89
+        public function warning($message){
90
+            $this->writeLog($message, self::WARNING);
91
+        } 
92 92
 		
93
-		/**
94
-		 * Save the info message in the log
95
-		 * @see Log::writeLog for more detail
96
-		 * @param  string $message the log message to save
97
-		 */
98
-		public function info($message){
99
-			$this->writeLog($message, self::INFO);
100
-		} 
93
+        /**
94
+         * Save the info message in the log
95
+         * @see Log::writeLog for more detail
96
+         * @param  string $message the log message to save
97
+         */
98
+        public function info($message){
99
+            $this->writeLog($message, self::INFO);
100
+        } 
101 101
 		
102
-		/**
103
-		 * Save the debug message in the log
104
-		 * @see Log::writeLog for more detail
105
-		 * @param  string $message the log message to save
106
-		 */
107
-		public function debug($message){
108
-			$this->writeLog($message, self::DEBUG);
109
-		} 
102
+        /**
103
+         * Save the debug message in the log
104
+         * @see Log::writeLog for more detail
105
+         * @param  string $message the log message to save
106
+         */
107
+        public function debug($message){
108
+            $this->writeLog($message, self::DEBUG);
109
+        } 
110 110
 		
111 111
 		
112
-		/**
113
-		 * Save the log message
114
-		 * @param  string $message the log message to be saved
115
-		 * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116
-		 * to allow check the log level threshold.
117
-		 */
118
-		public function writeLog($message, $level = self::INFO){
119
-			$configLogLevel = get_config('log_level');
120
-			if(! $configLogLevel){
121
-				//so means no need log just stop here
122
-				return;
123
-			}
124
-			//check config log level
125
-			if(! self::isValidConfigLevel($configLogLevel)){
126
-				//NOTE: here need put the show_error() "logging" to false to prevent loop
127
-				show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128
-			}
112
+        /**
113
+         * Save the log message
114
+         * @param  string $message the log message to be saved
115
+         * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116
+         * to allow check the log level threshold.
117
+         */
118
+        public function writeLog($message, $level = self::INFO){
119
+            $configLogLevel = get_config('log_level');
120
+            if(! $configLogLevel){
121
+                //so means no need log just stop here
122
+                return;
123
+            }
124
+            //check config log level
125
+            if(! self::isValidConfigLevel($configLogLevel)){
126
+                //NOTE: here need put the show_error() "logging" to false to prevent loop
127
+                show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128
+            }
129 129
 			
130
-			//check if config log_logger_name is set
131
-			if($this->logger){
132
-				$configLoggersName = get_config('log_logger_name', array());
133
-				if (!empty($configLoggersName)) {
134
-					//for best comparaison put all string to lowercase
135
-					$configLoggersName = array_map('strtolower', $configLoggersName);
136
-					if(! in_array(strtolower($this->logger), $configLoggersName)){
137
-						return;
138
-					}
139
-				}
140
-			}
130
+            //check if config log_logger_name is set
131
+            if($this->logger){
132
+                $configLoggersName = get_config('log_logger_name', array());
133
+                if (!empty($configLoggersName)) {
134
+                    //for best comparaison put all string to lowercase
135
+                    $configLoggersName = array_map('strtolower', $configLoggersName);
136
+                    if(! in_array(strtolower($this->logger), $configLoggersName)){
137
+                        return;
138
+                    }
139
+                }
140
+            }
141 141
 			
142
-			//if $level is not an integer
143
-			if(! is_numeric($level)){
144
-				$level = self::getLevelValue($level);
145
-			}
142
+            //if $level is not an integer
143
+            if(! is_numeric($level)){
144
+                $level = self::getLevelValue($level);
145
+            }
146 146
 			
147
-			//check if can logging regarding the log level config
148
-			$configLevel = self::getLevelValue($configLogLevel);
149
-			if($configLevel > $level){
150
-				//can't log
151
-				return;
152
-			}
153
-			//check log file and directory
154
-			$path = $this->checkAndSetLogFileDirectory();
155
-			//save the log data
156
-			$this->saveLogData($path, $level, $message);
157
-		}	
147
+            //check if can logging regarding the log level config
148
+            $configLevel = self::getLevelValue($configLogLevel);
149
+            if($configLevel > $level){
150
+                //can't log
151
+                return;
152
+            }
153
+            //check log file and directory
154
+            $path = $this->checkAndSetLogFileDirectory();
155
+            //save the log data
156
+            $this->saveLogData($path, $level, $message);
157
+        }	
158 158
 
159
-		/**
160
-		 * Save the log data into file
161
-		 * @param  string $path    the path of the log file
162
-		 * @param  int $level   the log level in numeric format
163
-		 * @param  string $message the log message to save
164
-		 * @return void
165
-		 */
166
-		public function saveLogData($path, $level, $message){
167
-			//may be at this time helper user_agent not yet included
168
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
159
+        /**
160
+         * Save the log data into file
161
+         * @param  string $path    the path of the log file
162
+         * @param  int $level   the log level in numeric format
163
+         * @param  string $message the log message to save
164
+         * @return void
165
+         */
166
+        public function saveLogData($path, $level, $message){
167
+            //may be at this time helper user_agent not yet included
168
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
169 169
 			
170
-			///////////////////// date //////////////
171
-			$timestampWithMicro = microtime(true);
172
-			$microtime = sprintf('%06d', ($timestampWithMicro - floor($timestampWithMicro)) * 1000000);
173
-			$dateTime = new DateTime(date('Y-m-d H:i:s.' . $microtime, $timestampWithMicro));
174
-			$logDate = $dateTime->format('Y-m-d H:i:s.u'); 
175
-			//ip
176
-			$ip = get_ip();
177
-			//level name
178
-			$levelName = self::getLevelName($level);
170
+            ///////////////////// date //////////////
171
+            $timestampWithMicro = microtime(true);
172
+            $microtime = sprintf('%06d', ($timestampWithMicro - floor($timestampWithMicro)) * 1000000);
173
+            $dateTime = new DateTime(date('Y-m-d H:i:s.' . $microtime, $timestampWithMicro));
174
+            $logDate = $dateTime->format('Y-m-d H:i:s.u'); 
175
+            //ip
176
+            $ip = get_ip();
177
+            //level name
178
+            $levelName = self::getLevelName($level);
179 179
 			
180
-			//debug info
181
-			$dtrace = debug_backtrace();
182
-			$fileInfo = $dtrace[0]['file'] == __FILE__ ? $dtrace[1] : $dtrace[0];
180
+            //debug info
181
+            $dtrace = debug_backtrace();
182
+            $fileInfo = $dtrace[0]['file'] == __FILE__ ? $dtrace[1] : $dtrace[0];
183 183
 			
184
-			$str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
185
-			$fp = fopen($path, 'a+');
186
-			if(is_resource($fp)){
187
-				flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
188
-				fwrite($fp, $str);
189
-				fclose($fp);
190
-			}
191
-		}	
184
+            $str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
185
+            $fp = fopen($path, 'a+');
186
+            if(is_resource($fp)){
187
+                flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
188
+                fwrite($fp, $str);
189
+                fclose($fp);
190
+            }
191
+        }	
192 192
 
193
-		/**
194
-		 * Check the file and directory 
195
-		 * @return string the log file path
196
-		 */
197
-		protected function checkAndSetLogFileDirectory(){
198
-			$logSavePath = get_config('log_save_path');
199
-			if(! $logSavePath){
200
-				$logSavePath = LOGS_PATH;
201
-			}
193
+        /**
194
+         * Check the file and directory 
195
+         * @return string the log file path
196
+         */
197
+        protected function checkAndSetLogFileDirectory(){
198
+            $logSavePath = get_config('log_save_path');
199
+            if(! $logSavePath){
200
+                $logSavePath = LOGS_PATH;
201
+            }
202 202
 			
203
-			if(! is_dir($logSavePath) || !is_writable($logSavePath)){
204
-				//NOTE: here need put the show_error() "logging" to false to prevent loop
205
-				show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
206
-			}
203
+            if(! is_dir($logSavePath) || !is_writable($logSavePath)){
204
+                //NOTE: here need put the show_error() "logging" to false to prevent loop
205
+                show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
206
+            }
207 207
 			
208
-			$path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
209
-			if(! file_exists($path)){
210
-				touch($path);
211
-			}
212
-			return $path;
213
-		}
208
+            $path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
209
+            if(! file_exists($path)){
210
+                touch($path);
211
+            }
212
+            return $path;
213
+        }
214 214
 		
215
-		/**
216
-		 * Check if the given log level is valid
217
-		 *
218
-		 * @param  string  $level the log level
219
-		 *
220
-		 * @return boolean        true if the given log level is valid, false if not
221
-		 */
222
-		protected static function isValidConfigLevel($level){
223
-			$level = strtolower($level);
224
-			return in_array($level, self::$validConfigLevel);
225
-		}
215
+        /**
216
+         * Check if the given log level is valid
217
+         *
218
+         * @param  string  $level the log level
219
+         *
220
+         * @return boolean        true if the given log level is valid, false if not
221
+         */
222
+        protected static function isValidConfigLevel($level){
223
+            $level = strtolower($level);
224
+            return in_array($level, self::$validConfigLevel);
225
+        }
226 226
 
227
-		/**
228
-		 * Get the log level number for the given level string
229
-		 * @param  string $level the log level in string format
230
-		 * 
231
-		 * @return int        the log level in integer format using the predefinied constants
232
-		 */
233
-		protected static function getLevelValue($level){
234
-			$level = strtolower($level);
235
-			$levelMaps = array(
236
-				'fatal'   => self::FATAL,
237
-				'error'   => self::ERROR,
238
-				'warning' => self::WARNING,
239
-				'warn'    => self::WARNING,
240
-				'info'    => self::INFO,
241
-				'debug'   => self::DEBUG,
242
-				'all'     => self::ALL
243
-			);
244
-			//the default value is NONE, so means no need test for NONE
245
-			$value = self::NONE;
246
-			foreach ($levelMaps as $k => $v) {
247
-				if($level == $k){
248
-					$value = $v;
249
-					break;
250
-				}
251
-			}
252
-			return $value;
253
-		}
227
+        /**
228
+         * Get the log level number for the given level string
229
+         * @param  string $level the log level in string format
230
+         * 
231
+         * @return int        the log level in integer format using the predefinied constants
232
+         */
233
+        protected static function getLevelValue($level){
234
+            $level = strtolower($level);
235
+            $levelMaps = array(
236
+                'fatal'   => self::FATAL,
237
+                'error'   => self::ERROR,
238
+                'warning' => self::WARNING,
239
+                'warn'    => self::WARNING,
240
+                'info'    => self::INFO,
241
+                'debug'   => self::DEBUG,
242
+                'all'     => self::ALL
243
+            );
244
+            //the default value is NONE, so means no need test for NONE
245
+            $value = self::NONE;
246
+            foreach ($levelMaps as $k => $v) {
247
+                if($level == $k){
248
+                    $value = $v;
249
+                    break;
250
+                }
251
+            }
252
+            return $value;
253
+        }
254 254
 
255
-		/**
256
-		 * Get the log level string for the given log level integer
257
-		 * @param  integer $level the log level in integer format
258
-		 * @return string        the log level in string format
259
-		 */
260
-		protected static function getLevelName($level){
261
-			$levelMaps = array(
262
-				self::FATAL   => 'FATAL',
263
-				self::ERROR   => 'ERROR',
264
-				self::WARNING => 'WARNING',
265
-				self::INFO    => 'INFO',
266
-				self::DEBUG   => 'DEBUG'
267
-			);
268
-			$value = '';
269
-			foreach ($levelMaps as $k => $v) {
270
-				if($level == $k){
271
-					$value = $v;
272
-					break;
273
-				}
274
-			}
275
-			//no need for ALL
276
-			return $value;
277
-		}
255
+        /**
256
+         * Get the log level string for the given log level integer
257
+         * @param  integer $level the log level in integer format
258
+         * @return string        the log level in string format
259
+         */
260
+        protected static function getLevelName($level){
261
+            $levelMaps = array(
262
+                self::FATAL   => 'FATAL',
263
+                self::ERROR   => 'ERROR',
264
+                self::WARNING => 'WARNING',
265
+                self::INFO    => 'INFO',
266
+                self::DEBUG   => 'DEBUG'
267
+            );
268
+            $value = '';
269
+            foreach ($levelMaps as $k => $v) {
270
+                if($level == $k){
271
+                    $value = $v;
272
+                    break;
273
+                }
274
+            }
275
+            //no need for ALL
276
+            return $value;
277
+        }
278 278
 
279
-	}
279
+    }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Log{
27
+	class Log {
28 28
 		
29 29
 		/**
30 30
 		 * The defined constante for Log level
@@ -52,14 +52,14 @@  discard block
 block discarded – undo
52 52
 		/**
53 53
 		 * Create new Log instance
54 54
 		 */
55
-		public function __construct(){
55
+		public function __construct() {
56 56
 		}
57 57
 
58 58
 		/**
59 59
 		 * Set the logger to identify each message in the log
60 60
 		 * @param string $logger the logger name
61 61
 		 */
62
-		public  function setLogger($logger){
62
+		public  function setLogger($logger) {
63 63
 			$this->logger = $logger;
64 64
 		}
65 65
 
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		 * @see Log::writeLog for more detail
69 69
 		 * @param  string $message the log message to save
70 70
 		 */
71
-		public function fatal($message){
71
+		public function fatal($message) {
72 72
 			$this->writeLog($message, self::FATAL);
73 73
 		} 
74 74
 		
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 		 * @see Log::writeLog for more detail
78 78
 		 * @param  string $message the log message to save
79 79
 		 */
80
-		public function error($message){
80
+		public function error($message) {
81 81
 			$this->writeLog($message, self::ERROR);
82 82
 		} 
83 83
 
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 		 * @see Log::writeLog for more detail
87 87
 		 * @param  string $message the log message to save
88 88
 		 */
89
-		public function warning($message){
89
+		public function warning($message) {
90 90
 			$this->writeLog($message, self::WARNING);
91 91
 		} 
92 92
 		
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		 * @see Log::writeLog for more detail
96 96
 		 * @param  string $message the log message to save
97 97
 		 */
98
-		public function info($message){
98
+		public function info($message) {
99 99
 			$this->writeLog($message, self::INFO);
100 100
 		} 
101 101
 		
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		 * @see Log::writeLog for more detail
105 105
 		 * @param  string $message the log message to save
106 106
 		 */
107
-		public function debug($message){
107
+		public function debug($message) {
108 108
 			$this->writeLog($message, self::DEBUG);
109 109
 		} 
110 110
 		
@@ -115,38 +115,38 @@  discard block
 block discarded – undo
115 115
 		 * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116 116
 		 * to allow check the log level threshold.
117 117
 		 */
118
-		public function writeLog($message, $level = self::INFO){
118
+		public function writeLog($message, $level = self::INFO) {
119 119
 			$configLogLevel = get_config('log_level');
120
-			if(! $configLogLevel){
120
+			if (!$configLogLevel) {
121 121
 				//so means no need log just stop here
122 122
 				return;
123 123
 			}
124 124
 			//check config log level
125
-			if(! self::isValidConfigLevel($configLogLevel)){
125
+			if (!self::isValidConfigLevel($configLogLevel)) {
126 126
 				//NOTE: here need put the show_error() "logging" to false to prevent loop
127 127
 				show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128 128
 			}
129 129
 			
130 130
 			//check if config log_logger_name is set
131
-			if($this->logger){
131
+			if ($this->logger) {
132 132
 				$configLoggersName = get_config('log_logger_name', array());
133 133
 				if (!empty($configLoggersName)) {
134 134
 					//for best comparaison put all string to lowercase
135 135
 					$configLoggersName = array_map('strtolower', $configLoggersName);
136
-					if(! in_array(strtolower($this->logger), $configLoggersName)){
136
+					if (!in_array(strtolower($this->logger), $configLoggersName)) {
137 137
 						return;
138 138
 					}
139 139
 				}
140 140
 			}
141 141
 			
142 142
 			//if $level is not an integer
143
-			if(! is_numeric($level)){
143
+			if (!is_numeric($level)) {
144 144
 				$level = self::getLevelValue($level);
145 145
 			}
146 146
 			
147 147
 			//check if can logging regarding the log level config
148 148
 			$configLevel = self::getLevelValue($configLogLevel);
149
-			if($configLevel > $level){
149
+			if ($configLevel > $level) {
150 150
 				//can't log
151 151
 				return;
152 152
 			}
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		 * @param  string $message the log message to save
164 164
 		 * @return void
165 165
 		 */
166
-		public function saveLogData($path, $level, $message){
166
+		public function saveLogData($path, $level, $message) {
167 167
 			//may be at this time helper user_agent not yet included
168 168
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
169 169
 			
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 			
184 184
 			$str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
185 185
 			$fp = fopen($path, 'a+');
186
-			if(is_resource($fp)){
186
+			if (is_resource($fp)) {
187 187
 				flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
188 188
 				fwrite($fp, $str);
189 189
 				fclose($fp);
@@ -194,19 +194,19 @@  discard block
 block discarded – undo
194 194
 		 * Check the file and directory 
195 195
 		 * @return string the log file path
196 196
 		 */
197
-		protected function checkAndSetLogFileDirectory(){
197
+		protected function checkAndSetLogFileDirectory() {
198 198
 			$logSavePath = get_config('log_save_path');
199
-			if(! $logSavePath){
199
+			if (!$logSavePath) {
200 200
 				$logSavePath = LOGS_PATH;
201 201
 			}
202 202
 			
203
-			if(! is_dir($logSavePath) || !is_writable($logSavePath)){
203
+			if (!is_dir($logSavePath) || !is_writable($logSavePath)) {
204 204
 				//NOTE: here need put the show_error() "logging" to false to prevent loop
205 205
 				show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
206 206
 			}
207 207
 			
208 208
 			$path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
209
-			if(! file_exists($path)){
209
+			if (!file_exists($path)) {
210 210
 				touch($path);
211 211
 			}
212 212
 			return $path;
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 		 *
220 220
 		 * @return boolean        true if the given log level is valid, false if not
221 221
 		 */
222
-		protected static function isValidConfigLevel($level){
222
+		protected static function isValidConfigLevel($level) {
223 223
 			$level = strtolower($level);
224 224
 			return in_array($level, self::$validConfigLevel);
225 225
 		}
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		 * 
231 231
 		 * @return int        the log level in integer format using the predefinied constants
232 232
 		 */
233
-		protected static function getLevelValue($level){
233
+		protected static function getLevelValue($level) {
234 234
 			$level = strtolower($level);
235 235
 			$levelMaps = array(
236 236
 				'fatal'   => self::FATAL,
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
 			//the default value is NONE, so means no need test for NONE
245 245
 			$value = self::NONE;
246 246
 			foreach ($levelMaps as $k => $v) {
247
-				if($level == $k){
247
+				if ($level == $k) {
248 248
 					$value = $v;
249 249
 					break;
250 250
 				}
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 		 * @param  integer $level the log level in integer format
258 258
 		 * @return string        the log level in string format
259 259
 		 */
260
-		protected static function getLevelName($level){
260
+		protected static function getLevelName($level) {
261 261
 			$levelMaps = array(
262 262
 				self::FATAL   => 'FATAL',
263 263
 				self::ERROR   => 'ERROR',
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 			);
268 268
 			$value = '';
269 269
 			foreach ($levelMaps as $k => $v) {
270
-				if($level == $k){
270
+				if ($level == $k) {
271 271
 					$value = $v;
272 272
 					break;
273 273
 				}
Please login to merge, or discard this patch.
core/libraries/FormValidation.php 2 patches
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -22,10 +22,10 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
 
27 27
 
28
-     class FormValidation{
28
+        class FormValidation{
29 29
 		 
30 30
         /**
31 31
          * The form validation status
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
          */
61 61
         protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
62 62
         
63
-		/**
63
+        /**
64 64
          * Indicated if need force the validation to be failed
65 65
          * @var boolean
66 66
          */
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
             $this->logger =& class_loader('Log', 'classes');
101 101
             $this->logger->setLogger('Library::FormValidation');
102 102
            
103
-		   //Load form validation language message
103
+            //Load form validation language message
104 104
             Loader::lang('form_validation');
105 105
             $obj = & get_instance();
106 106
             $this->_errorsMessages  = array(
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
         /**
163 163
          * Set the form validation data
164 164
          * @param array $data the values to be validated
165
-		 *
165
+         *
166 166
          * @return FormValidation Current instance of object.
167 167
          */
168 168
         public function setData(array $data){
169 169
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
170 170
             $this->data = $data;
171
-			return $this;
171
+            return $this;
172 172
         }
173 173
 
174 174
         /**
@@ -179,11 +179,11 @@  discard block
 block discarded – undo
179 179
             return $this->data;
180 180
         }
181 181
 
182
-		/**
183
-		* Get the validation function name to validate a rule
184
-		*
185
-		* @return string the function name
186
-		*/
182
+        /**
183
+         * Get the validation function name to validate a rule
184
+         *
185
+         * @return string the function name
186
+         */
187 187
         protected function _toCallCase($funcName, $prefix='_validate') {
188 188
             $funcName = strtolower($funcName);
189 189
             $finalFuncName = $prefix;
@@ -253,12 +253,12 @@  discard block
 block discarded – undo
253 253
             $this->_forceFail = false;
254 254
 
255 255
             foreach ($this->getData() as $inputName => $inputVal) {
256
-    			if(is_array($this->data[$inputName])){
257
-    				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
-    			}
259
-    			else{
260
-    				$this->data[$inputName] = trim($this->data[$inputName]);
261
-    			}
256
+                if(is_array($this->data[$inputName])){
257
+                    $this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
+                }
259
+                else{
260
+                    $this->data[$inputName] = trim($this->data[$inputName]);
261
+                }
262 262
 
263 263
                 if (array_key_exists($inputName, $this->_rules)) {
264 264
                     foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
          *
275 275
          * @param string $inputField Name of the field or the data key to add a rule to
276 276
          * @param string $ruleSets PIPE seperated string of rules
277
-		 *
277
+         *
278 278
          * @return FormValidation Current instance of object.
279 279
          */
280 280
         public function setRule($inputField, $inputLabel, $ruleSets) {
@@ -288,8 +288,8 @@  discard block
 block discarded – undo
288 288
          * Takes an array of rules and uses setRule() to set them, accepts an array
289 289
          * of rule names rather than a pipe-delimited string as well.
290 290
          * @param array $ruleSets
291
-		 *
292
-		 * @return FormValidation Current instance of object.
291
+         *
292
+         * @return FormValidation Current instance of object.
293 293
          */
294 294
         public function setRules(array $ruleSets) {
295 295
             foreach ($ruleSets as $ruleSet) {
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
          * @param string $start Before block of errors gets displayed, HTML allowed.
312 312
          * @param string $end After the block of errors gets displayed, HTML allowed.
313 313
          *
314
-		 * @return FormValidation Current instance of object.
314
+         * @return FormValidation Current instance of object.
315 315
          */
316 316
         public function setErrorsDelimiter($start, $end) {
317 317
             $this->_allErrorsDelimiter[0] = $start;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
          * @param string $start Displayed before each error.
327 327
          * @param string $end Displayed after each error.
328 328
          * 
329
-		 * @return FormValidation Current instance of object.
329
+         * @return FormValidation Current instance of object.
330 330
          */
331 331
         public function setErrorDelimiter($start, $end) {
332 332
             $this->_eachErrorDelimiter[0] = $start;
@@ -334,21 +334,21 @@  discard block
 block discarded – undo
334 334
             return $this;
335 335
         }
336 336
 
337
-		/**
338
-		* Get the each errors delimiters
339
-		*
340
-		* @return array
341
-		*/
342
-    	public function getErrorDelimiter() {
337
+        /**
338
+         * Get the each errors delimiters
339
+         *
340
+         * @return array
341
+         */
342
+        public function getErrorDelimiter() {
343 343
             return $this->_eachErrorDelimiter;
344 344
         }
345 345
 
346
-		/**
347
-		* Get the all errors delimiters
348
-		*
349
-		* @return array
350
-		*/
351
-    	public function getErrorsDelimiter() {
346
+        /**
347
+         * Get the all errors delimiters
348
+         *
349
+         * @return array
350
+         */
351
+        public function getErrorsDelimiter() {
352 352
             return $this->_allErrorsDelimiter;
353 353
         }
354 354
 
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
          *
387 387
          * @param string $inputName The form input name or data key
388 388
          * @param string $errorMessage Error to display
389
-		 *
389
+         *
390 390
          * @return formValidation Current instance of the object
391 391
          */
392 392
         public function setCustomError($inputName, $errorMessage) {
@@ -423,17 +423,17 @@  discard block
 block discarded – undo
423 423
          *
424 424
          * @param boolean $limit number of error to display or return
425 425
          * @param boolean $echo Whether or not the values are to be returned or displayed
426
-		 *
426
+         *
427 427
          * @return string Errors formatted for output
428 428
          */
429 429
         public function displayErrors($limit = null, $echo = true) {
430 430
             list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
431 431
             list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
432 432
             $errorOutput = $errorsStart;
433
-    		$i = 0;
433
+            $i = 0;
434 434
             if (!empty($this->_errors)) {
435 435
                 foreach ($this->_errors as $fieldName => $error) {
436
-        	    	if ($i === $limit) { 
436
+                    if ($i === $limit) { 
437 437
                         break; 
438 438
                     }
439 439
                     $errorOutput .= $errorStart;
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
          * Breaks up a PIPE seperated string of rules, and puts them into an array.
462 462
          *
463 463
          * @param string $ruleString String to be parsed.
464
-		 *
464
+         *
465 465
          * @return array Array of each value in original string.
466 466
          */
467 467
         protected function _parseRuleString($ruleString) {
@@ -474,10 +474,10 @@  discard block
 block discarded – undo
474 474
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
475 475
                 preg_match($rule, $ruleString, $regexRule);
476 476
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
477
-                 if(!empty($regexRule[0])){
478
-                     $ruleSets[] = $regexRule[0];
479
-                 }
480
-                 $ruleStringRegex = explode('|', $ruleStringTemp);
477
+                    if(!empty($regexRule[0])){
478
+                        $ruleSets[] = $regexRule[0];
479
+                    }
480
+                    $ruleStringRegex = explode('|', $ruleStringTemp);
481 481
                 foreach ($ruleStringRegex as $rule) {
482 482
                     $rule = trim($rule);
483 483
                     if($rule){
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
                 } else {
494 494
                     $ruleSets[] = $ruleString;
495 495
                 }
496
-             }
496
+                }
497 497
             return $ruleSets;
498 498
         }
499 499
 
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
          * Returns whether or not a field obtains the rule "required".
502 502
          *
503 503
          * @param string $fieldName Field to check if required.
504
-		 *
504
+         *
505 505
          * @return boolean Whether or not the field is required.
506 506
          */
507 507
         protected function _fieldIsRequired($fieldName) {
@@ -536,13 +536,13 @@  discard block
 block discarded – undo
536 536
             return;
537 537
         }
538 538
 
539
-		/**
540
-		* Set error for the given field or key
541
-		*
542
-		* @param string $inputName the input or key name
543
-		* @param string $ruleName the rule name
544
-		* @param array|string $replacements
545
-		*/
539
+        /**
540
+         * Set error for the given field or key
541
+         *
542
+         * @param string $inputName the input or key name
543
+         * @param string $ruleName the rule name
544
+         * @param array|string $replacements
545
+         */
546 546
         protected function _setError($inputName, $ruleName, $replacements = array()) {
547 547
             $rulePhraseKeyParts = explode(',', $ruleName);
548 548
             $rulePhrase = null;
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
             }
560 560
             // Type cast to array in case it's a string
561 561
             $replacements = (array) $replacements;
562
-			$replacementCount = count($replacements);
562
+            $replacementCount = count($replacements);
563 563
             for ($i = 1; $i <= $replacementCount; $i++) {
564 564
                 $key = $i - 1;
565 565
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
@@ -577,11 +577,11 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @param type $inputArg
579 579
          * @param string $callbackFunc
580
-		 *
580
+         *
581 581
          * @return mixed
582 582
          */
583 583
         protected function _runCallback($inputArg, $callbackFunc) {
584
-			return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
584
+            return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
585 585
         }
586 586
 
587 587
         /**
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          * arguments.
591 591
          *
592 592
          * @param string $callbackFunc
593
-		 *
593
+         *
594 594
          * @return mixed
595 595
          */
596 596
         protected function _runEmptyCallback($callbackFunc) {
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
          * Gets a specific label of a specific field input name.
602 602
          *
603 603
          * @param string $inputName
604
-		 *
604
+         *
605 605
          * @return string
606 606
          */
607 607
         protected function _getLabel($inputName) {
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
          * @param  string $ruleName  the rule name for this validation ("required")
615 615
          * @param  array  $ruleArgs  the rules argument
616 616
          */
617
-		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
617
+        protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
618 618
             $inputVal = $this->post($inputName);
619 619
             if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
620 620
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
@@ -622,8 +622,8 @@  discard block
 block discarded – undo
622 622
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
623 623
                 }
624 624
             } 
625
-			else if($inputVal == '') {
626
-				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
625
+            else if($inputVal == '') {
626
+                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
627 627
             }
628 628
         }
629 629
 
@@ -647,10 +647,10 @@  discard block
 block discarded – undo
647 647
          */
648 648
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
649 649
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
650
-				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
651
-				if(! $result){
652
-					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
653
-				}
650
+                $result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
651
+                if(! $result){
652
+                    $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
653
+                }
654 654
             }
655 655
         }
656 656
 
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
                         continue;
683 683
                     }
684 684
                 } 
685
-				else{
685
+                else{
686 686
                     if ($inputVal == $doNotEqual) {
687 687
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
688 688
                         continue;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
          * @param  string $ruleName  the rule name for this validation ("less_than")
775 775
          * @param  array  $ruleArgs  the rules argument
776 776
          */
777
-    	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
777
+        protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
778 778
             $inputVal = $this->post($inputName);
779 779
             if ($inputVal >= $ruleArgs[1]) { 
780 780
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
          * @param  string $ruleName  the rule name for this validation ("greater_than")
791 791
          * @param  array  $ruleArgs  the rules argument
792 792
          */
793
-    	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
793
+        protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
794 794
             $inputVal = $this->post($inputName);
795 795
             if ($inputVal <= $ruleArgs[1]) {
796 796
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
          * @param  string $ruleName  the rule name for this validation ("numeric")
807 807
          * @param  array  $ruleArgs  the rules argument
808 808
          */
809
-    	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
809
+        protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
810 810
             $inputVal = $this->post($inputName);
811 811
             if (! is_numeric($inputVal)) {
812 812
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -822,18 +822,18 @@  discard block
 block discarded – undo
822 822
          * @param  string $ruleName  the rule name for this validation ("exists")
823 823
          * @param  array  $ruleArgs  the rules argument
824 824
          */
825
-		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
825
+        protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
826 826
             $inputVal = $this->post($inputName);
827
-    		if (! is_object($this->databaseInstance)){
827
+            if (! is_object($this->databaseInstance)){
828 828
                 $obj = & get_instance();
829 829
                 if(isset($obj->database)){
830 830
                     $this->databaseInstance = $obj->database;
831 831
                 } 
832 832
             }
833
-    		list($table, $column) = explode('.', $ruleArgs[1]);
834
-    		$this->databaseInstance->getQueryBuilder()->from($table)
835
-    			                                       ->where($column, $inputVal);
836
-    		$this->databaseInstance->get();
833
+            list($table, $column) = explode('.', $ruleArgs[1]);
834
+            $this->databaseInstance->getQueryBuilder()->from($table)
835
+                                                        ->where($column, $inputVal);
836
+            $this->databaseInstance->get();
837 837
             if ($this->databaseInstance->numRows() <= 0) {
838 838
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
839 839
                     return;
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
          * @param  string $ruleName  the rule name for this validation ("is_unique")
849 849
          * @param  array  $ruleArgs  the rules argument
850 850
          */
851
-    	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
851
+        protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
852 852
             $inputVal = $this->post($inputName);
853 853
             if (! is_object($this->databaseInstance)){
854 854
                 $obj = & get_instance();
@@ -856,11 +856,11 @@  discard block
 block discarded – undo
856 856
                     $this->databaseInstance = $obj->database;
857 857
                 } 
858 858
             }
859
-    		list($table, $column) = explode('.', $ruleArgs[1]);
860
-    		$this->databaseInstance->getQueryBuilder()->from($table)
861
-    			                                      ->where($column, $inputVal);
862
-    		$this->databaseInstance->get();
863
-    		if ($this->databaseInstance->numRows() > 0) {
859
+            list($table, $column) = explode('.', $ruleArgs[1]);
860
+            $this->databaseInstance->getQueryBuilder()->from($table)
861
+                                                        ->where($column, $inputVal);
862
+            $this->databaseInstance->get();
863
+            if ($this->databaseInstance->numRows() > 0) {
864 864
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
865 865
                     return;
866 866
                 }
@@ -874,25 +874,25 @@  discard block
 block discarded – undo
874 874
          * @param  string $ruleName  the rule name for this validation ("is_unique_update")
875 875
          * @param  array  $ruleArgs  the rules argument
876 876
          */
877
-    	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
877
+        protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
878 878
             $inputVal = $this->post($inputName);
879
-    		if (! is_object($this->databaseInstance)){
879
+            if (! is_object($this->databaseInstance)){
880 880
                 $obj = & get_instance();
881 881
                 if(isset($obj->database)){
882 882
                     $this->databaseInstance = $obj->database;
883 883
                 } 
884 884
             }
885
-    		$data = explode(',', $ruleArgs[1]);
886
-    		if(count($data) < 2){
887
-    			return;
888
-    		}
889
-    		list($table, $column) = explode('.', $data[0]);
890
-    		list($field, $val)    = explode('=', $data[1]);
891
-    		$this->databaseInstance->getQueryBuilder()->from($table)
892
-                                			          ->where($column, $inputVal)
893
-                                            		  ->where($field, '!=', trim($val));
885
+            $data = explode(',', $ruleArgs[1]);
886
+            if(count($data) < 2){
887
+                return;
888
+            }
889
+            list($table, $column) = explode('.', $data[0]);
890
+            list($field, $val)    = explode('=', $data[1]);
891
+            $this->databaseInstance->getQueryBuilder()->from($table)
892
+                                                        ->where($column, $inputVal)
893
+                                                        ->where($field, '!=', trim($val));
894 894
             $this->databaseInstance->get();
895
-    		if ($this->databaseInstance->numRows() > 0) {
895
+            if ($this->databaseInstance->numRows() > 0) {
896 896
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
897 897
                     return;
898 898
                 }
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
          */
909 909
         protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
910 910
             $inputVal = $this->post($inputName);
911
-    		$list = explode(',', $ruleArgs[1]);
911
+            $list = explode(',', $ruleArgs[1]);
912 912
             $list = array_map('trim', $list);
913 913
             if (! in_array($inputVal, $list)) {
914 914
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
          */
927 927
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
928 928
             $inputVal = $this->post($inputName);
929
-    		$regex = $ruleArgs[1];
929
+            $regex = $ruleArgs[1];
930 930
             if (! preg_match($regex, $inputVal)) {
931 931
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
932 932
                     return;
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -25,13 +25,13 @@  discard block
 block discarded – undo
25 25
     */
26 26
 
27 27
 
28
-     class FormValidation{
28
+     class FormValidation {
29 29
 		 
30 30
         /**
31 31
          * The form validation status
32 32
          * @var boolean
33 33
          */
34
-        protected $_success  = false;
34
+        protected $_success = false;
35 35
 
36 36
         /**
37 37
          * The list of errors messages
@@ -40,31 +40,31 @@  discard block
 block discarded – undo
40 40
         protected $_errorsMessages = array();
41 41
         
42 42
         // Array of rule sets, fieldName => PIPE seperated ruleString
43
-        protected $_rules             = array();
43
+        protected $_rules = array();
44 44
         
45 45
         // Array of errors, niceName => Error Message
46
-        protected $_errors             = array();
46
+        protected $_errors = array();
47 47
         
48 48
         // Array of post Key => Nice name labels
49
-        protected $_labels          = array();
49
+        protected $_labels = array();
50 50
         
51 51
         /**
52 52
          * The errors delimiters
53 53
          * @var array
54 54
          */
55
-        protected $_allErrorsDelimiter   = array('<div class="error">', '</div>');
55
+        protected $_allErrorsDelimiter = array('<div class="error">', '</div>');
56 56
 
57 57
         /**
58 58
          * The each error delimiter
59 59
          * @var array
60 60
          */
61
-        protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
61
+        protected $_eachErrorDelimiter = array('<p class="error">', '</p>');
62 62
         
63 63
 		/**
64 64
          * Indicated if need force the validation to be failed
65 65
          * @var boolean
66 66
          */
67
-        protected $_forceFail            = false;
67
+        protected $_forceFail = false;
68 68
 
69 69
         /**
70 70
          * The list of the error messages overrides by the original
@@ -97,13 +97,13 @@  discard block
 block discarded – undo
97 97
          * @return void
98 98
          */
99 99
         public function __construct() {
100
-            $this->logger =& class_loader('Log', 'classes');
100
+            $this->logger = & class_loader('Log', 'classes');
101 101
             $this->logger->setLogger('Library::FormValidation');
102 102
            
103 103
 		   //Load form validation language message
104 104
             Loader::lang('form_validation');
105 105
             $obj = & get_instance();
106
-            $this->_errorsMessages  = array(
106
+            $this->_errorsMessages = array(
107 107
                         'required'         => $obj->lang->get('fv_required'),
108 108
                         'min_length'       => $obj->lang->get('fv_min_length'),
109 109
                         'max_length'       => $obj->lang->get('fv_max_length'),
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
          * Set the database instance
134 134
          * @param object $database the database instance
135 135
          */
136
-        public function setDatabase(Database $database){
136
+        public function setDatabase(Database $database) {
137 137
             $this->databaseInstance = $database;
138 138
             return $this;
139 139
         }
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
          * Get the database instance
143 143
          * @return object the database instance
144 144
          */
145
-        public function getDatabase(){
145
+        public function getDatabase() {
146 146
             return $this->databaseInstance;
147 147
         }
148 148
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		 *
166 166
          * @return FormValidation Current instance of object.
167 167
          */
168
-        public function setData(array $data){
168
+        public function setData(array $data) {
169 169
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
170 170
             $this->data = $data;
171 171
 			return $this;
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
          * Get the form validation data
176 176
          * @return array the form validation data to be validated
177 177
          */
178
-        public function getData(){
178
+        public function getData() {
179 179
             return $this->data;
180 180
         }
181 181
 
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 		*
185 185
 		* @return string the function name
186 186
 		*/
187
-        protected function _toCallCase($funcName, $prefix='_validate') {
187
+        protected function _toCallCase($funcName, $prefix = '_validate') {
188 188
             $funcName = strtolower($funcName);
189 189
             $finalFuncName = $prefix;
190 190
             foreach (explode('_', $funcName) as $funcNamePart) {
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
          * @return boolean Whether or not the form has been submitted or the data is available for validation.
209 209
          */
210 210
         public function canDoValidation() {
211
-            return get_instance()->request->method() === 'POST' || ! empty($this->data);
211
+            return get_instance()->request->method() === 'POST' || !empty($this->data);
212 212
         }
213 213
 
214 214
         /**
@@ -228,14 +228,14 @@  discard block
 block discarded – undo
228 228
          * Validate the CSRF 
229 229
          * @return void 
230 230
          */
231
-        protected function validateCSRF(){
232
-            if(get_instance()->request->method() == 'POST'){
231
+        protected function validateCSRF() {
232
+            if (get_instance()->request->method() == 'POST') {
233 233
                 $this->logger->debug('Check if CSRF is enabled in configuration');
234 234
                 //first check for CSRF
235
-                if (get_config('csrf_enable', false) && ! Security::validateCSRF()){
235
+                if (get_config('csrf_enable', false) && !Security::validateCSRF()) {
236 236
                     show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
237 237
                 }
238
-                else{
238
+                else {
239 239
                     $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
240 240
                 }
241 241
             }
@@ -253,10 +253,10 @@  discard block
 block discarded – undo
253 253
             $this->_forceFail = false;
254 254
 
255 255
             foreach ($this->getData() as $inputName => $inputVal) {
256
-    			if(is_array($this->data[$inputName])){
256
+    			if (is_array($this->data[$inputName])) {
257 257
     				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258 258
     			}
259
-    			else{
259
+    			else {
260 260
     				$this->data[$inputName] = trim($this->data[$inputName]);
261 261
     			}
262 262
 
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
                     }
267 267
                 }
268 268
             }
269
-            $this->_success =  empty($this->_errors) && $this->_forceFail === false;
269
+            $this->_success = empty($this->_errors) && $this->_forceFail === false;
270 270
         }
271 271
 
272 272
         /**
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
         public function setRule($inputField, $inputLabel, $ruleSets) {
281 281
             $this->_rules[$inputField] = $ruleSets;
282 282
             $this->_labels[$inputField] = $inputLabel;
283
-            $this->logger->info('Set the field rule: name [' .$inputField. '], label [' .$inputLabel. '], rules [' .$ruleSets. ']');
283
+            $this->logger->info('Set the field rule: name [' . $inputField . '], label [' . $inputLabel . '], rules [' . $ruleSets . ']');
284 284
             return $this;
285 285
         }
286 286
 
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
             }
445 445
             $errorOutput .= $errorsEnd;
446 446
             echo ($echo) ? $errorOutput : '';
447
-            return (! $echo) ? $errorOutput : null;
447
+            return (!$echo) ? $errorOutput : null;
448 448
         }
449 449
 
450 450
         /**
@@ -469,25 +469,25 @@  discard block
 block discarded – undo
469 469
             /*
470 470
             //////////////// hack for regex rule that can contain "|"
471 471
             */
472
-            if(strpos($ruleString, 'regex') !== false){
472
+            if (strpos($ruleString, 'regex') !== false) {
473 473
                 $regexRule = array();
474 474
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
475 475
                 preg_match($rule, $ruleString, $regexRule);
476 476
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
477
-                 if(!empty($regexRule[0])){
477
+                 if (!empty($regexRule[0])) {
478 478
                      $ruleSets[] = $regexRule[0];
479 479
                  }
480 480
                  $ruleStringRegex = explode('|', $ruleStringTemp);
481 481
                 foreach ($ruleStringRegex as $rule) {
482 482
                     $rule = trim($rule);
483
-                    if($rule){
483
+                    if ($rule) {
484 484
                         $ruleSets[] = $rule;
485 485
                     }
486 486
                 }
487 487
                  
488 488
             }
489 489
             /***********************************/
490
-            else{
490
+            else {
491 491
                 if (strpos($ruleString, '|') !== FALSE) {
492 492
                     $ruleSets = explode('|', $ruleString);
493 493
                 } else {
@@ -519,7 +519,7 @@  discard block
 block discarded – undo
519 519
          * @return void
520 520
          */
521 521
         protected function _validateRule($inputName, $inputVal, $ruleName) {
522
-            $this->logger->debug('Rule validation of field [' .$inputName. '], value [' .$inputVal. '], rule [' .$ruleName. ']');
522
+            $this->logger->debug('Rule validation of field [' . $inputName . '], value [' . $inputVal . '], rule [' . $ruleName . ']');
523 523
             // Array to store args
524 524
             $ruleArgs = array();
525 525
 
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
                 $key = $i - 1;
565 565
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
566 566
             }
567
-            if (! array_key_exists($inputName, $this->_errors)) {
567
+            if (!array_key_exists($inputName, $this->_errors)) {
568 568
                 $this->_errors[$inputName] = $rulePhrase;
569 569
             }
570 570
         }
@@ -616,13 +616,13 @@  discard block
 block discarded – undo
616 616
          */
617 617
 		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
618 618
             $inputVal = $this->post($inputName);
619
-            if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
619
+            if (array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
620 620
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
621 621
                 if ($inputVal == '' && $callbackReturn == true) {
622 622
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
623 623
                 }
624 624
             } 
625
-			else if($inputVal == '') {
625
+			else if ($inputVal == '') {
626 626
 				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
627 627
             }
628 628
         }
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
649 649
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
650 650
 				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
651
-				if(! $result){
651
+				if (!$result) {
652 652
 					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
653 653
 				}
654 654
             }
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
                         continue;
683 683
                     }
684 684
                 } 
685
-				else{
685
+				else {
686 686
                     if ($inputVal == $doNotEqual) {
687 687
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
688 688
                         continue;
@@ -712,8 +712,8 @@  discard block
 block discarded – undo
712 712
          */
713 713
         protected function _validateValidEmail($inputName, $ruleName, array $ruleArgs) {
714 714
             $inputVal = $this->post($inputName);
715
-            if (! preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
716
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
715
+            if (!preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
716
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
717 717
                     return;
718 718
                 }
719 719
                 $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
         protected function _validateExactLength($inputName, $ruleName, array $ruleArgs) {
730 730
             $inputVal = $this->post($inputName);
731 731
             if (strlen($inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
732
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
732
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
733 733
                     return;
734 734
                 }
735 735
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
         protected function _validateMaxLength($inputName, $ruleName, array $ruleArgs) {
746 746
             $inputVal = $this->post($inputName);
747 747
             if (strlen($inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
748
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
748
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
749 749
                     return;
750 750
                 }
751 751
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
         protected function _validateMinLength($inputName, $ruleName, array $ruleArgs) {
762 762
             $inputVal = $this->post($inputName);
763 763
             if (strlen($inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
764
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
764
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
765 765
                     return;
766 766
                 }
767 767
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
     	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
778 778
             $inputVal = $this->post($inputName);
779 779
             if ($inputVal >= $ruleArgs[1]) { 
780
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
780
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
781 781
                     return;
782 782
                 }
783 783
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
     	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
794 794
             $inputVal = $this->post($inputName);
795 795
             if ($inputVal <= $ruleArgs[1]) {
796
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
796
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
797 797
                     return;
798 798
                 }
799 799
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -808,8 +808,8 @@  discard block
 block discarded – undo
808 808
          */
809 809
     	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
810 810
             $inputVal = $this->post($inputName);
811
-            if (! is_numeric($inputVal)) {
812
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
811
+            if (!is_numeric($inputVal)) {
812
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
813 813
                     return;
814 814
                 }
815 815
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -824,9 +824,9 @@  discard block
 block discarded – undo
824 824
          */
825 825
 		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
826 826
             $inputVal = $this->post($inputName);
827
-    		if (! is_object($this->databaseInstance)){
827
+    		if (!is_object($this->databaseInstance)) {
828 828
                 $obj = & get_instance();
829
-                if(isset($obj->database)){
829
+                if (isset($obj->database)) {
830 830
                     $this->databaseInstance = $obj->database;
831 831
                 } 
832 832
             }
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
     			                                       ->where($column, $inputVal);
836 836
     		$this->databaseInstance->get();
837 837
             if ($this->databaseInstance->numRows() <= 0) {
838
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
838
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
839 839
                     return;
840 840
                 }
841 841
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -850,9 +850,9 @@  discard block
 block discarded – undo
850 850
          */
851 851
     	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
852 852
             $inputVal = $this->post($inputName);
853
-            if (! is_object($this->databaseInstance)){
853
+            if (!is_object($this->databaseInstance)) {
854 854
                 $obj = & get_instance();
855
-                if(isset($obj->database)){
855
+                if (isset($obj->database)) {
856 856
                     $this->databaseInstance = $obj->database;
857 857
                 } 
858 858
             }
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
     			                                      ->where($column, $inputVal);
862 862
     		$this->databaseInstance->get();
863 863
     		if ($this->databaseInstance->numRows() > 0) {
864
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
864
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
865 865
                     return;
866 866
                 }
867 867
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -876,14 +876,14 @@  discard block
 block discarded – undo
876 876
          */
877 877
     	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
878 878
             $inputVal = $this->post($inputName);
879
-    		if (! is_object($this->databaseInstance)){
879
+    		if (!is_object($this->databaseInstance)) {
880 880
                 $obj = & get_instance();
881
-                if(isset($obj->database)){
881
+                if (isset($obj->database)) {
882 882
                     $this->databaseInstance = $obj->database;
883 883
                 } 
884 884
             }
885 885
     		$data = explode(',', $ruleArgs[1]);
886
-    		if(count($data) < 2){
886
+    		if (count($data) < 2) {
887 887
     			return;
888 888
     		}
889 889
     		list($table, $column) = explode('.', $data[0]);
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
                                             		  ->where($field, '!=', trim($val));
894 894
             $this->databaseInstance->get();
895 895
     		if ($this->databaseInstance->numRows() > 0) {
896
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
896
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
897 897
                     return;
898 898
                 }
899 899
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
             $inputVal = $this->post($inputName);
911 911
     		$list = explode(',', $ruleArgs[1]);
912 912
             $list = array_map('trim', $list);
913
-            if (! in_array($inputVal, $list)) {
914
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
913
+            if (!in_array($inputVal, $list)) {
914
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
915 915
                     return;
916 916
                 }
917 917
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -927,8 +927,8 @@  discard block
 block discarded – undo
927 927
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
928 928
             $inputVal = $this->post($inputName);
929 929
     		$regex = $ruleArgs[1];
930
-            if (! preg_match($regex, $inputVal)) {
931
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
930
+            if (!preg_match($regex, $inputVal)) {
931
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
932 932
                     return;
933 933
                 }
934 934
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
Please login to merge, or discard this patch.