Passed
Push — 1.0.0-dev ( 4efac2...b68981 )
by nguereza
02:49
created
tests/hmvc/models/DBSessionModel.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	class DBSessionModel extends DBSessionHandlerModel{
2
+	class DBSessionModel extends DBSessionHandlerModel {
3 3
 		
4 4
 		protected $_table = 'ses';
5 5
 		protected $primary_key = 's_id';
@@ -14,14 +14,14 @@  discard block
 block discarded – undo
14 14
 			'skey' => 'test_id' //VARCHAR(255) 
15 15
 		);
16 16
 		
17
-		public function deleteByTime($time){
17
+		public function deleteByTime($time) {
18 18
 			$this->getQueryBuilder()->from($this->_table)
19 19
 									->where('s_time', '<', $time);
20 20
 			$this->_database->delete();
21 21
 		}
22 22
 
23 23
 		
24
-		public function getKeyValue(){
24
+		public function getKeyValue() {
25 25
 			$user_id = 0;
26 26
 			return $user_id;
27 27
 		}
Please login to merge, or discard this patch.
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -1,28 +1,28 @@
 block discarded – undo
1 1
 <?php
2
-	class DBSessionModel extends DBSessionHandlerModel{
2
+    class DBSessionModel extends DBSessionHandlerModel{
3 3
 		
4
-		protected $_table = 'ses';
5
-		protected $primary_key = 's_id';
4
+        protected $_table = 'ses';
5
+        protected $primary_key = 's_id';
6 6
 		
7
-		protected $sessionTableColumns = array(
8
-			'sid' => 's_id', //VARCHAR(255)
9
-			'sdata' => 's_data', //TEXT
10
-			'stime' => 's_time', //unix timestamp (INT|BIGINT)
11
-			'shost' => 's_host', //VARCHAR(255)
12
-			'sip' => 's_ip', //VARCHAR(255) 
13
-			'sbrowser' => 's_browser', //VARCHAR(255) 
14
-			'skey' => 'test_id' //VARCHAR(255) 
15
-		);
7
+        protected $sessionTableColumns = array(
8
+            'sid' => 's_id', //VARCHAR(255)
9
+            'sdata' => 's_data', //TEXT
10
+            'stime' => 's_time', //unix timestamp (INT|BIGINT)
11
+            'shost' => 's_host', //VARCHAR(255)
12
+            'sip' => 's_ip', //VARCHAR(255) 
13
+            'sbrowser' => 's_browser', //VARCHAR(255) 
14
+            'skey' => 'test_id' //VARCHAR(255) 
15
+        );
16 16
 		
17
-		public function deleteByTime($time){
18
-			$this->getQueryBuilder()->from($this->_table)
19
-									->where('s_time', '<', $time);
20
-			$this->_database->delete();
21
-		}
17
+        public function deleteByTime($time){
18
+            $this->getQueryBuilder()->from($this->_table)
19
+                                    ->where('s_time', '<', $time);
20
+            $this->_database->delete();
21
+        }
22 22
 
23 23
 		
24
-		public function getKeyValue(){
25
-			$user_id = 0;
26
-			return $user_id;
27
-		}
28
-	}
29 24
\ No newline at end of file
25
+        public function getKeyValue(){
26
+            $user_id = 0;
27
+            return $user_id;
28
+        }
29
+    }
30 30
\ No newline at end of file
Please login to merge, or discard this patch.
tests/include/autoloader.php 3 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 	//Autoload function
3
-	function tests_autoload($class){
3
+	function tests_autoload($class) {
4 4
 		$classesMap = array(
5 5
 			//Caches
6 6
 			'ApcCache' => CORE_CLASSES_CACHE_PATH . 'ApcCache.php',
@@ -40,11 +40,11 @@  discard block
 block discarded – undo
40 40
 			'StringHash' => CORE_LIBRARY_PATH . 'StringHash.php',
41 41
 			'Upload' => CORE_LIBRARY_PATH . 'Upload.php',
42 42
 		);
43
-		if(isset($classesMap[$class])){
44
-			if(file_exists($classesMap[$class])){
43
+		if (isset($classesMap[$class])) {
44
+			if (file_exists($classesMap[$class])) {
45 45
 				require_once $classesMap[$class];
46 46
 			}
47
-			else{
47
+			else {
48 48
 				echo 'File for class ' . $class . ' not found';
49 49
 			}
50 50
 		}
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -43,8 +43,7 @@
 block discarded – undo
43 43
 		if(isset($classesMap[$class])){
44 44
 			if(file_exists($classesMap[$class])){
45 45
 				require_once $classesMap[$class];
46
-			}
47
-			else{
46
+			} else{
48 47
 				echo 'File for class ' . $class . ' not found';
49 48
 			}
50 49
 		}
Please login to merge, or discard this patch.
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -1,54 +1,54 @@
 block discarded – undo
1 1
 <?php
2
-	//Autoload function
3
-	function tests_autoload($class){
4
-		$classesMap = array(
5
-			//Caches
6
-			'ApcCache' => CORE_CLASSES_CACHE_PATH . 'ApcCache.php',
7
-			'CacheInterface' => CORE_CLASSES_CACHE_PATH . 'CacheInterface.php',
8
-			'FileCache' => CORE_CLASSES_CACHE_PATH . 'FileCache.php',
9
-			//models
10
-			'DBSessionHandlerModel' => CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php',
11
-			'Model' => CORE_CLASSES_MODEL_PATH . 'Model.php',
12
-			//Core classes
13
-			'Config' => CORE_CLASSES_PATH . 'Config.php',
14
-			'Controller' => CORE_CLASSES_PATH . 'Controller.php',
15
-			'Database' => CORE_CLASSES_DATABASE_PATH . 'Database.php',
16
-			'DatabaseQueryBuilder' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryBuilder.php',
17
-			'DatabaseQueryResult' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryResult.php',
18
-			'DatabaseQueryRunner' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryRunner.php',
19
-			'DBSessionHandler' => CORE_CLASSES_PATH . 'DBSessionHandler.php',
20
-			'EventInfo' => CORE_CLASSES_PATH . 'EventInfo.php',
21
-			'EventDispatcher' => CORE_CLASSES_PATH . 'EventDispatcher.php',
22
-			'Lang' => CORE_CLASSES_PATH . 'Lang.php',
23
-			'Loader' => CORE_CLASSES_PATH . 'Loader.php',
24
-			'Log' => CORE_CLASSES_PATH . 'Log.php',
25
-			'Module' => CORE_CLASSES_PATH . 'Module.php',
26
-			'Request' => CORE_CLASSES_PATH . 'Request.php',
27
-			'Response' => CORE_CLASSES_PATH . 'Response.php',
28
-			'Router' => CORE_CLASSES_PATH . 'Router.php',
29
-			'Security' => CORE_CLASSES_PATH . 'Security.php',
30
-			'Session' => CORE_CLASSES_PATH . 'Session.php',
31
-			'Url' => CORE_CLASSES_PATH . 'Url.php',
32
-			//Core libraries
33
-			'Assets' => CORE_LIBRARY_PATH . 'Assets.php',
34
-			'Benchmark' => CORE_LIBRARY_PATH . 'Benchmark.php',
35
-			'Browser' => CORE_LIBRARY_PATH . 'Browser.php',
36
-			'Cookie' => CORE_LIBRARY_PATH . 'Cookie.php',
37
-			'Email' => CORE_LIBRARY_PATH . 'Email.php',
38
-			'Form' => CORE_LIBRARY_PATH . 'Form.php',
39
-			'FormValidation' => CORE_LIBRARY_PATH . 'FormValidation.php',
40
-			'Html' => CORE_LIBRARY_PATH . 'Html.php',
41
-			'Pagination' => CORE_LIBRARY_PATH . 'Pagination.php',
42
-			'PDF' => CORE_LIBRARY_PATH . 'PDF.php',
43
-			'StringHash' => CORE_LIBRARY_PATH . 'StringHash.php',
44
-			'Upload' => CORE_LIBRARY_PATH . 'Upload.php',
45
-		);
46
-		if(isset($classesMap[$class])){
47
-			if(file_exists($classesMap[$class])){
48
-				require_once $classesMap[$class];
49
-			}
50
-			else{
51
-				echo 'File for class ' . $class . ' not found';
52
-			}
53
-		}
54
-	}
55 2
\ No newline at end of file
3
+    //Autoload function
4
+    function tests_autoload($class){
5
+        $classesMap = array(
6
+            //Caches
7
+            'ApcCache' => CORE_CLASSES_CACHE_PATH . 'ApcCache.php',
8
+            'CacheInterface' => CORE_CLASSES_CACHE_PATH . 'CacheInterface.php',
9
+            'FileCache' => CORE_CLASSES_CACHE_PATH . 'FileCache.php',
10
+            //models
11
+            'DBSessionHandlerModel' => CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php',
12
+            'Model' => CORE_CLASSES_MODEL_PATH . 'Model.php',
13
+            //Core classes
14
+            'Config' => CORE_CLASSES_PATH . 'Config.php',
15
+            'Controller' => CORE_CLASSES_PATH . 'Controller.php',
16
+            'Database' => CORE_CLASSES_DATABASE_PATH . 'Database.php',
17
+            'DatabaseQueryBuilder' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryBuilder.php',
18
+            'DatabaseQueryResult' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryResult.php',
19
+            'DatabaseQueryRunner' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryRunner.php',
20
+            'DBSessionHandler' => CORE_CLASSES_PATH . 'DBSessionHandler.php',
21
+            'EventInfo' => CORE_CLASSES_PATH . 'EventInfo.php',
22
+            'EventDispatcher' => CORE_CLASSES_PATH . 'EventDispatcher.php',
23
+            'Lang' => CORE_CLASSES_PATH . 'Lang.php',
24
+            'Loader' => CORE_CLASSES_PATH . 'Loader.php',
25
+            'Log' => CORE_CLASSES_PATH . 'Log.php',
26
+            'Module' => CORE_CLASSES_PATH . 'Module.php',
27
+            'Request' => CORE_CLASSES_PATH . 'Request.php',
28
+            'Response' => CORE_CLASSES_PATH . 'Response.php',
29
+            'Router' => CORE_CLASSES_PATH . 'Router.php',
30
+            'Security' => CORE_CLASSES_PATH . 'Security.php',
31
+            'Session' => CORE_CLASSES_PATH . 'Session.php',
32
+            'Url' => CORE_CLASSES_PATH . 'Url.php',
33
+            //Core libraries
34
+            'Assets' => CORE_LIBRARY_PATH . 'Assets.php',
35
+            'Benchmark' => CORE_LIBRARY_PATH . 'Benchmark.php',
36
+            'Browser' => CORE_LIBRARY_PATH . 'Browser.php',
37
+            'Cookie' => CORE_LIBRARY_PATH . 'Cookie.php',
38
+            'Email' => CORE_LIBRARY_PATH . 'Email.php',
39
+            'Form' => CORE_LIBRARY_PATH . 'Form.php',
40
+            'FormValidation' => CORE_LIBRARY_PATH . 'FormValidation.php',
41
+            'Html' => CORE_LIBRARY_PATH . 'Html.php',
42
+            'Pagination' => CORE_LIBRARY_PATH . 'Pagination.php',
43
+            'PDF' => CORE_LIBRARY_PATH . 'PDF.php',
44
+            'StringHash' => CORE_LIBRARY_PATH . 'StringHash.php',
45
+            'Upload' => CORE_LIBRARY_PATH . 'Upload.php',
46
+        );
47
+        if(isset($classesMap[$class])){
48
+            if(file_exists($classesMap[$class])){
49
+                require_once $classesMap[$class];
50
+            }
51
+            else{
52
+                echo 'File for class ' . $class . ' not found';
53
+            }
54
+        }
55
+    }
56 56
\ No newline at end of file
Please login to merge, or discard this patch.
core/common.php 3 patches
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -53,14 +53,14 @@  discard block
 block discarded – undo
53 53
 		//put the first letter of class to upper case 
54 54
 		$class = ucfirst($class);
55 55
 		static $classes = array();
56
-		if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log'){
56
+		if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log') {
57 57
 			return $classes[$class];
58 58
 		}
59 59
 		$found = false;
60 60
 		foreach (array(ROOT_PATH, CORE_PATH) as $path) {
61 61
 			$file = $path . $dir . '/' . $class . '.php';
62
-			if (file_exists($file)){
63
-				if (class_exists($class, false) === false){
62
+			if (file_exists($file)) {
63
+				if (class_exists($class, false) === false) {
64 64
 					require_once $file;
65 65
 				}
66 66
 				//already found
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 				break;
69 69
 			}
70 70
 		}
71
-		if (! $found){
71
+		if (!$found) {
72 72
 			//can't use show_error() at this time because some dependencies not yet loaded
73 73
 			set_http_status_header(503);
74 74
 			echo 'Cannot find the class [' . $class . ']';
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 		/*
79 79
 		   TODO use the best method to get the Log instance
80 80
 		 */
81
-		if ($class == 'Log'){
81
+		if ($class == 'Log') {
82 82
 			//can't use the instruction like "return new Log()" 
83 83
 			//because we need return the reference instance of the loaded class.
84 84
 			$log = new Log();
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 	 */
103 103
 	function & class_loaded($class = null){
104 104
 		static $list = array();
105
-		if ($class !== null){
105
+		if ($class !== null) {
106 106
 			$list[strtolower($class)] = $class;
107 107
 		}
108 108
 		return $list;
@@ -117,14 +117,14 @@  discard block
 block discarded – undo
117 117
 	 */
118 118
 	function & load_configurations(array $overwrite_values = array()){
119 119
 		static $config;
120
-		if (empty($config)){
120
+		if (empty($config)) {
121 121
 			$file = CONFIG_PATH . 'config.php';
122 122
 			$found = false;
123
-			if (file_exists($file)){
123
+			if (file_exists($file)) {
124 124
 				require_once $file;
125 125
 				$found = true;
126 126
 			}
127
-			if (! $found){
127
+			if (!$found) {
128 128
 				set_http_status_header(503);
129 129
 				echo 'Unable to find the configuration file [' . $file . ']';
130 130
 				die();
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 	 * 
145 145
 	 * @return mixed          the config value
146 146
 	 */
147
-	function get_config($key, $default = null){
147
+	function get_config($key, $default = null) {
148 148
 		static $cfg;
149
-		if (empty($cfg)){
149
+		if (empty($cfg)) {
150 150
 			$cfg[0] = & load_configurations();
151 151
 		}
152 152
 		return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
@@ -160,9 +160,9 @@  discard block
 block discarded – undo
160 160
 	 * 
161 161
 	 * @codeCoverageIgnore
162 162
 	 */
163
-	function save_to_log($level, $message, $logger = null){
164
-		$log =& class_loader('Log', 'classes');
165
-		if ($logger){
163
+	function save_to_log($level, $message, $logger = null) {
164
+		$log = & class_loader('Log', 'classes');
165
+		if ($logger) {
166 166
 			$log->setLogger($logger);
167 167
 		}
168 168
 		$log->writeLog($message, $level);
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
 	 * 
176 176
 	 * @codeCoverageIgnore
177 177
 	 */
178
-	function set_http_status_header($code = 200, $text = null){
179
-		if (empty($text)){
178
+	function set_http_status_header($code = 200, $text = null) {
179
+		if (empty($text)) {
180 180
 			$http_status = array(
181 181
 								100 => 'Continue',
182 182
 								101 => 'Switching Protocols',
@@ -224,18 +224,18 @@  discard block
 block discarded – undo
224 224
 								504 => 'Gateway Timeout',
225 225
 								505 => 'HTTP Version Not Supported',
226 226
 							);
227
-			if (isset($http_status[$code])){
227
+			if (isset($http_status[$code])) {
228 228
 				$text = $http_status[$code];
229 229
 			}
230
-			else{
230
+			else {
231 231
 				show_error('No HTTP status text found for your code please check it.');
232 232
 			}
233 233
 		}
234 234
 		
235
-		if (strpos(php_sapi_name(), 'cgi') === 0){
235
+		if (strpos(php_sapi_name(), 'cgi') === 0) {
236 236
 			header('Status: ' . $code . ' ' . $text, TRUE);
237 237
 		}
238
-		else{
238
+		else {
239 239
 			$proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240 240
 			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241 241
 		}
@@ -250,13 +250,13 @@  discard block
 block discarded – undo
250 250
 	 *  
251 251
 	 *  @codeCoverageIgnore
252 252
 	 */
253
-	function show_error($msg, $title = 'error', $logging = true){
253
+	function show_error($msg, $title = 'error', $logging = true) {
254 254
 		$title = strtoupper($title);
255 255
 		$data = array();
256 256
 		$data['error'] = $msg;
257 257
 		$data['title'] = $title;
258
-		if ($logging){
259
-			save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
258
+		if ($logging) {
259
+			save_to_log('error', '[' . $title . '] ' . strip_tags($msg), 'GLOBAL::ERROR');
260 260
 		}
261 261
 		$response = & class_loader('Response', 'classes');
262 262
 		$response->sendError($data);
@@ -270,18 +270,18 @@  discard block
 block discarded – undo
270 270
 	 *  
271 271
 	 *  @return boolean true if the web server uses the https protocol, false if not.
272 272
 	 */
273
-	function is_https(){
273
+	function is_https() {
274 274
 		/*
275 275
 		* some servers pass the "HTTPS" parameter in the server variable,
276 276
 		* if is the case, check if the value is "on", "true", "1".
277 277
 		*/
278
-		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
278
+		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
279 279
 			return true;
280 280
 		}
281
-		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
281
+		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
282 282
 			return true;
283 283
 		}
284
-		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
284
+		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
285 285
 			return true;
286 286
 		}
287 287
 		return false;
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 	 *  
297 297
 	 *  @return boolean true if is a valid URL address or false.
298 298
 	 */
299
-	function is_url($url){
299
+	function is_url($url) {
300 300
 		return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
301 301
 	}
302 302
 	
@@ -306,8 +306,8 @@  discard block
 block discarded – undo
306 306
 	 *  @param string $controllerClass the controller class name to be loaded
307 307
 	 *  @codeCoverageIgnore
308 308
 	 */
309
-	function autoload_controller($controllerClass){
310
-		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
309
+	function autoload_controller($controllerClass) {
310
+		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')) {
311 311
 			require_once $path;
312 312
 		}
313 313
 	}
@@ -321,11 +321,11 @@  discard block
 block discarded – undo
321 321
 	 *  
322 322
 	 *  @return boolean
323 323
 	 */
324
-	function php_exception_handler($ex){
325
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326
-			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
324
+	function php_exception_handler($ex) {
325
+		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
326
+			show_error('An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327 327
 		}
328
-		else{
328
+		else {
329 329
 			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330 330
 		}
331 331
 		return true;
@@ -342,16 +342,16 @@  discard block
 block discarded – undo
342 342
 	 *  
343 343
 	 *  @return boolean	
344 344
 	 */
345
-	function php_error_handler($errno , $errstr, $errfile , $errline){
345
+	function php_error_handler($errno, $errstr, $errfile, $errline) {
346 346
 		$isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
347
-		if ($isError){
347
+		if ($isError) {
348 348
 			set_http_status_header(500);
349 349
 		}
350
-		if (! (error_reporting() & $errno)) {
350
+		if (!(error_reporting() & $errno)) {
351 351
 			save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
352 352
 			return;
353 353
 		}
354
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
354
+		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
355 355
 			$errorType = 'error';
356 356
 			switch ($errno) {
357 357
 				case E_USER_ERROR:
@@ -367,9 +367,9 @@  discard block
 block discarded – undo
367 367
 					$errorType = 'error';
368 368
 					break;
369 369
 			}
370
-			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
370
+			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline . '</b> raison : ' . $errstr, 'PHP ' . $errorType);
371 371
 		}
372
-		if ($isError){
372
+		if ($isError) {
373 373
 			die();
374 374
 		}
375 375
 		return true;
@@ -379,10 +379,10 @@  discard block
 block discarded – undo
379 379
 	 * This function is used to run in shutdown situation of the script
380 380
 	 * @codeCoverageIgnore
381 381
 	 */
382
-	function php_shudown_handler(){
382
+	function php_shudown_handler() {
383 383
 		$lastError = error_get_last();
384 384
 		if (isset($lastError) &&
385
-			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
385
+			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))) {
386 386
 			php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
387 387
 		}
388 388
 	}
@@ -400,11 +400,11 @@  discard block
 block discarded – undo
400 400
 	 *   
401 401
 	 *  @return string string of the HTML attribute.
402 402
 	 */
403
-	function attributes_to_string(array $attributes){
403
+	function attributes_to_string(array $attributes) {
404 404
 		$str = ' ';
405 405
 		//we check that the array passed as an argument is not empty.
406
-		if (! empty($attributes)){
407
-			foreach($attributes as $key => $value){
406
+		if (!empty($attributes)) {
407
+			foreach ($attributes as $key => $value) {
408 408
 				$key = trim(htmlspecialchars($key));
409 409
 				$value = trim(htmlspecialchars($value));
410 410
 				/*
@@ -414,10 +414,10 @@  discard block
 block discarded – undo
414 414
 				* 	$attr = array('placeholder' => 'I am a "puple"')
415 415
 				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
416 416
 				 */
417
-				if ($value && strpos('"', $value) !== false){
417
+				if ($value && strpos('"', $value) !== false) {
418 418
 					$value = addslashes($value);
419 419
 				}
420
-				$str .= $key.' = "'.$value.'" ';
420
+				$str .= $key . ' = "' . $value . '" ';
421 421
 			}
422 422
 		}
423 423
 		//remove the space after using rtrim()
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 	*
434 434
 	* @return string the stringfy value
435 435
 	*/
436
-	function stringfy_vars($var){
436
+	function stringfy_vars($var) {
437 437
 		return print_r($var, true);
438 438
 	}
439 439
 
@@ -444,18 +444,18 @@  discard block
 block discarded – undo
444 444
 	 * 
445 445
 	 * @return mixed   the sanitize value
446 446
 	 */
447
-	function clean_input($str){
448
-		if (is_array($str)){
447
+	function clean_input($str) {
448
+		if (is_array($str)) {
449 449
 			$str = array_map('clean_input', $str);
450 450
 		}
451
-		else if (is_object($str)){
451
+		else if (is_object($str)) {
452 452
 			$obj = $str;
453 453
 			foreach ($str as $var => $value) {
454 454
 				$obj->$var = clean_input($value);
455 455
 			}
456 456
 			$str = $obj;
457 457
 		}
458
-		else{
458
+		else {
459 459
 			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460 460
 		}
461 461
 		return $str;
@@ -473,11 +473,11 @@  discard block
 block discarded – undo
473 473
 	 * 
474 474
 	 * @return string the string with the hidden part.
475 475
 	 */
476
-	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
476
+	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*') {
477 477
 		//get the string length
478 478
 		$len = strlen($str);
479 479
 		//if str is empty
480
-		if ($len <= 0){
480
+		if ($len <= 0) {
481 481
 			return str_repeat($hiddenChar, 6);
482 482
 		}
483 483
 		//if the length is less than startCount and endCount
@@ -485,14 +485,14 @@  discard block
 block discarded – undo
485 485
 		//or startCount is negative or endCount is negative
486 486
 		//return the full string hidden
487 487
 		
488
-		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
488
+		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)) {
489 489
 			return str_repeat($hiddenChar, $len);
490 490
 		}
491 491
 		//the start non hidden string
492 492
 		$startNonHiddenStr = substr($str, 0, $startCount);
493 493
 		//the end non hidden string
494 494
 		$endNonHiddenStr = null;
495
-		if ($endCount > 0){
495
+		if ($endCount > 0) {
496 496
 			$endNonHiddenStr = substr($str, - $endCount);
497 497
 		}
498 498
 		//the hidden string
@@ -505,40 +505,40 @@  discard block
 block discarded – undo
505 505
 	 * This function is used to set the initial session config regarding the configuration
506 506
 	 * @codeCoverageIgnore
507 507
 	 */
508
-	function set_session_config(){
508
+	function set_session_config() {
509 509
 		//$_SESSION is not available on cli mode 
510
-		if (! IS_CLI){
511
-			$logger =& class_loader('Log', 'classes');
510
+		if (!IS_CLI) {
511
+			$logger = & class_loader('Log', 'classes');
512 512
 			$logger->setLogger('PHPSession');
513 513
 			//set session params
514 514
 			$sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
515 515
 			$sessionName = get_config('session_name');
516
-			if ($sessionName){
516
+			if ($sessionName) {
517 517
 				session_name($sessionName);
518 518
 			}
519 519
 			$logger->info('Session handler: ' . $sessionHandler);
520 520
 			$logger->info('Session name: ' . $sessionName);
521 521
 
522
-			if ($sessionHandler == 'files'){
522
+			if ($sessionHandler == 'files') {
523 523
 				$sessionSavePath = get_config('session_save_path');
524
-				if ($sessionSavePath){
525
-					if (! is_dir($sessionSavePath)){
524
+				if ($sessionSavePath) {
525
+					if (!is_dir($sessionSavePath)) {
526 526
 						mkdir($sessionSavePath, 1773);
527 527
 					}
528 528
 					session_save_path($sessionSavePath);
529 529
 					$logger->info('Session save path: ' . $sessionSavePath);
530 530
 				}
531 531
 			}
532
-			else if ($sessionHandler == 'database'){
532
+			else if ($sessionHandler == 'database') {
533 533
 				//load database session handle library
534 534
 				//Database Session handler Model
535 535
 				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
536 536
 
537
-				$DBS =& class_loader('DBSessionHandler', 'classes');
537
+				$DBS = & class_loader('DBSessionHandler', 'classes');
538 538
 				session_set_save_handler($DBS, true);
539 539
 				$logger->info('session save path: ' . get_config('session_save_path'));
540 540
 			}
541
-			else{
541
+			else {
542 542
 				show_error('Invalid session handler configuration');
543 543
 			}
544 544
 			$lifetime = get_config('session_cookie_lifetime', 0);
@@ -561,9 +561,9 @@  discard block
 block discarded – undo
561 561
 			$logger->info('Session lifetime: ' . $lifetime);
562 562
 			$logger->info('Session cookie path: ' . $path);
563 563
 			$logger->info('Session domain: ' . $domain);
564
-			$logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
564
+			$logger->info('Session is secure: ' . ($secure ? 'TRUE' : 'FALSE'));
565 565
 			
566
-			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
566
+			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
567 567
 				$logger->info('Session not yet start, start it now');
568 568
 				session_start();
569 569
 			}
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -226,16 +226,14 @@  discard block
 block discarded – undo
226 226
 							);
227 227
 			if (isset($http_status[$code])){
228 228
 				$text = $http_status[$code];
229
-			}
230
-			else{
229
+			} else{
231 230
 				show_error('No HTTP status text found for your code please check it.');
232 231
 			}
233 232
 		}
234 233
 		
235 234
 		if (strpos(php_sapi_name(), 'cgi') === 0){
236 235
 			header('Status: ' . $code . ' ' . $text, TRUE);
237
-		}
238
-		else{
236
+		} else{
239 237
 			$proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240 238
 			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241 239
 		}
@@ -277,11 +275,9 @@  discard block
 block discarded – undo
277 275
 		*/
278 276
 		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
279 277
 			return true;
280
-		}
281
-		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
278
+		} else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
282 279
 			return true;
283
-		}
284
-		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
280
+		} else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
285 281
 			return true;
286 282
 		}
287 283
 		return false;
@@ -324,8 +320,7 @@  discard block
 block discarded – undo
324 320
 	function php_exception_handler($ex){
325 321
 		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326 322
 			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327
-		}
328
-		else{
323
+		} else{
329 324
 			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330 325
 		}
331 326
 		return true;
@@ -447,15 +442,13 @@  discard block
 block discarded – undo
447 442
 	function clean_input($str){
448 443
 		if (is_array($str)){
449 444
 			$str = array_map('clean_input', $str);
450
-		}
451
-		else if (is_object($str)){
445
+		} else if (is_object($str)){
452 446
 			$obj = $str;
453 447
 			foreach ($str as $var => $value) {
454 448
 				$obj->$var = clean_input($value);
455 449
 			}
456 450
 			$str = $obj;
457
-		}
458
-		else{
451
+		} else{
459 452
 			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460 453
 		}
461 454
 		return $str;
@@ -528,8 +521,7 @@  discard block
 block discarded – undo
528 521
 					session_save_path($sessionSavePath);
529 522
 					$logger->info('Session save path: ' . $sessionSavePath);
530 523
 				}
531
-			}
532
-			else if ($sessionHandler == 'database'){
524
+			} else if ($sessionHandler == 'database'){
533 525
 				//load database session handle library
534 526
 				//Database Session handler Model
535 527
 				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
@@ -537,8 +529,7 @@  discard block
 block discarded – undo
537 529
 				$DBS =& class_loader('DBSessionHandler', 'classes');
538 530
 				session_set_save_handler($DBS, true);
539 531
 				$logger->info('session save path: ' . get_config('session_save_path'));
540
-			}
541
-			else{
532
+			} else{
542 533
 				show_error('Invalid session handler configuration');
543 534
 			}
544 535
 			$lifetime = get_config('session_cookie_lifetime', 0);
Please login to merge, or discard this patch.
Indentation   +536 added lines, -536 removed lines patch added patch discarded remove patch
@@ -1,585 +1,585 @@
 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
-	/**
28
-	 *  @file common.php
29
-	 *  
30
-	 *  Contains most of the commons functions used by the system
31
-	 *  
32
-	 *  @package	core
33
-	 *  @author	Tony NGUEREZA
34
-	 *  @copyright	Copyright (c) 2017
35
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
-	 *  @link	http://www.iacademy.cf
37
-	 *  @version 1.0.0
38
-	 *  @filesource
39
-	 */
27
+    /**
28
+     *  @file common.php
29
+     *  
30
+     *  Contains most of the commons functions used by the system
31
+     *  
32
+     *  @package	core
33
+     *  @author	Tony NGUEREZA
34
+     *  @copyright	Copyright (c) 2017
35
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
+     *  @link	http://www.iacademy.cf
37
+     *  @version 1.0.0
38
+     *  @filesource
39
+     */
40 40
 	
41 41
 
42
-	/**
43
-	 * This function is the class loader helper is used if the library "Loader" not yet loaded
44
-	 * he load the class once
45
-	 * @param  string $class  the class name to be loaded
46
-	 * @param  string $dir    the directory where to find the class
47
-	 * @param  mixed $params the parameter to pass as argument to the constructor of the class
48
-	 * @codeCoverageIgnore
49
-	 * 
50
-	 * @return object         the instance of the loaded class
51
-	 */
52
-	function & class_loader($class, $dir = 'libraries', $params = null){
53
-		//put the first letter of class to upper case 
54
-		$class = ucfirst($class);
55
-		static $classes = array();
56
-		if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log'){
57
-			return $classes[$class];
58
-		}
59
-		$found = false;
60
-		foreach (array(ROOT_PATH, CORE_PATH) as $path) {
61
-			$file = $path . $dir . '/' . $class . '.php';
62
-			if (file_exists($file)){
63
-				if (class_exists($class, false) === false){
64
-					require_once $file;
65
-				}
66
-				//already found
67
-				$found = true;
68
-				break;
69
-			}
70
-		}
71
-		if (! $found){
72
-			//can't use show_error() at this time because some dependencies not yet loaded
73
-			set_http_status_header(503);
74
-			echo 'Cannot find the class [' . $class . ']';
75
-			die();
76
-		}
42
+    /**
43
+     * This function is the class loader helper is used if the library "Loader" not yet loaded
44
+     * he load the class once
45
+     * @param  string $class  the class name to be loaded
46
+     * @param  string $dir    the directory where to find the class
47
+     * @param  mixed $params the parameter to pass as argument to the constructor of the class
48
+     * @codeCoverageIgnore
49
+     * 
50
+     * @return object         the instance of the loaded class
51
+     */
52
+    function & class_loader($class, $dir = 'libraries', $params = null){
53
+        //put the first letter of class to upper case 
54
+        $class = ucfirst($class);
55
+        static $classes = array();
56
+        if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log'){
57
+            return $classes[$class];
58
+        }
59
+        $found = false;
60
+        foreach (array(ROOT_PATH, CORE_PATH) as $path) {
61
+            $file = $path . $dir . '/' . $class . '.php';
62
+            if (file_exists($file)){
63
+                if (class_exists($class, false) === false){
64
+                    require_once $file;
65
+                }
66
+                //already found
67
+                $found = true;
68
+                break;
69
+            }
70
+        }
71
+        if (! $found){
72
+            //can't use show_error() at this time because some dependencies not yet loaded
73
+            set_http_status_header(503);
74
+            echo 'Cannot find the class [' . $class . ']';
75
+            die();
76
+        }
77 77
 		
78
-		/*
78
+        /*
79 79
 		   TODO use the best method to get the Log instance
80 80
 		 */
81
-		if ($class == 'Log'){
82
-			//can't use the instruction like "return new Log()" 
83
-			//because we need return the reference instance of the loaded class.
84
-			$log = new Log();
85
-			return $log;
86
-		}
87
-		//track of loaded classes
88
-		class_loaded($class);
81
+        if ($class == 'Log'){
82
+            //can't use the instruction like "return new Log()" 
83
+            //because we need return the reference instance of the loaded class.
84
+            $log = new Log();
85
+            return $log;
86
+        }
87
+        //track of loaded classes
88
+        class_loaded($class);
89 89
 		
90
-		//record the class instance
91
-		$classes[$class] = isset($params) ? new $class($params) : new $class();
90
+        //record the class instance
91
+        $classes[$class] = isset($params) ? new $class($params) : new $class();
92 92
 		
93
-		return $classes[$class];
94
-	}
93
+        return $classes[$class];
94
+    }
95 95
 
96
-	/**
97
-	 * This function is the helper to record the loaded classes
98
-	 * @param  string $class the loaded class name
99
-	 * @codeCoverageIgnore
100
-	 * 
101
-	 * @return array        the list of the loaded classes
102
-	 */
103
-	function & class_loaded($class = null){
104
-		static $list = array();
105
-		if ($class !== null){
106
-			$list[strtolower($class)] = $class;
107
-		}
108
-		return $list;
109
-	}
96
+    /**
97
+     * This function is the helper to record the loaded classes
98
+     * @param  string $class the loaded class name
99
+     * @codeCoverageIgnore
100
+     * 
101
+     * @return array        the list of the loaded classes
102
+     */
103
+    function & class_loaded($class = null){
104
+        static $list = array();
105
+        if ($class !== null){
106
+            $list[strtolower($class)] = $class;
107
+        }
108
+        return $list;
109
+    }
110 110
 
111
-	/**
112
-	 * This function is used to load the configurations in the case the "Config" library not yet loaded
113
-	 * @param  array  $overwrite_values if need overwrite the existing configuration
114
-	 * @codeCoverageIgnore
115
-	 * 
116
-	 * @return array                   the configurations values
117
-	 */
118
-	function & load_configurations(array $overwrite_values = array()){
119
-		static $config;
120
-		if (empty($config)){
121
-			$file = CONFIG_PATH . 'config.php';
122
-			$found = false;
123
-			if (file_exists($file)){
124
-				require_once $file;
125
-				$found = true;
126
-			}
127
-			if (! $found){
128
-				set_http_status_header(503);
129
-				echo 'Unable to find the configuration file [' . $file . ']';
130
-				die();
131
-			}
132
-		}
133
-		foreach ($overwrite_values as $key => $value) {
134
-			$config[$key] = $value;
135
-		}
136
-		return $config;
137
-	}
111
+    /**
112
+     * This function is used to load the configurations in the case the "Config" library not yet loaded
113
+     * @param  array  $overwrite_values if need overwrite the existing configuration
114
+     * @codeCoverageIgnore
115
+     * 
116
+     * @return array                   the configurations values
117
+     */
118
+    function & load_configurations(array $overwrite_values = array()){
119
+        static $config;
120
+        if (empty($config)){
121
+            $file = CONFIG_PATH . 'config.php';
122
+            $found = false;
123
+            if (file_exists($file)){
124
+                require_once $file;
125
+                $found = true;
126
+            }
127
+            if (! $found){
128
+                set_http_status_header(503);
129
+                echo 'Unable to find the configuration file [' . $file . ']';
130
+                die();
131
+            }
132
+        }
133
+        foreach ($overwrite_values as $key => $value) {
134
+            $config[$key] = $value;
135
+        }
136
+        return $config;
137
+    }
138 138
 
139
-	/**
140
-	 * This function is the helper to get the config value in case the "Config" library not yet loaded
141
-	 * @param  string $key     the config item to get the vale
142
-	 * @param  mixed $default the default value to return if can't find the config item in the configuration
143
-	 * @test
144
-	 * 
145
-	 * @return mixed          the config value
146
-	 */
147
-	function get_config($key, $default = null){
148
-		static $cfg;
149
-		if (empty($cfg)){
150
-			$cfg[0] = & load_configurations();
151
-		}
152
-		return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
153
-	}
139
+    /**
140
+     * This function is the helper to get the config value in case the "Config" library not yet loaded
141
+     * @param  string $key     the config item to get the vale
142
+     * @param  mixed $default the default value to return if can't find the config item in the configuration
143
+     * @test
144
+     * 
145
+     * @return mixed          the config value
146
+     */
147
+    function get_config($key, $default = null){
148
+        static $cfg;
149
+        if (empty($cfg)){
150
+            $cfg[0] = & load_configurations();
151
+        }
152
+        return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
153
+    }
154 154
 
155
-	/**
156
-	 * This function is a helper to logging message
157
-	 * @param  string $level   the log level "ERROR", "DEBUG", "INFO", etc.
158
-	 * @param  string $message the log message to be saved
159
-	 * @param  string $logger  the logger to use if is set
160
-	 * 
161
-	 * @codeCoverageIgnore
162
-	 */
163
-	function save_to_log($level, $message, $logger = null){
164
-		$log =& class_loader('Log', 'classes');
165
-		if ($logger){
166
-			$log->setLogger($logger);
167
-		}
168
-		$log->writeLog($message, $level);
169
-	}
155
+    /**
156
+     * This function is a helper to logging message
157
+     * @param  string $level   the log level "ERROR", "DEBUG", "INFO", etc.
158
+     * @param  string $message the log message to be saved
159
+     * @param  string $logger  the logger to use if is set
160
+     * 
161
+     * @codeCoverageIgnore
162
+     */
163
+    function save_to_log($level, $message, $logger = null){
164
+        $log =& class_loader('Log', 'classes');
165
+        if ($logger){
166
+            $log->setLogger($logger);
167
+        }
168
+        $log->writeLog($message, $level);
169
+    }
170 170
 
171
-	/**
172
-	 * Set the HTTP status header
173
-	 * @param integer $code the HTTP status code
174
-	 * @param string  $text the HTTP status text
175
-	 * 
176
-	 * @codeCoverageIgnore
177
-	 */
178
-	function set_http_status_header($code = 200, $text = null){
179
-		if (empty($text)){
180
-			$http_status = array(
181
-								100 => 'Continue',
182
-								101 => 'Switching Protocols',
171
+    /**
172
+     * Set the HTTP status header
173
+     * @param integer $code the HTTP status code
174
+     * @param string  $text the HTTP status text
175
+     * 
176
+     * @codeCoverageIgnore
177
+     */
178
+    function set_http_status_header($code = 200, $text = null){
179
+        if (empty($text)){
180
+            $http_status = array(
181
+                                100 => 'Continue',
182
+                                101 => 'Switching Protocols',
183 183
 
184
-								200 => 'OK',
185
-								201 => 'Created',
186
-								202 => 'Accepted',
187
-								203 => 'Non-Authoritative Information',
188
-								204 => 'No Content',
189
-								205 => 'Reset Content',
190
-								206 => 'Partial Content',
184
+                                200 => 'OK',
185
+                                201 => 'Created',
186
+                                202 => 'Accepted',
187
+                                203 => 'Non-Authoritative Information',
188
+                                204 => 'No Content',
189
+                                205 => 'Reset Content',
190
+                                206 => 'Partial Content',
191 191
 
192
-								300 => 'Multiple Choices',
193
-								301 => 'Moved Permanently',
194
-								302 => 'Found',
195
-								303 => 'See Other',
196
-								304 => 'Not Modified',
197
-								305 => 'Use Proxy',
198
-								307 => 'Temporary Redirect',
192
+                                300 => 'Multiple Choices',
193
+                                301 => 'Moved Permanently',
194
+                                302 => 'Found',
195
+                                303 => 'See Other',
196
+                                304 => 'Not Modified',
197
+                                305 => 'Use Proxy',
198
+                                307 => 'Temporary Redirect',
199 199
 
200
-								400 => 'Bad Request',
201
-								401 => 'Unauthorized',
202
-								402 => 'Payment Required',
203
-								403 => 'Forbidden',
204
-								404 => 'Not Found',
205
-								405 => 'Method Not Allowed',
206
-								406 => 'Not Acceptable',
207
-								407 => 'Proxy Authentication Required',
208
-								408 => 'Request Timeout',
209
-								409 => 'Conflict',
210
-								410 => 'Gone',
211
-								411 => 'Length Required',
212
-								412 => 'Precondition Failed',
213
-								413 => 'Request Entity Too Large',
214
-								414 => 'Request-URI Too Long',
215
-								415 => 'Unsupported Media Type',
216
-								416 => 'Requested Range Not Satisfiable',
217
-								417 => 'Expectation Failed',
218
-								418 => 'I\'m a teapot',
200
+                                400 => 'Bad Request',
201
+                                401 => 'Unauthorized',
202
+                                402 => 'Payment Required',
203
+                                403 => 'Forbidden',
204
+                                404 => 'Not Found',
205
+                                405 => 'Method Not Allowed',
206
+                                406 => 'Not Acceptable',
207
+                                407 => 'Proxy Authentication Required',
208
+                                408 => 'Request Timeout',
209
+                                409 => 'Conflict',
210
+                                410 => 'Gone',
211
+                                411 => 'Length Required',
212
+                                412 => 'Precondition Failed',
213
+                                413 => 'Request Entity Too Large',
214
+                                414 => 'Request-URI Too Long',
215
+                                415 => 'Unsupported Media Type',
216
+                                416 => 'Requested Range Not Satisfiable',
217
+                                417 => 'Expectation Failed',
218
+                                418 => 'I\'m a teapot',
219 219
 
220
-								500 => 'Internal Server Error',
221
-								501 => 'Not Implemented',
222
-								502 => 'Bad Gateway',
223
-								503 => 'Service Unavailable',
224
-								504 => 'Gateway Timeout',
225
-								505 => 'HTTP Version Not Supported',
226
-							);
227
-			if (isset($http_status[$code])){
228
-				$text = $http_status[$code];
229
-			}
230
-			else{
231
-				show_error('No HTTP status text found for your code please check it.');
232
-			}
233
-		}
220
+                                500 => 'Internal Server Error',
221
+                                501 => 'Not Implemented',
222
+                                502 => 'Bad Gateway',
223
+                                503 => 'Service Unavailable',
224
+                                504 => 'Gateway Timeout',
225
+                                505 => 'HTTP Version Not Supported',
226
+                            );
227
+            if (isset($http_status[$code])){
228
+                $text = $http_status[$code];
229
+            }
230
+            else{
231
+                show_error('No HTTP status text found for your code please check it.');
232
+            }
233
+        }
234 234
 		
235
-		if (strpos(php_sapi_name(), 'cgi') === 0){
236
-			header('Status: ' . $code . ' ' . $text, TRUE);
237
-		}
238
-		else{
239
-			$proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240
-			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241
-		}
242
-	}
235
+        if (strpos(php_sapi_name(), 'cgi') === 0){
236
+            header('Status: ' . $code . ' ' . $text, TRUE);
237
+        }
238
+        else{
239
+            $proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240
+            header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241
+        }
242
+    }
243 243
 
244
-	/**
245
-	 *  This function displays an error message to the user and ends the execution of the script.
246
-	 *  
247
-	 *  @param string $msg the message to display
248
-	 *  @param string $title the message title: "error", "info", "warning", etc.
249
-	 *  @param boolean $logging either to save error in log
250
-	 *  
251
-	 *  @codeCoverageIgnore
252
-	 */
253
-	function show_error($msg, $title = 'error', $logging = true){
254
-		$title = strtoupper($title);
255
-		$data = array();
256
-		$data['error'] = $msg;
257
-		$data['title'] = $title;
258
-		if ($logging){
259
-			save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
260
-		}
261
-		$response = & class_loader('Response', 'classes');
262
-		$response->sendError($data);
263
-		die();
264
-	}
244
+    /**
245
+     *  This function displays an error message to the user and ends the execution of the script.
246
+     *  
247
+     *  @param string $msg the message to display
248
+     *  @param string $title the message title: "error", "info", "warning", etc.
249
+     *  @param boolean $logging either to save error in log
250
+     *  
251
+     *  @codeCoverageIgnore
252
+     */
253
+    function show_error($msg, $title = 'error', $logging = true){
254
+        $title = strtoupper($title);
255
+        $data = array();
256
+        $data['error'] = $msg;
257
+        $data['title'] = $title;
258
+        if ($logging){
259
+            save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
260
+        }
261
+        $response = & class_loader('Response', 'classes');
262
+        $response->sendError($data);
263
+        die();
264
+    }
265 265
 
266
-	/**
267
-	 *  Check whether the protocol used is "https" or not
268
-	 *  That is, the web server is configured to use a secure connection.
269
-	 *  @codeCoverageIgnore
270
-	 *  
271
-	 *  @return boolean true if the web server uses the https protocol, false if not.
272
-	 */
273
-	function is_https(){
274
-		/*
266
+    /**
267
+     *  Check whether the protocol used is "https" or not
268
+     *  That is, the web server is configured to use a secure connection.
269
+     *  @codeCoverageIgnore
270
+     *  
271
+     *  @return boolean true if the web server uses the https protocol, false if not.
272
+     */
273
+    function is_https(){
274
+        /*
275 275
 		* some servers pass the "HTTPS" parameter in the server variable,
276 276
 		* if is the case, check if the value is "on", "true", "1".
277 277
 		*/
278
-		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
279
-			return true;
280
-		}
281
-		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
282
-			return true;
283
-		}
284
-		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
285
-			return true;
286
-		}
287
-		return false;
288
-	}
278
+        if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
279
+            return true;
280
+        }
281
+        else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
282
+            return true;
283
+        }
284
+        else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
285
+            return true;
286
+        }
287
+        return false;
288
+    }
289 289
 	
290
-	/**
291
-	 *  This function is used to check the URL format of the given string argument. 
292
-	 *  The address is valid if the protocol is http, https, ftp, etc.
293
-	 *
294
-	 *  @param string $url the URL address to check
295
-	 *  @test
296
-	 *  
297
-	 *  @return boolean true if is a valid URL address or false.
298
-	 */
299
-	function is_url($url){
300
-		return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
301
-	}
290
+    /**
291
+     *  This function is used to check the URL format of the given string argument. 
292
+     *  The address is valid if the protocol is http, https, ftp, etc.
293
+     *
294
+     *  @param string $url the URL address to check
295
+     *  @test
296
+     *  
297
+     *  @return boolean true if is a valid URL address or false.
298
+     */
299
+    function is_url($url){
300
+        return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
301
+    }
302 302
 	
303
-	/**
304
-	 *  Function defined to load controller
305
-	 *  
306
-	 *  @param string $controllerClass the controller class name to be loaded
307
-	 *  @codeCoverageIgnore
308
-	 */
309
-	function autoload_controller($controllerClass){
310
-		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
311
-			require_once $path;
312
-		}
313
-	}
303
+    /**
304
+     *  Function defined to load controller
305
+     *  
306
+     *  @param string $controllerClass the controller class name to be loaded
307
+     *  @codeCoverageIgnore
308
+     */
309
+    function autoload_controller($controllerClass){
310
+        if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
311
+            require_once $path;
312
+        }
313
+    }
314 314
 	
315
-	/**
316
-	 *  Function defined for handling PHP exception error message, 
317
-	 *  it displays an error message using the function "show_error"
318
-	 *  
319
-	 *  @param object $ex instance of the "Exception" class or a derived class
320
-	 *  @codeCoverageIgnore
321
-	 *  
322
-	 *  @return boolean
323
-	 */
324
-	function php_exception_handler($ex){
325
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326
-			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327
-		}
328
-		else{
329
-			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330
-		}
331
-		return true;
332
-	}
315
+    /**
316
+     *  Function defined for handling PHP exception error message, 
317
+     *  it displays an error message using the function "show_error"
318
+     *  
319
+     *  @param object $ex instance of the "Exception" class or a derived class
320
+     *  @codeCoverageIgnore
321
+     *  
322
+     *  @return boolean
323
+     */
324
+    function php_exception_handler($ex){
325
+        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326
+            show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327
+        }
328
+        else{
329
+            save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330
+        }
331
+        return true;
332
+    }
333 333
 	
334
-	/**
335
-	 *  Function defined for PHP error message handling
336
-	 *  			
337
-	 *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
338
-	 *  @param string $errstr the error message
339
-	 *  @param string $errfile the file where the error occurred
340
-	 *  @param int $errline the line number where the error occurred
341
-	 *  @codeCoverageIgnore
342
-	 *  
343
-	 *  @return boolean	
344
-	 */
345
-	function php_error_handler($errno , $errstr, $errfile , $errline){
346
-		$isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
347
-		if ($isError){
348
-			set_http_status_header(500);
349
-		}
350
-		if (! (error_reporting() & $errno)) {
351
-			save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
352
-			return;
353
-		}
354
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
355
-			$errorType = 'error';
356
-			switch ($errno) {
357
-				case E_USER_ERROR:
358
-					$errorType = 'error';
359
-					break;
360
-				case E_USER_WARNING:
361
-					$errorType = 'warning';
362
-					break;
363
-				case E_USER_NOTICE:
364
-					$errorType = 'notice';
365
-					break;
366
-				default:
367
-					$errorType = 'error';
368
-					break;
369
-			}
370
-			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
371
-		}
372
-		if ($isError){
373
-			die();
374
-		}
375
-		return true;
376
-	}
334
+    /**
335
+     *  Function defined for PHP error message handling
336
+     *  			
337
+     *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
338
+     *  @param string $errstr the error message
339
+     *  @param string $errfile the file where the error occurred
340
+     *  @param int $errline the line number where the error occurred
341
+     *  @codeCoverageIgnore
342
+     *  
343
+     *  @return boolean	
344
+     */
345
+    function php_error_handler($errno , $errstr, $errfile , $errline){
346
+        $isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
347
+        if ($isError){
348
+            set_http_status_header(500);
349
+        }
350
+        if (! (error_reporting() & $errno)) {
351
+            save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
352
+            return;
353
+        }
354
+        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
355
+            $errorType = 'error';
356
+            switch ($errno) {
357
+                case E_USER_ERROR:
358
+                    $errorType = 'error';
359
+                    break;
360
+                case E_USER_WARNING:
361
+                    $errorType = 'warning';
362
+                    break;
363
+                case E_USER_NOTICE:
364
+                    $errorType = 'notice';
365
+                    break;
366
+                default:
367
+                    $errorType = 'error';
368
+                    break;
369
+            }
370
+            show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
371
+        }
372
+        if ($isError){
373
+            die();
374
+        }
375
+        return true;
376
+    }
377 377
 
378
-	/**
379
-	 * This function is used to run in shutdown situation of the script
380
-	 * @codeCoverageIgnore
381
-	 */
382
-	function php_shudown_handler(){
383
-		$lastError = error_get_last();
384
-		if (isset($lastError) &&
385
-			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
386
-			php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
387
-		}
388
-	}
378
+    /**
379
+     * This function is used to run in shutdown situation of the script
380
+     * @codeCoverageIgnore
381
+     */
382
+    function php_shudown_handler(){
383
+        $lastError = error_get_last();
384
+        if (isset($lastError) &&
385
+            ($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
386
+            php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
387
+        }
388
+    }
389 389
 
390 390
 
391
-	/**
392
-	 *  Convert array attributes to string
393
-	 *
394
-	 *  This function converts an associative array into HTML attributes.
395
-	 *  For example :
396
-	 *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
397
-	 *  name = "Foo" type = "text"
398
-	 *
399
-	 *  @param array $attributes associative array to convert to a string attribute.
400
-	 *   
401
-	 *  @return string string of the HTML attribute.
402
-	 */
403
-	function attributes_to_string(array $attributes){
404
-		$str = ' ';
405
-		//we check that the array passed as an argument is not empty.
406
-		if (! empty($attributes)){
407
-			foreach($attributes as $key => $value){
408
-				$key = trim(htmlspecialchars($key));
409
-				$value = trim(htmlspecialchars($value));
410
-				/*
391
+    /**
392
+     *  Convert array attributes to string
393
+     *
394
+     *  This function converts an associative array into HTML attributes.
395
+     *  For example :
396
+     *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
397
+     *  name = "Foo" type = "text"
398
+     *
399
+     *  @param array $attributes associative array to convert to a string attribute.
400
+     *   
401
+     *  @return string string of the HTML attribute.
402
+     */
403
+    function attributes_to_string(array $attributes){
404
+        $str = ' ';
405
+        //we check that the array passed as an argument is not empty.
406
+        if (! empty($attributes)){
407
+            foreach($attributes as $key => $value){
408
+                $key = trim(htmlspecialchars($key));
409
+                $value = trim(htmlspecialchars($value));
410
+                /*
411 411
 				* To predict the case where the string to convert contains the character "
412 412
 				* we check if this is the case we add a slash to solve this problem.
413 413
 				* For example:
414 414
 				* 	$attr = array('placeholder' => 'I am a "puple"')
415 415
 				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
416 416
 				 */
417
-				if ($value && strpos('"', $value) !== false){
418
-					$value = addslashes($value);
419
-				}
420
-				$str .= $key.' = "'.$value.'" ';
421
-			}
422
-		}
423
-		//remove the space after using rtrim()
424
-		return rtrim($str);
425
-	}
417
+                if ($value && strpos('"', $value) !== false){
418
+                    $value = addslashes($value);
419
+                }
420
+                $str .= $key.' = "'.$value.'" ';
421
+            }
422
+        }
423
+        //remove the space after using rtrim()
424
+        return rtrim($str);
425
+    }
426 426
 
427 427
 
428
-	/**
429
-	* Function to stringfy PHP variable, useful in debug situation
430
-	*
431
-	* @param mixed $var the variable to stringfy
432
-	* @codeCoverageIgnore
433
-	*
434
-	* @return string the stringfy value
435
-	*/
436
-	function stringfy_vars($var){
437
-		return print_r($var, true);
438
-	}
428
+    /**
429
+     * Function to stringfy PHP variable, useful in debug situation
430
+     *
431
+     * @param mixed $var the variable to stringfy
432
+     * @codeCoverageIgnore
433
+     *
434
+     * @return string the stringfy value
435
+     */
436
+    function stringfy_vars($var){
437
+        return print_r($var, true);
438
+    }
439 439
 
440
-	/**
441
-	 * Clean the user input
442
-	 * @param  mixed $str the value to clean
443
-	 * @test
444
-	 * 
445
-	 * @return mixed   the sanitize value
446
-	 */
447
-	function clean_input($str){
448
-		if (is_array($str)){
449
-			$str = array_map('clean_input', $str);
450
-		}
451
-		else if (is_object($str)){
452
-			$obj = $str;
453
-			foreach ($str as $var => $value) {
454
-				$obj->$var = clean_input($value);
455
-			}
456
-			$str = $obj;
457
-		}
458
-		else{
459
-			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460
-		}
461
-		return $str;
462
-	}
440
+    /**
441
+     * Clean the user input
442
+     * @param  mixed $str the value to clean
443
+     * @test
444
+     * 
445
+     * @return mixed   the sanitize value
446
+     */
447
+    function clean_input($str){
448
+        if (is_array($str)){
449
+            $str = array_map('clean_input', $str);
450
+        }
451
+        else if (is_object($str)){
452
+            $obj = $str;
453
+            foreach ($str as $var => $value) {
454
+                $obj->$var = clean_input($value);
455
+            }
456
+            $str = $obj;
457
+        }
458
+        else{
459
+            $str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460
+        }
461
+        return $str;
462
+    }
463 463
 	
464
-	/**
465
-	 * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
466
-	 * Information like credit card number, password, etc.
467
-	 *
468
-	 * @param  string $str the string you want to hide some part
469
-	 * @param  int $startCount the length of non hidden for the beginning char
470
-	 * @param  int $endCount the length of non hidden for the ending char
471
-	 * @param  string $hiddenChar the char used to hide the given string
472
-	 * @test
473
-	 * 
474
-	 * @return string the string with the hidden part.
475
-	 */
476
-	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
477
-		//get the string length
478
-		$len = strlen($str);
479
-		//if str is empty
480
-		if ($len <= 0){
481
-			return str_repeat($hiddenChar, 6);
482
-		}
483
-		//if the length is less than startCount and endCount
484
-		//or the startCount and endCount length is 0
485
-		//or startCount is negative or endCount is negative
486
-		//return the full string hidden
464
+    /**
465
+     * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
466
+     * Information like credit card number, password, etc.
467
+     *
468
+     * @param  string $str the string you want to hide some part
469
+     * @param  int $startCount the length of non hidden for the beginning char
470
+     * @param  int $endCount the length of non hidden for the ending char
471
+     * @param  string $hiddenChar the char used to hide the given string
472
+     * @test
473
+     * 
474
+     * @return string the string with the hidden part.
475
+     */
476
+    function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
477
+        //get the string length
478
+        $len = strlen($str);
479
+        //if str is empty
480
+        if ($len <= 0){
481
+            return str_repeat($hiddenChar, 6);
482
+        }
483
+        //if the length is less than startCount and endCount
484
+        //or the startCount and endCount length is 0
485
+        //or startCount is negative or endCount is negative
486
+        //return the full string hidden
487 487
 		
488
-		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
489
-			return str_repeat($hiddenChar, $len);
490
-		}
491
-		//the start non hidden string
492
-		$startNonHiddenStr = substr($str, 0, $startCount);
493
-		//the end non hidden string
494
-		$endNonHiddenStr = null;
495
-		if ($endCount > 0){
496
-			$endNonHiddenStr = substr($str, - $endCount);
497
-		}
498
-		//the hidden string
499
-		$hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
488
+        if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
489
+            return str_repeat($hiddenChar, $len);
490
+        }
491
+        //the start non hidden string
492
+        $startNonHiddenStr = substr($str, 0, $startCount);
493
+        //the end non hidden string
494
+        $endNonHiddenStr = null;
495
+        if ($endCount > 0){
496
+            $endNonHiddenStr = substr($str, - $endCount);
497
+        }
498
+        //the hidden string
499
+        $hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
500 500
 		
501
-		return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
502
-	}
501
+        return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
502
+    }
503 503
 	
504
-	/**
505
-	 * This function is used to set the initial session config regarding the configuration
506
-	 * @codeCoverageIgnore
507
-	 */
508
-	function set_session_config(){
509
-		//$_SESSION is not available on cli mode 
510
-		if (! IS_CLI){
511
-			$logger =& class_loader('Log', 'classes');
512
-			$logger->setLogger('PHPSession');
513
-			//set session params
514
-			$sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
515
-			$sessionName = get_config('session_name');
516
-			if ($sessionName){
517
-				session_name($sessionName);
518
-			}
519
-			$logger->info('Session handler: ' . $sessionHandler);
520
-			$logger->info('Session name: ' . $sessionName);
504
+    /**
505
+     * This function is used to set the initial session config regarding the configuration
506
+     * @codeCoverageIgnore
507
+     */
508
+    function set_session_config(){
509
+        //$_SESSION is not available on cli mode 
510
+        if (! IS_CLI){
511
+            $logger =& class_loader('Log', 'classes');
512
+            $logger->setLogger('PHPSession');
513
+            //set session params
514
+            $sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
515
+            $sessionName = get_config('session_name');
516
+            if ($sessionName){
517
+                session_name($sessionName);
518
+            }
519
+            $logger->info('Session handler: ' . $sessionHandler);
520
+            $logger->info('Session name: ' . $sessionName);
521 521
 
522
-			if ($sessionHandler == 'files'){
523
-				$sessionSavePath = get_config('session_save_path');
524
-				if ($sessionSavePath){
525
-					if (! is_dir($sessionSavePath)){
526
-						mkdir($sessionSavePath, 1773);
527
-					}
528
-					session_save_path($sessionSavePath);
529
-					$logger->info('Session save path: ' . $sessionSavePath);
530
-				}
531
-			}
532
-			else if ($sessionHandler == 'database'){
533
-				//load database session handle library
534
-				//Database Session handler Model
535
-				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
522
+            if ($sessionHandler == 'files'){
523
+                $sessionSavePath = get_config('session_save_path');
524
+                if ($sessionSavePath){
525
+                    if (! is_dir($sessionSavePath)){
526
+                        mkdir($sessionSavePath, 1773);
527
+                    }
528
+                    session_save_path($sessionSavePath);
529
+                    $logger->info('Session save path: ' . $sessionSavePath);
530
+                }
531
+            }
532
+            else if ($sessionHandler == 'database'){
533
+                //load database session handle library
534
+                //Database Session handler Model
535
+                require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
536 536
 
537
-				$DBS =& class_loader('DBSessionHandler', 'classes');
538
-				session_set_save_handler($DBS, true);
539
-				$logger->info('session save path: ' . get_config('session_save_path'));
540
-			}
541
-			else{
542
-				show_error('Invalid session handler configuration');
543
-			}
544
-			$lifetime = get_config('session_cookie_lifetime', 0);
545
-			$path = get_config('session_cookie_path', '/');
546
-			$domain = get_config('session_cookie_domain', '');
547
-			$secure = get_config('session_cookie_secure', false);
548
-			session_set_cookie_params(
549
-				$lifetime,
550
-				$path,
551
-				$domain,
552
-				$secure,
553
-				$httponly = true /*for security for access to cookie via javascript or XSS attack*/
554
-			);
555
-			//to prevent attack of Session Fixation 
556
-			//thank to https://www.phparch.com/2018/01/php-sessions-in-depth/
557
-			ini_set('session.use_strict_mode ', 1);
558
-			ini_set('session.use_only_cookies', 1);
559
-			ini_set('session.use_trans_sid ', 0);
537
+                $DBS =& class_loader('DBSessionHandler', 'classes');
538
+                session_set_save_handler($DBS, true);
539
+                $logger->info('session save path: ' . get_config('session_save_path'));
540
+            }
541
+            else{
542
+                show_error('Invalid session handler configuration');
543
+            }
544
+            $lifetime = get_config('session_cookie_lifetime', 0);
545
+            $path = get_config('session_cookie_path', '/');
546
+            $domain = get_config('session_cookie_domain', '');
547
+            $secure = get_config('session_cookie_secure', false);
548
+            session_set_cookie_params(
549
+                $lifetime,
550
+                $path,
551
+                $domain,
552
+                $secure,
553
+                $httponly = true /*for security for access to cookie via javascript or XSS attack*/
554
+            );
555
+            //to prevent attack of Session Fixation 
556
+            //thank to https://www.phparch.com/2018/01/php-sessions-in-depth/
557
+            ini_set('session.use_strict_mode ', 1);
558
+            ini_set('session.use_only_cookies', 1);
559
+            ini_set('session.use_trans_sid ', 0);
560 560
 			
561
-			$logger->info('Session lifetime: ' . $lifetime);
562
-			$logger->info('Session cookie path: ' . $path);
563
-			$logger->info('Session domain: ' . $domain);
564
-			$logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
561
+            $logger->info('Session lifetime: ' . $lifetime);
562
+            $logger->info('Session cookie path: ' . $path);
563
+            $logger->info('Session domain: ' . $domain);
564
+            $logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
565 565
 			
566
-			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
567
-				$logger->info('Session not yet start, start it now');
568
-				session_start();
569
-			}
570
-		}
571
-	}
566
+            if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
567
+                $logger->info('Session not yet start, start it now');
568
+                session_start();
569
+            }
570
+        }
571
+    }
572 572
 	
573
-	/**
574
-	* This function is very useful, it allows to recover the instance of the global controller.
575
-	* Note this function always returns the address of the super instance.
576
-	* For example :
577
-	* $obj = & get_instance();
578
-	* 
579
-	* @codeCoverageIgnore
580
-	*  
581
-	* @return object the instance of the "Controller" class
582
-	*/
583
-	function & get_instance(){
584
-		return Controller::get_instance();
585
-	}
573
+    /**
574
+     * This function is very useful, it allows to recover the instance of the global controller.
575
+     * Note this function always returns the address of the super instance.
576
+     * For example :
577
+     * $obj = & get_instance();
578
+     * 
579
+     * @codeCoverageIgnore
580
+     *  
581
+     * @return object the instance of the "Controller" class
582
+     */
583
+    function & get_instance(){
584
+        return Controller::get_instance();
585
+    }
Please login to merge, or discard this patch.
core/classes/model/Model.php 3 patches
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
      * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34 34
      */
35 35
 
36
-    class Model{
36
+    class Model {
37 37
 
38 38
         /* --------------------------------------------------------------
39 39
          * VARIABLES
@@ -140,13 +140,13 @@  discard block
 block discarded – undo
140 140
          * Initialise the model, tie into the CodeIgniter superobject and
141 141
          * try our best to guess the table name.
142 142
          */
143
-        public function __construct(Database $db = null){
144
-            if (is_object($db)){
143
+        public function __construct(Database $db = null) {
144
+            if (is_object($db)) {
145 145
                 $this->setDatabaseInstance($db);
146 146
             }
147
-            else{
147
+            else {
148 148
                 $obj = & get_instance();
149
-        		if (isset($obj->database) && is_object($obj->database)){
149
+        		if (isset($obj->database) && is_object($obj->database)) {
150 150
                     /**
151 151
                     * NOTE: Need use "clone" because some Model need have the personal instance of the database library
152 152
                     * to prevent duplication
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 
183 183
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
184 184
             {
185
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
185
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
186 186
             }
187 187
     		$this->_set_where($where);
188 188
 
@@ -224,9 +224,9 @@  discard block
 block discarded – undo
224 224
             $this->trigger('before_get');
225 225
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
226 226
             {
227
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
227
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
228 228
             }
229
-			$type = $this->_temporary_return_type == 'array' ? 'array':false;
229
+			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
230 230
             $this->getQueryBuilder()->from($this->_table);
231 231
 			$result = $this->_database->getAll($type);
232 232
             $this->_temporary_return_type = $this->return_type;
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
                 $insert_id = $this->_database->insertId();
260 260
                 $this->trigger('after_create', $insert_id);
261 261
 				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
262
-				return ! $insert_id ? true : $insert_id;
262
+				return !$insert_id ? true : $insert_id;
263 263
             }
264 264
             else
265 265
             {
@@ -336,13 +336,13 @@  discard block
 block discarded – undo
336 336
         {
337 337
             $args = func_get_args();
338 338
             $data = array();
339
-            if (count($args) == 2){
340
-                if (is_array($args[1])){
339
+            if (count($args) == 2) {
340
+                if (is_array($args[1])) {
341 341
                     $data = array_pop($args);
342 342
                 }
343 343
             }
344
-            else if (count($args) == 3){
345
-                if (is_array($args[2])){
344
+            else if (count($args) == 3) {
345
+                if (is_array($args[2])) {
346 346
                     $data = array_pop($args);
347 347
                 }
348 348
             }
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
             if ($this->soft_delete)
385 385
             {
386 386
                 $this->getQueryBuilder()->from($this->_table);	
387
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
387
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
388 388
             }
389 389
             else
390 390
             {
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
             if ($this->soft_delete)
409 409
             {
410 410
                 $this->getQueryBuilder()->from($this->_table);	
411
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
411
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
412 412
             }
413 413
             else
414 414
             {
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
             if ($this->soft_delete)
431 431
             {
432 432
                 $this->getQueryBuilder()->from($this->_table);	
433
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
433
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
434 434
             }
435 435
             else
436 436
             {
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
                 $key = $this->primary_key;
501 501
                 $value = $args[0];
502 502
             }
503
-            $this->trigger('before_dropdown', array( $key, $value ));
503
+            $this->trigger('before_dropdown', array($key, $value));
504 504
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
505 505
             {
506 506
                 $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
         {
526 526
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
527 527
             {
528
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
528
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
529 529
             }
530 530
             $where = func_get_args();
531 531
             $this->_set_where($where);
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
         {
542 542
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
543 543
             {
544
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
544
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
545 545
             }
546 546
 			$this->getQueryBuilder()->from($this->_table);
547 547
 			$this->_database->getAll();
@@ -551,8 +551,8 @@  discard block
 block discarded – undo
551 551
 		/**
552 552
 		* Enabled cache temporary
553 553
 		*/
554
-		public function cached($ttl = 0){
555
-		  if ($ttl > 0){
554
+		public function cached($ttl = 0) {
555
+		  if ($ttl > 0) {
556 556
 			$this->_database = $this->_database->cached($ttl);
557 557
 		  }
558 558
 		  return $this;
@@ -706,13 +706,13 @@  discard block
 block discarded – undo
706 706
             {
707 707
                 if (is_object($row))
708 708
                 {
709
-					if (isset($row->$attr)){
709
+					if (isset($row->$attr)) {
710 710
 						unset($row->$attr);
711 711
 					}
712 712
                 }
713 713
                 else
714 714
                 {
715
-					if (isset($row[$attr])){
715
+					if (isset($row[$attr])) {
716 716
 						unset($row[$attr]);
717 717
 					}
718 718
                 }
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
          * Return the database instance
725 725
          * @return Database the database instance
726 726
          */
727
-        public function getDatabaseInstance(){
727
+        public function getDatabaseInstance() {
728 728
             return $this->_database;
729 729
         }
730 730
 
@@ -732,9 +732,9 @@  discard block
 block discarded – undo
732 732
          * set the Database instance for future use
733 733
          * @param Database $db the database object
734 734
          */
735
-         public function setDatabaseInstance($db){
735
+         public function setDatabaseInstance($db) {
736 736
             $this->_database = $db;
737
-            if ($this->dbCacheTime > 0){
737
+            if ($this->dbCacheTime > 0) {
738 738
                 $this->_database->setCache($this->dbCacheTime);
739 739
             }
740 740
             return $this;
@@ -744,7 +744,7 @@  discard block
 block discarded – undo
744 744
          * Return the loader instance
745 745
          * @return Loader the loader instance
746 746
          */
747
-        public function getLoader(){
747
+        public function getLoader() {
748 748
             return $this->loaderInstance;
749 749
         }
750 750
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
          * @param Loader $loader the loader object
754 754
 		 * @return object
755 755
          */
756
-         public function setLoader($loader){
756
+         public function setLoader($loader) {
757 757
             $this->loaderInstance = $loader;
758 758
             return $this;
759 759
         }
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
          * Return the queryBuilder instance this is the shortcut to database queryBuilder
763 763
          * @return object the DatabaseQueryBuilder instance
764 764
          */
765
-        public function getQueryBuilder(){
765
+        public function getQueryBuilder() {
766 766
             return $this->_database->getQueryBuilder();
767 767
         }
768 768
 
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
          * @param object $queryBuilder the DatabaseQueryBuilder object
772 772
 		 * @return object
773 773
          */
774
-         public function setQueryBuilder($queryBuilder){
774
+         public function setQueryBuilder($queryBuilder) {
775 775
             $this->_database->setQueryBuilder($queryBuilder);
776 776
             return $this;
777 777
         }
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
          * Return the FormValidation instance
782 782
          * @return FormValidation the form validation instance
783 783
          */
784
-        public function getFormValidation(){
784
+        public function getFormValidation() {
785 785
             return $this->formValidationInstance;
786 786
         }
787 787
 
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
          * @param FormValidation $fv the form validation object
791 791
 		 * @return object
792 792
          */
793
-         public function setFormValidation($fv){
793
+         public function setFormValidation($fv) {
794 794
             $this->formValidationInstance = $fv;
795 795
             return $this;
796 796
         }
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
          */
805 805
         public function order_by($criteria, $order = 'ASC')
806 806
         {
807
-            if ( is_array($criteria) )
807
+            if (is_array($criteria))
808 808
             {
809 809
                 foreach ($criteria as $key => $value)
810 810
                 {
@@ -835,13 +835,13 @@  discard block
 block discarded – undo
835 835
 		* relate for the relation "belongs_to"
836 836
 		* @return mixed
837 837
 		*/
838
-		protected function relateBelongsTo($row){
838
+		protected function relateBelongsTo($row) {
839 839
 			foreach ($this->belongs_to as $key => $value)
840 840
             {
841 841
                 if (is_string($value))
842 842
                 {
843 843
                     $relationship = $value;
844
-                    $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
844
+                    $options = array('primary_key' => $value . '_id', 'model' => $value . '_model');
845 845
                 }
846 846
                 else
847 847
                 {
@@ -851,10 +851,10 @@  discard block
 block discarded – undo
851 851
 
852 852
                 if (in_array($relationship, $this->_with))
853 853
                 {
854
-                    if (is_object($this->loaderInstance)){
854
+                    if (is_object($this->loaderInstance)) {
855 855
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
856 856
                     }
857
-                    else{
857
+                    else {
858 858
                         Loader::model($options['model'], $relationship . '_model');    
859 859
                     }
860 860
                     if (is_object($row))
@@ -874,13 +874,13 @@  discard block
 block discarded – undo
874 874
 		* relate for the relation "has_many"
875 875
 		* @return mixed
876 876
 		*/
877
-		protected function relateHasMany($row){
877
+		protected function relateHasMany($row) {
878 878
 			foreach ($this->has_many as $key => $value)
879 879
             {
880 880
                 if (is_string($value))
881 881
                 {
882 882
                     $relationship = $value;
883
-                    $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
883
+                    $options = array('primary_key' => $this->_table . '_id', 'model' => $value . '_model');
884 884
                 }
885 885
                 else
886 886
                 {
@@ -890,10 +890,10 @@  discard block
 block discarded – undo
890 890
 
891 891
                 if (in_array($relationship, $this->_with))
892 892
                 {
893
-                    if (is_object($this->loaderInstance)){
893
+                    if (is_object($this->loaderInstance)) {
894 894
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
895 895
                     }
896
-                    else{
896
+                    else {
897 897
                         Loader::model($options['model'], $relationship . '_model');    
898 898
                     }
899 899
                     if (is_object($row))
@@ -944,10 +944,10 @@  discard block
 block discarded – undo
944 944
             if (!empty($this->validate))
945 945
             {
946 946
                 $fv = null;
947
-                if (is_object($this->formValidationInstance)){
947
+                if (is_object($this->formValidationInstance)) {
948 948
                     $fv = $this->formValidationInstance;
949 949
                 }
950
-                else{
950
+                else {
951 951
                     Loader::library('FormValidation');
952 952
                     $fv = $this->formvalidation;
953 953
                     $this->setFormValidation($fv);
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
 		* Set WHERE parameters, when is array
977 977
 		* @param array $params
978 978
 		*/
979
-		protected function _set_where_array(array $params){
979
+		protected function _set_where_array(array $params) {
980 980
 			foreach ($params as $field => $filter)
981 981
 			{
982 982
 				if (is_array($filter))
@@ -1042,7 +1042,7 @@  discard block
 block discarded – undo
1042 1042
         /**
1043 1043
             Shortcut to controller
1044 1044
         */
1045
-        public function __get($key){
1045
+        public function __get($key) {
1046 1046
             return get_instance()->{$key};
1047 1047
         }
1048 1048
 
Please login to merge, or discard this patch.
Braces   +32 added lines, -64 removed lines patch added patch discarded remove patch
@@ -143,8 +143,7 @@  discard block
 block discarded – undo
143 143
         public function __construct(Database $db = null){
144 144
             if (is_object($db)){
145 145
                 $this->setDatabaseInstance($db);
146
-            }
147
-            else{
146
+            } else{
148 147
                 $obj = & get_instance();
149 148
         		if (isset($obj->database) && is_object($obj->database)){
150 149
                     /**
@@ -260,8 +259,7 @@  discard block
 block discarded – undo
260 259
                 $this->trigger('after_create', $insert_id);
261 260
 				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
262 261
 				return ! $insert_id ? true : $insert_id;
263
-            }
264
-            else
262
+            } else
265 263
             {
266 264
                 return FALSE;
267 265
             }
@@ -298,8 +296,7 @@  discard block
 block discarded – undo
298 296
                 $result = $this->_database->update($data, $escape);
299 297
                 $this->trigger('after_update', array($data, $result));
300 298
                 return $result;
301
-            }
302
-            else
299
+            } else
303 300
             {
304 301
                 return FALSE;
305 302
             }
@@ -322,8 +319,7 @@  discard block
 block discarded – undo
322 319
 				$result = $this->_database->update($data, $escape);
323 320
                 $this->trigger('after_update', array($data, $result));
324 321
                 return $result;
325
-            }
326
-            else
322
+            } else
327 323
             {
328 324
                 return FALSE;
329 325
             }
@@ -340,8 +336,7 @@  discard block
 block discarded – undo
340 336
                 if (is_array($args[1])){
341 337
                     $data = array_pop($args);
342 338
                 }
343
-            }
344
-            else if (count($args) == 3){
339
+            } else if (count($args) == 3){
345 340
                 if (is_array($args[2])){
346 341
                     $data = array_pop($args);
347 342
                 }
@@ -354,8 +349,7 @@  discard block
 block discarded – undo
354 349
 				$result = $this->_database->update($data);
355 350
                 $this->trigger('after_update', array($data, $result));
356 351
                 return $result;
357
-            }
358
-            else
352
+            } else
359 353
             {
360 354
                 return FALSE;
361 355
             }
@@ -385,8 +379,7 @@  discard block
 block discarded – undo
385 379
             {
386 380
                 $this->getQueryBuilder()->from($this->_table);	
387 381
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
388
-            }
389
-            else
382
+            } else
390 383
             {
391 384
                 $this->getQueryBuilder()->from($this->_table); 
392 385
 				$result = $this->_database->delete();
@@ -409,8 +402,7 @@  discard block
 block discarded – undo
409 402
             {
410 403
                 $this->getQueryBuilder()->from($this->_table);	
411 404
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
412
-            }
413
-            else
405
+            } else
414 406
             {
415 407
                 $this->getQueryBuilder()->from($this->_table); 
416 408
 				$result = $this->_database->delete();
@@ -431,8 +423,7 @@  discard block
 block discarded – undo
431 423
             {
432 424
                 $this->getQueryBuilder()->from($this->_table);	
433 425
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
434
-            }
435
-            else
426
+            } else
436 427
             {
437 428
                 $this->getQueryBuilder()->from($this->_table); 
438 429
 				$result = $this->_database->delete();
@@ -494,8 +485,7 @@  discard block
 block discarded – undo
494 485
             if (count($args) == 2)
495 486
             {
496 487
                 list($key, $value) = $args;
497
-            }
498
-            else
488
+            } else
499 489
             {
500 490
                 $key = $this->primary_key;
501 491
                 $value = $args[0];
@@ -647,8 +637,7 @@  discard block
 block discarded – undo
647 637
             if (is_object($row))
648 638
             {
649 639
                 $row->created_at = date('Y-m-d H:i:s');
650
-            }
651
-            else
640
+            } else
652 641
             {
653 642
                 $row['created_at'] = date('Y-m-d H:i:s');
654 643
             }
@@ -660,8 +649,7 @@  discard block
 block discarded – undo
660 649
             if (is_object($row))
661 650
             {
662 651
                 $row->updated_at = date('Y-m-d H:i:s');
663
-            }
664
-            else
652
+            } else
665 653
             {
666 654
                 $row['updated_at'] = date('Y-m-d H:i:s');
667 655
             }
@@ -688,8 +676,7 @@  discard block
 block discarded – undo
688 676
                 if (is_array($row))
689 677
                 {
690 678
                     $row[$column] = unserialize($row[$column]);
691
-                }
692
-                else
679
+                } else
693 680
                 {
694 681
                     $row->$column = unserialize($row->$column);
695 682
                 }
@@ -709,8 +696,7 @@  discard block
 block discarded – undo
709 696
 					if (isset($row->$attr)){
710 697
 						unset($row->$attr);
711 698
 					}
712
-                }
713
-                else
699
+                } else
714 700
                 {
715 701
 					if (isset($row[$attr])){
716 702
 						unset($row[$attr]);
@@ -810,8 +796,7 @@  discard block
 block discarded – undo
810 796
                 {
811 797
                     $this->getQueryBuilder()->orderBy($key, $value);
812 798
                 }
813
-            }
814
-            else
799
+            } else
815 800
             {
816 801
                 $this->getQueryBuilder()->orderBy($criteria, $order);
817 802
             }
@@ -842,8 +827,7 @@  discard block
 block discarded – undo
842 827
                 {
843 828
                     $relationship = $value;
844 829
                     $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
845
-                }
846
-                else
830
+                } else
847 831
                 {
848 832
                     $relationship = $key;
849 833
                     $options = $value;
@@ -853,15 +837,13 @@  discard block
 block discarded – undo
853 837
                 {
854 838
                     if (is_object($this->loaderInstance)){
855 839
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
856
-                    }
857
-                    else{
840
+                    } else{
858 841
                         Loader::model($options['model'], $relationship . '_model');    
859 842
                     }
860 843
                     if (is_object($row))
861 844
                     {
862 845
                         $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
863
-                    }
864
-                    else
846
+                    } else
865 847
                     {
866 848
                         $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
867 849
                     }
@@ -881,8 +863,7 @@  discard block
 block discarded – undo
881 863
                 {
882 864
                     $relationship = $value;
883 865
                     $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
884
-                }
885
-                else
866
+                } else
886 867
                 {
887 868
                     $relationship = $key;
888 869
                     $options = $value;
@@ -892,15 +873,13 @@  discard block
 block discarded – undo
892 873
                 {
893 874
                     if (is_object($this->loaderInstance)){
894 875
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
895
-                    }
896
-                    else{
876
+                    } else{
897 877
                         Loader::model($options['model'], $relationship . '_model');    
898 878
                     }
899 879
                     if (is_object($row))
900 880
                     {
901 881
                         $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
902
-                    }
903
-                    else
882
+                    } else
904 883
                     {
905 884
                         $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
906 885
                     }
@@ -946,8 +925,7 @@  discard block
 block discarded – undo
946 925
                 $fv = null;
947 926
                 if (is_object($this->formValidationInstance)){
948 927
                     $fv = $this->formValidationInstance;
949
-                }
950
-                else{
928
+                } else{
951 929
                     Loader::library('FormValidation');
952 930
                     $fv = $this->formvalidation;
953 931
                     $this->setFormValidation($fv);
@@ -959,13 +937,11 @@  discard block
 block discarded – undo
959 937
                 if ($fv->run())
960 938
                 {
961 939
                     return $data;
962
-                }
963
-                else
940
+                } else
964 941
                 {
965 942
                     return FALSE;
966 943
                 }
967
-            }
968
-            else
944
+            } else
969 945
             {
970 946
                 return $data;
971 947
             }
@@ -982,14 +958,12 @@  discard block
 block discarded – undo
982 958
 				if (is_array($filter))
983 959
 				{
984 960
 					$this->getQueryBuilder()->in($field, $filter);
985
-				}
986
-				else
961
+				} else
987 962
 				{
988 963
 					if (is_int($field))
989 964
 					{
990 965
 						$this->getQueryBuilder()->where($filter);
991
-					}
992
-					else
966
+					} else
993 967
 					{
994 968
 						$this->getQueryBuilder()->where($field, $filter);
995 969
 					}
@@ -1006,33 +980,27 @@  discard block
 block discarded – undo
1006 980
             if (count($params) == 1 && is_array($params[0]))
1007 981
             {
1008 982
                 $this->_set_where_array($params[0]);
1009
-            }
1010
-            else if (count($params) == 1)
983
+            } else if (count($params) == 1)
1011 984
             {
1012 985
                 $this->getQueryBuilder()->where($params[0]);
1013
-            }
1014
-        	else if (count($params) == 2)
986
+            } else if (count($params) == 2)
1015 987
     		{
1016 988
                 if (is_array($params[1]))
1017 989
                 {
1018 990
                     $this->getQueryBuilder()->in($params[0], $params[1]);
1019
-                }
1020
-                else
991
+                } else
1021 992
                 {
1022 993
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1023 994
                 }
1024
-    		}
1025
-    		else if (count($params) == 3)
995
+    		} else if (count($params) == 3)
1026 996
     		{
1027 997
     			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1028
-    		}
1029
-            else
998
+    		} else
1030 999
             {
1031 1000
                 if (is_array($params[1]))
1032 1001
                 {
1033 1002
                     $this->getQueryBuilder()->in($params[0], $params[1]);
1034
-                }
1035
-                else
1003
+                } else
1036 1004
                 {
1037 1005
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1038 1006
                 }
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  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 28
     /**
@@ -120,10 +120,10 @@  discard block
 block discarded – undo
120 120
         protected $_temporary_return_type = NULL;
121 121
     	
122 122
     	
123
-    	/**
123
+        /**
124 124
     		The database cache time 
125
-    	*/
126
-    	protected $dbCacheTime = 0;
125
+         */
126
+        protected $dbCacheTime = 0;
127 127
 
128 128
         /**
129 129
          * Instance of the Loader class
@@ -151,12 +151,12 @@  discard block
 block discarded – undo
151 151
             }
152 152
             else{
153 153
                 $obj = & get_instance();
154
-        		if (isset($obj->database) && is_object($obj->database)){
154
+                if (isset($obj->database) && is_object($obj->database)){
155 155
                     /**
156
-                    * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157
-                    * to prevent duplication
158
-                    */
159
-        			$this->setDatabaseInstance(clone $obj->database);
156
+                     * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157
+                     * to prevent duplication
158
+                     */
159
+                    $this->setDatabaseInstance(clone $obj->database);
160 160
                 }
161 161
             }
162 162
 
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
          */
175 175
         public function get($primary_value)
176 176
         {
177
-    		return $this->get_by($this->primary_key, $primary_value);
177
+            return $this->get_by($this->primary_key, $primary_value);
178 178
         }
179 179
 
180 180
         /**
@@ -189,12 +189,12 @@  discard block
 block discarded – undo
189 189
             {
190 190
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
191 191
             }
192
-    		$this->_set_where($where);
192
+            $this->_set_where($where);
193 193
 
194 194
             $this->trigger('before_get');
195
-			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
195
+            $type = $this->_temporary_return_type == 'array' ? 'array' : false;
196 196
             $this->getQueryBuilder()->from($this->_table);
197
-			$row = $this->_database->get($type);
197
+            $row = $this->_database->get($type);
198 198
             $this->_temporary_return_type = $this->return_type;
199 199
             $row = $this->trigger('after_get', $row);
200 200
             $this->_with = array();
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
             {
232 232
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
233 233
             }
234
-			$type = $this->_temporary_return_type == 'array' ? 'array':false;
234
+            $type = $this->_temporary_return_type == 'array' ? 'array':false;
235 235
             $this->getQueryBuilder()->from($this->_table);
236
-			$result = $this->_database->getAll($type);
236
+            $result = $this->_database->getAll($type);
237 237
             $this->_temporary_return_type = $this->return_type;
238 238
 
239 239
             foreach ($result as $key => &$row)
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
         /**
248 248
          * Insert a new row into the table. $data should be an associative array
249 249
          * of data to be inserted. Returns newly created ID.
250
-		 * @see Database::insert
250
+         * @see Database::insert
251 251
          */
252 252
         public function insert($data = array(), $skip_validation = FALSE, $escape = true)
253 253
         {
@@ -260,11 +260,11 @@  discard block
 block discarded – undo
260 260
             {
261 261
                 $data = $this->trigger('before_create', $data);
262 262
                 $this->getQueryBuilder()->from($this->_table);
263
-				$this->_database->insert($data, $escape);
263
+                $this->_database->insert($data, $escape);
264 264
                 $insert_id = $this->_database->insertId();
265 265
                 $this->trigger('after_create', $insert_id);
266
-				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
267
-				return ! $insert_id ? true : $insert_id;
266
+                //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
267
+                return ! $insert_id ? true : $insert_id;
268 268
             }
269 269
             else
270 270
             {
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
             {
325 325
                 $this->getQueryBuilder()->in($this->primary_key, $primary_values)
326 326
                                         ->from($this->_table);
327
-				$result = $this->_database->update($data, $escape);
327
+                $result = $this->_database->update($data, $escape);
328 328
                 $this->trigger('after_update', array($data, $result));
329 329
                 return $result;
330 330
             }
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
             {
357 357
                 $this->_set_where($args);
358 358
                 $this->getQueryBuilder()->from($this->_table);
359
-				$result = $this->_database->update($data);
359
+                $result = $this->_database->update($data);
360 360
                 $this->trigger('after_update', array($data, $result));
361 361
                 return $result;
362 362
             }
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
         {
374 374
             $data = $this->trigger('before_update', $data);
375 375
             $this->getQueryBuilder()->from($this->_table);
376
-			$result = $this->_database->update($data, $escape);
376
+            $result = $this->_database->update($data, $escape);
377 377
             $this->trigger('after_update', array($data, $result));
378 378
             return $result;
379 379
         }
@@ -385,16 +385,16 @@  discard block
 block discarded – undo
385 385
         {
386 386
             $this->trigger('before_delete', $id);
387 387
             $this->getQueryBuilder()->where($this->primary_key, $id);
388
-			$result = false;
388
+            $result = false;
389 389
             if ($this->soft_delete)
390 390
             {
391 391
                 $this->getQueryBuilder()->from($this->_table);	
392
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
392
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
393 393
             }
394 394
             else
395 395
             {
396 396
                 $this->getQueryBuilder()->from($this->_table); 
397
-				$result = $this->_database->delete();
397
+                $result = $this->_database->delete();
398 398
             }
399 399
 
400 400
             $this->trigger('after_delete', $result);
@@ -407,18 +407,18 @@  discard block
 block discarded – undo
407 407
         public function delete_by()
408 408
         {
409 409
             $where = func_get_args();
410
-    	    $where = $this->trigger('before_delete', $where);
410
+            $where = $this->trigger('before_delete', $where);
411 411
             $this->_set_where($where);
412
-			$result = false;
412
+            $result = false;
413 413
             if ($this->soft_delete)
414 414
             {
415 415
                 $this->getQueryBuilder()->from($this->_table);	
416
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
416
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
417 417
             }
418 418
             else
419 419
             {
420 420
                 $this->getQueryBuilder()->from($this->_table); 
421
-				$result = $this->_database->delete();
421
+                $result = $this->_database->delete();
422 422
             }
423 423
             $this->trigger('after_delete', $result);
424 424
             return $result;
@@ -431,16 +431,16 @@  discard block
 block discarded – undo
431 431
         {
432 432
             $primary_values = $this->trigger('before_delete', $primary_values);
433 433
             $this->getQueryBuilder()->in($this->primary_key, $primary_values);
434
-			$result = false;
434
+            $result = false;
435 435
             if ($this->soft_delete)
436 436
             {
437 437
                 $this->getQueryBuilder()->from($this->_table);	
438
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
438
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
439 439
             }
440 440
             else
441 441
             {
442 442
                 $this->getQueryBuilder()->from($this->_table); 
443
-				$result = $this->_database->delete();
443
+                $result = $this->_database->delete();
444 444
             }
445 445
             $this->trigger('after_delete', $result);
446 446
             return $result;
@@ -452,8 +452,8 @@  discard block
 block discarded – undo
452 452
          */
453 453
         public function truncate()
454 454
         {
455
-			$this->getQueryBuilder()->from($this->_table); 
456
-			$result = $this->_database->delete();
455
+            $this->getQueryBuilder()->from($this->_table); 
456
+            $result = $this->_database->delete();
457 457
             return $result;
458 458
         }
459 459
 
@@ -471,14 +471,14 @@  discard block
 block discarded – undo
471 471
             return $this;
472 472
         }
473 473
 		
474
-		/**
475
-		* Relationship
476
-		*/
474
+        /**
475
+         * Relationship
476
+         */
477 477
         public function relate($row)
478 478
         {
479
-    		if (empty($row))
479
+            if (empty($row))
480 480
             {
481
-    		    return $row;
481
+                return $row;
482 482
             }
483 483
 
484 484
             $row = $this->relateBelongsTo($row);
@@ -511,9 +511,9 @@  discard block
 block discarded – undo
511 511
                 $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
512 512
             }
513 513
             $this->getQueryBuilder()
514
-									 ->select(array($key, $value))
515
-									 ->from($this->_table);
516
-			$result = $this->_database->getAll();
514
+                                        ->select(array($key, $value))
515
+                                        ->from($this->_table);
516
+            $result = $this->_database->getAll();
517 517
             $options = array();
518 518
             foreach ($result as $row)
519 519
             {
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
             $where = func_get_args();
536 536
             $this->_set_where($where);
537 537
             $this->getQueryBuilder()->from($this->_table);
538
-			$this->_database->getAll();
538
+            $this->_database->getAll();
539 539
             return $this->_database->numRows();
540 540
         }
541 541
 
@@ -548,20 +548,20 @@  discard block
 block discarded – undo
548 548
             {
549 549
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
550 550
             }
551
-			$this->getQueryBuilder()->from($this->_table);
552
-			$this->_database->getAll();
551
+            $this->getQueryBuilder()->from($this->_table);
552
+            $this->_database->getAll();
553 553
             return $this->_database->numRows();
554 554
         }
555 555
 		
556
-		/**
557
-		* Enabled cache temporary
558
-		*/
559
-		public function cached($ttl = 0){
560
-		  if ($ttl > 0){
561
-			$this->_database = $this->_database->cached($ttl);
562
-		  }
563
-		  return $this;
564
-		}
556
+        /**
557
+         * Enabled cache temporary
558
+         */
559
+        public function cached($ttl = 0){
560
+            if ($ttl > 0){
561
+            $this->_database = $this->_database->cached($ttl);
562
+            }
563
+            return $this;
564
+        }
565 565
 
566 566
         /**
567 567
          * Tell the class to skip the insert validation
@@ -585,10 +585,10 @@  discard block
 block discarded – undo
585 585
          */
586 586
         public function get_next_id()
587 587
         {
588
-			$this->getQueryBuilder()->select('AUTO_INCREMENT')
589
-									->from('information_schema.TABLES')
590
-									->where('TABLE_NAME', $this->_table)
591
-									->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
588
+            $this->getQueryBuilder()->select('AUTO_INCREMENT')
589
+                                    ->from('information_schema.TABLES')
590
+                                    ->where('TABLE_NAME', $this->_table)
591
+                                    ->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
592 592
             return (int) $this->_database->get()->AUTO_INCREMENT;
593 593
         }
594 594
 
@@ -711,24 +711,24 @@  discard block
 block discarded – undo
711 711
             {
712 712
                 if (is_object($row))
713 713
                 {
714
-					if (isset($row->$attr)){
715
-						unset($row->$attr);
716
-					}
714
+                    if (isset($row->$attr)){
715
+                        unset($row->$attr);
716
+                    }
717 717
                 }
718 718
                 else
719 719
                 {
720
-					if (isset($row[$attr])){
721
-						unset($row[$attr]);
722
-					}
720
+                    if (isset($row[$attr])){
721
+                        unset($row[$attr]);
722
+                    }
723 723
                 }
724 724
             }
725 725
             return $row;
726 726
         }
727 727
 		
728
-		 /**
729
-         * Return the database instance
730
-         * @return Database the database instance
731
-         */
728
+            /**
729
+             * Return the database instance
730
+             * @return Database the database instance
731
+             */
732 732
         public function getDatabaseInstance(){
733 733
             return $this->_database;
734 734
         }
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
          * set the Database instance for future use
738 738
          * @param Database $db the database object
739 739
          */
740
-         public function setDatabaseInstance($db){
740
+            public function setDatabaseInstance($db){
741 741
             $this->_database = $db;
742 742
             if ($this->dbCacheTime > 0){
743 743
                 $this->_database->setCache($this->dbCacheTime);
@@ -756,14 +756,14 @@  discard block
 block discarded – undo
756 756
         /**
757 757
          * Set the loader instance for future use
758 758
          * @param Loader $loader the loader object
759
-		 * @return object
759
+         * @return object
760 760
          */
761
-         public function setLoader($loader){
761
+            public function setLoader($loader){
762 762
             $this->loaderInstance = $loader;
763 763
             return $this;
764 764
         }
765 765
 
766
-		/**
766
+        /**
767 767
          * Return the queryBuilder instance this is the shortcut to database queryBuilder
768 768
          * @return object the DatabaseQueryBuilder instance
769 769
          */
@@ -774,9 +774,9 @@  discard block
 block discarded – undo
774 774
         /**
775 775
          * Set the DatabaseQueryBuilder instance for future use
776 776
          * @param object $queryBuilder the DatabaseQueryBuilder object
777
-		 * @return object
777
+         * @return object
778 778
          */
779
-         public function setQueryBuilder($queryBuilder){
779
+            public function setQueryBuilder($queryBuilder){
780 780
             $this->_database->setQueryBuilder($queryBuilder);
781 781
             return $this;
782 782
         }
@@ -793,9 +793,9 @@  discard block
 block discarded – undo
793 793
         /**
794 794
          * Set the form validation instance for future use
795 795
          * @param FormValidation $fv the form validation object
796
-		 * @return object
796
+         * @return object
797 797
          */
798
-         public function setFormValidation($fv){
798
+            public function setFormValidation($fv){
799 799
             $this->formValidationInstance = $fv;
800 800
             return $this;
801 801
         }
@@ -836,12 +836,12 @@  discard block
 block discarded – undo
836 836
          * INTERNAL METHODS
837 837
          * ------------------------------------------------------------ */
838 838
 
839
-		/**
840
-		* relate for the relation "belongs_to"
841
-		* @return mixed
842
-		*/
843
-		protected function relateBelongsTo($row){
844
-			foreach ($this->belongs_to as $key => $value)
839
+        /**
840
+         * relate for the relation "belongs_to"
841
+         * @return mixed
842
+         */
843
+        protected function relateBelongsTo($row){
844
+            foreach ($this->belongs_to as $key => $value)
845 845
             {
846 846
                 if (is_string($value))
847 847
                 {
@@ -872,15 +872,15 @@  discard block
 block discarded – undo
872 872
                     }
873 873
                 }
874 874
             }
875
-			return $row;
876
-		}
877
-
878
-		/**
879
-		* relate for the relation "has_many"
880
-		* @return mixed
881
-		*/
882
-		protected function relateHasMany($row){
883
-			foreach ($this->has_many as $key => $value)
875
+            return $row;
876
+        }
877
+
878
+        /**
879
+         * relate for the relation "has_many"
880
+         * @return mixed
881
+         */
882
+        protected function relateHasMany($row){
883
+            foreach ($this->has_many as $key => $value)
884 884
             {
885 885
                 if (is_string($value))
886 886
                 {
@@ -911,8 +911,8 @@  discard block
 block discarded – undo
911 911
                     }
912 912
                 }
913 913
             }
914
-			return $row;
915
-		}
914
+            return $row;
915
+        }
916 916
 		
917 917
         /**
918 918
          * Trigger an event and call its observers. Pass through the event name
@@ -977,30 +977,30 @@  discard block
 block discarded – undo
977 977
         }
978 978
 		
979 979
 		
980
-		/**
981
-		* Set WHERE parameters, when is array
982
-		* @param array $params
983
-		*/
984
-		protected function _set_where_array(array $params){
985
-			foreach ($params as $field => $filter)
986
-			{
987
-				if (is_array($filter))
988
-				{
989
-					$this->getQueryBuilder()->in($field, $filter);
990
-				}
991
-				else
992
-				{
993
-					if (is_int($field))
994
-					{
995
-						$this->getQueryBuilder()->where($filter);
996
-					}
997
-					else
998
-					{
999
-						$this->getQueryBuilder()->where($field, $filter);
1000
-					}
1001
-				}
1002
-			}
1003
-		}
980
+        /**
981
+         * Set WHERE parameters, when is array
982
+         * @param array $params
983
+         */
984
+        protected function _set_where_array(array $params){
985
+            foreach ($params as $field => $filter)
986
+            {
987
+                if (is_array($filter))
988
+                {
989
+                    $this->getQueryBuilder()->in($field, $filter);
990
+                }
991
+                else
992
+                {
993
+                    if (is_int($field))
994
+                    {
995
+                        $this->getQueryBuilder()->where($filter);
996
+                    }
997
+                    else
998
+                    {
999
+                        $this->getQueryBuilder()->where($field, $filter);
1000
+                    }
1001
+                }
1002
+            }
1003
+        }
1004 1004
 
1005 1005
 
1006 1006
         /**
@@ -1016,8 +1016,8 @@  discard block
 block discarded – undo
1016 1016
             {
1017 1017
                 $this->getQueryBuilder()->where($params[0]);
1018 1018
             }
1019
-        	else if (count($params) == 2)
1020
-    		{
1019
+            else if (count($params) == 2)
1020
+            {
1021 1021
                 if (is_array($params[1]))
1022 1022
                 {
1023 1023
                     $this->getQueryBuilder()->in($params[0], $params[1]);
@@ -1026,11 +1026,11 @@  discard block
 block discarded – undo
1026 1026
                 {
1027 1027
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1028 1028
                 }
1029
-    		}
1030
-    		else if (count($params) == 3)
1031
-    		{
1032
-    			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1033
-    		}
1029
+            }
1030
+            else if (count($params) == 3)
1031
+            {
1032
+                $this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1033
+            }
1034 1034
             else
1035 1035
             {
1036 1036
                 if (is_array($params[1]))
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 
1047 1047
         /**
1048 1048
             Shortcut to controller
1049
-        */
1049
+         */
1050 1050
         public function __get($key){
1051 1051
             return get_instance()->{$key};
1052 1052
         }
Please login to merge, or discard this patch.
core/classes/Database.php 3 patches
Braces   +8 added lines, -16 removed lines patch added patch discarded remove patch
@@ -153,14 +153,12 @@  discard block
 block discarded – undo
153 153
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
154 154
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
155 155
             return true;
156
-          }
157
-          catch (PDOException $e){
156
+          } catch (PDOException $e){
158 157
             $this->logger->fatal($e->getMessage());
159 158
             show_error('Cannot connect to Database.');
160 159
             return false;
161 160
           }
162
-      }
163
-      else{
161
+      } else{
164 162
         show_error('Database configuration is not set.');
165 163
         return false;
166 164
       }
@@ -203,8 +201,7 @@  discard block
 block discarded – undo
203 201
       $query = $this->getAll(true);
204 202
       if ($returnSQLQueryOrResultType === true){
205 203
         return $query;
206
-      }
207
-      else{
204
+      } else{
208 205
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
209 206
       }
210 207
     }
@@ -628,15 +625,13 @@  discard block
 block discarded – undo
628 625
       //if need return all result like list of record
629 626
       if (is_bool($all) && $all){
630 627
           $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
631
-      }
632
-      else{
628
+      } else{
633 629
           $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
634 630
       }
635 631
       //Sqlite and pgsql always return 0 when using rowCount()
636 632
       if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
637 633
         $this->numRows = count($this->result);  
638
-      }
639
-      else{
634
+      } else{
640 635
         $this->numRows = $pdoStatment->rowCount(); 
641 636
       }
642 637
     }
@@ -650,8 +645,7 @@  discard block
 block discarded – undo
650 645
       if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
651 646
         $this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
652 647
         $this->numRows = 1; //TODO use the correct method to get the exact affected row
653
-      }
654
-      else{
648
+      } else{
655 649
           $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
656 650
           $this->numRows = $pdoStatment->rowCount(); 
657 651
       }
@@ -776,8 +770,7 @@  discard block
 block discarded – undo
776 770
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
777 771
       if ($logger !== null){
778 772
         $this->setLogger($logger);
779
-      }
780
-      else{
773
+      } else{
781 774
           $this->logger =& class_loader('Log', 'classes');
782 775
           $this->logger->setLogger('Library::Database');
783 776
       }
@@ -790,8 +783,7 @@  discard block
 block discarded – undo
790 783
 	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
791 784
 	  if ($queryBuilder !== null){
792 785
       $this->setQueryBuilder($queryBuilder);
793
-	  }
794
-	  else{
786
+	  } else{
795 787
 		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
796 788
 	  }
797 789
 	}
Please login to merge, or discard this patch.
Spacing   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -23,110 +23,110 @@  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 error returned for the last query
60 60
 	 * @var string
61 61
 	*/
62
-    private $error               = null;
62
+    private $error = null;
63 63
 	
64 64
 	/**
65 65
 	 * The result returned for the last query
66 66
 	 * @var mixed
67 67
 	*/
68
-    private $result              = array();
68
+    private $result = array();
69 69
 	
70 70
 	/**
71 71
 	 * The cache default time to live in second. 0 means no need to use the cache feature
72 72
 	 * @var int
73 73
 	*/
74
-	private $cacheTtl              = 0;
74
+	private $cacheTtl = 0;
75 75
 	
76 76
 	/**
77 77
 	 * The cache current time to live. 0 means no need to use the cache feature
78 78
 	 * @var int
79 79
 	*/
80
-    private $temporaryCacheTtl   = 0;
80
+    private $temporaryCacheTtl = 0;
81 81
 	
82 82
 	/**
83 83
 	 * The number of executed query for the current request
84 84
 	 * @var int
85 85
 	*/
86
-    private $queryCount          = 0;
86
+    private $queryCount = 0;
87 87
 	
88 88
 	/**
89 89
 	 * The default data to be used in the statments query INSERT, UPDATE
90 90
 	 * @var array
91 91
 	*/
92
-    private $data                = array();
92
+    private $data = array();
93 93
 	
94 94
 	/**
95 95
 	 * The database configuration
96 96
 	 * @var array
97 97
 	*/
98
-    private $config              = array();
98
+    private $config = array();
99 99
 	
100 100
 	/**
101 101
 	 * The logger instance
102 102
 	 * @var object
103 103
 	 */
104
-    private $logger              = null;
104
+    private $logger = null;
105 105
 
106 106
     /**
107 107
     * The cache instance
108 108
     * @var object
109 109
     */
110
-    private $cacheInstance       = null;
110
+    private $cacheInstance = null;
111 111
 
112 112
     /**
113 113
     * The benchmark instance
114 114
     * @var object
115 115
     */
116
-    private $benchmarkInstance   = null;
116
+    private $benchmarkInstance = null;
117 117
 	
118 118
 	/**
119 119
     * The DatabaseQueryBuilder instance
120 120
     * @var object
121 121
     */
122
-    private $queryBuilder        = null;
122
+    private $queryBuilder = null;
123 123
 
124 124
 
125 125
     /**
126 126
      * Construct new database
127 127
      * @param array $overwriteConfig the config to overwrite with the config set in database.php
128 128
      */
129
-    public function __construct($overwriteConfig = array()){
129
+    public function __construct($overwriteConfig = array()) {
130 130
         //Set Log instance to use
131 131
         $this->setLoggerFromParamOrCreateNewInstance(null);
132 132
 		
@@ -144,23 +144,23 @@  discard block
 block discarded – undo
144 144
      * This is used to connect to database
145 145
      * @return bool 
146 146
      */
147
-    public function connect(){
147
+    public function connect() {
148 148
       $config = $this->getDatabaseConfiguration();
149
-      if (! empty($config)){
150
-        try{
149
+      if (!empty($config)) {
150
+        try {
151 151
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
152 152
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
153 153
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
154 154
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
155 155
             return true;
156 156
           }
157
-          catch (PDOException $e){
157
+          catch (PDOException $e) {
158 158
             $this->logger->fatal($e->getMessage());
159 159
             show_error('Cannot connect to Database.');
160 160
             return false;
161 161
           }
162 162
       }
163
-      else{
163
+      else {
164 164
         show_error('Database configuration is not set.');
165 165
         return false;
166 166
       }
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      * Return the number of rows returned by the current query
172 172
      * @return int
173 173
      */
174
-    public function numRows(){
174
+    public function numRows() {
175 175
       return $this->numRows;
176 176
     }
177 177
 
@@ -179,15 +179,15 @@  discard block
 block discarded – undo
179 179
      * Return the last insert id value
180 180
      * @return mixed
181 181
      */
182
-    public function insertId(){
182
+    public function insertId() {
183 183
       return $this->insertId;
184 184
     }
185 185
 
186 186
     /**
187 187
      * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
188 188
      */
189
-    public function error(){
190
-  		if ($this->error){
189
+    public function error() {
190
+  		if ($this->error) {
191 191
   			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
192 192
   		}
193 193
     }
@@ -198,13 +198,13 @@  discard block
 block discarded – undo
198 198
      * If is string will determine the result type "array" or "object"
199 199
      * @return mixed       the query SQL string or the record result
200 200
      */
201
-    public function get($returnSQLQueryOrResultType = false){
201
+    public function get($returnSQLQueryOrResultType = false) {
202 202
       $this->getQueryBuilder()->limit(1);
203 203
       $query = $this->getAll(true);
204
-      if ($returnSQLQueryOrResultType === true){
204
+      if ($returnSQLQueryOrResultType === true) {
205 205
         return $query;
206 206
       }
207
-      else{
207
+      else {
208 208
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
209 209
       }
210 210
     }
@@ -215,9 +215,9 @@  discard block
 block discarded – undo
215 215
      * If is string will determine the result type "array" or "object"
216 216
      * @return mixed       the query SQL string or the record result
217 217
      */
218
-    public function getAll($returnSQLQueryOrResultType = false){
218
+    public function getAll($returnSQLQueryOrResultType = false) {
219 219
 	   $query = $this->getQueryBuilder()->getQuery();
220
-	   if ($returnSQLQueryOrResultType === true){
220
+	   if ($returnSQLQueryOrResultType === true) {
221 221
       	return $query;
222 222
       }
223 223
       return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
@@ -229,18 +229,18 @@  discard block
 block discarded – undo
229 229
      * @param  boolean $escape  whether to escape or not the values
230 230
      * @return mixed          the insert id of the new record or null
231 231
      */
232
-    public function insert($data = array(), $escape = true){
233
-      if (empty($data) && $this->getData()){
232
+    public function insert($data = array(), $escape = true) {
233
+      if (empty($data) && $this->getData()) {
234 234
         //as when using $this->setData() may be the data already escaped
235 235
         $escape = false;
236 236
         $data = $this->getData();
237 237
       }
238 238
       $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
239 239
       $result = $this->query($query);
240
-      if ($result){
240
+      if ($result) {
241 241
         $this->insertId = $this->pdo->lastInsertId();
242 242
 		//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
243
-        return ! $this->insertId() ? true : $this->insertId();
243
+        return !$this->insertId() ? true : $this->insertId();
244 244
       }
245 245
       return false;
246 246
     }
@@ -251,8 +251,8 @@  discard block
 block discarded – undo
251 251
      * @param  boolean $escape  whether to escape or not the values
252 252
      * @return mixed          the update status
253 253
      */
254
-    public function update($data = array(), $escape = true){
255
-      if (empty($data) && $this->getData()){
254
+    public function update($data = array(), $escape = true) {
255
+      if (empty($data) && $this->getData()) {
256 256
         //as when using $this->setData() may be the data already escaped
257 257
         $escape = false;
258 258
         $data = $this->getData();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
      * Delete the record in database
266 266
      * @return mixed the delete status
267 267
      */
268
-    public function delete(){
268
+    public function delete() {
269 269
 		$query = $this->getQueryBuilder()->delete()->getQuery();
270 270
     	return $this->query($query);
271 271
     }
@@ -275,8 +275,8 @@  discard block
 block discarded – undo
275 275
      * @param integer $ttl the cache time to live in second
276 276
      * @return object        the current Database instance
277 277
      */
278
-    public function setCache($ttl = 0){
279
-      if ($ttl > 0){
278
+    public function setCache($ttl = 0) {
279
+      if ($ttl > 0) {
280 280
         $this->cacheTtl = $ttl;
281 281
         $this->temporaryCacheTtl = $ttl;
282 282
       }
@@ -288,8 +288,8 @@  discard block
 block discarded – undo
288 288
 	 * @param  integer $ttl the cache time to live in second
289 289
 	 * @return object        the current Database instance
290 290
 	 */
291
-  	public function cached($ttl = 0){
292
-        if ($ttl > 0){
291
+  	public function cached($ttl = 0) {
292
+        if ($ttl > 0) {
293 293
           $this->temporaryCacheTtl = $ttl;
294 294
         }
295 295
         return $this;
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
      * @param boolean $escaped whether we can do escape of not 
302 302
      * @return mixed       the data after escaped or the same data if not
303 303
      */
304
-    public function escape($data, $escaped = true){
304
+    public function escape($data, $escaped = true) {
305 305
       return $escaped ? 
306 306
                       $this->getPdo()->quote(trim($data)) 
307 307
                       : $data; 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
      * Return the number query executed count for the current request
312 312
      * @return int
313 313
      */
314
-    public function queryCount(){
314
+    public function queryCount() {
315 315
       return $this->queryCount;
316 316
     }
317 317
 
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
      * Return the current query SQL string
320 320
      * @return string
321 321
      */
322
-    public function getQuery(){
322
+    public function getQuery() {
323 323
       return $this->query;
324 324
     }
325 325
 
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
      * Return the application database name
328 328
      * @return string
329 329
      */
330
-    public function getDatabaseName(){
330
+    public function getDatabaseName() {
331 331
       return $this->databaseName;
332 332
     }
333 333
 
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
      * Return the PDO instance
336 336
      * @return object
337 337
      */
338
-    public function getPdo(){
338
+    public function getPdo() {
339 339
       return $this->pdo;
340 340
     }
341 341
 
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
      * @param object $pdo the pdo object
345 345
 	 * @return object Database
346 346
      */
347
-    public function setPdo(PDO $pdo){
347
+    public function setPdo(PDO $pdo) {
348 348
       $this->pdo = $pdo;
349 349
       return $this;
350 350
     }
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
      * Return the Log instance
355 355
      * @return Log
356 356
      */
357
-    public function getLogger(){
357
+    public function getLogger() {
358 358
       return $this->logger;
359 359
     }
360 360
 
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
      * @param Log $logger the log object
364 364
 	 * @return object Database
365 365
      */
366
-    public function setLogger($logger){
366
+    public function setLogger($logger) {
367 367
       $this->logger = $logger;
368 368
       return $this;
369 369
     }
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
      * Return the cache instance
373 373
      * @return CacheInterface
374 374
      */
375
-    public function getCacheInstance(){
375
+    public function getCacheInstance() {
376 376
       return $this->cacheInstance;
377 377
     }
378 378
 
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
      * @param CacheInterface $cache the cache object
382 382
 	 * @return object Database
383 383
      */
384
-    public function setCacheInstance($cache){
384
+    public function setCacheInstance($cache) {
385 385
       $this->cacheInstance = $cache;
386 386
       return $this;
387 387
     }
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
      * Return the benchmark instance
391 391
      * @return Benchmark
392 392
      */
393
-    public function getBenchmark(){
393
+    public function getBenchmark() {
394 394
       return $this->benchmarkInstance;
395 395
     }
396 396
 
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
      * @param Benchmark $benchmark the benchmark object
400 400
 	 * @return object Database
401 401
      */
402
-    public function setBenchmark($benchmark){
402
+    public function setBenchmark($benchmark) {
403 403
       $this->benchmarkInstance = $benchmark;
404 404
       return $this;
405 405
     }
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
      * Return the DatabaseQueryBuilder instance
410 410
      * @return object DatabaseQueryBuilder
411 411
      */
412
-    public function getQueryBuilder(){
412
+    public function getQueryBuilder() {
413 413
       return $this->queryBuilder;
414 414
     }
415 415
 
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
      * Set the DatabaseQueryBuilder instance
418 418
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
419 419
      */
420
-    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
420
+    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder) {
421 421
       $this->queryBuilder = $queryBuilder;
422 422
       return $this;
423 423
     }
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
      * Return the data to be used for insert, update, etc.
427 427
      * @return array
428 428
      */
429
-    public function getData(){
429
+    public function getData() {
430 430
       return $this->data;
431 431
     }
432 432
 
@@ -437,9 +437,9 @@  discard block
 block discarded – undo
437 437
      * @param boolean $escape whether to escape or not the $value
438 438
      * @return object        the current Database instance
439 439
      */
440
-    public function setData($key, $value = null, $escape = true){
441
-  	  if(is_array($key)){
442
-    		foreach($key as $k => $v){
440
+    public function setData($key, $value = null, $escape = true) {
441
+  	  if (is_array($key)) {
442
+    		foreach ($key as $k => $v) {
443 443
     			$this->setData($k, $v, $escape);
444 444
     		}	
445 445
   	  } else {
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
      * @param  boolean $array return the result as array
457 457
      * @return mixed         the query result
458 458
      */
459
-    public function query($query, $all = true, $array = false){
459
+    public function query($query, $all = true, $array = false) {
460 460
       $this->reset();
461 461
       $query = $this->getPreparedQuery($query, $all);
462 462
       $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
@@ -464,9 +464,9 @@  discard block
 block discarded – undo
464 464
       $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
465 465
 
466 466
       $this->logger->info(
467
-                          'Execute SQL query ['.$this->query.'], return type: ' 
468
-                          . ($array?'ARRAY':'OBJECT') .', return as list: ' 
469
-                          . (is_bool($all) && $all ? 'YES':'NO')
467
+                          'Execute SQL query [' . $this->query . '], return type: ' 
468
+                          . ($array ? 'ARRAY' : 'OBJECT') . ', return as list: ' 
469
+                          . (is_bool($all) && $all ? 'YES' : 'NO')
470 470
                         );
471 471
       //cache expire time
472 472
       $cacheExpire = $this->temporaryCacheTtl;
@@ -483,15 +483,15 @@  discard block
 block discarded – undo
483 483
       //if can use cache feature for this query
484 484
       $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
485 485
     
486
-      if ($dbCacheStatus && $isSqlSELECTQuery){
486
+      if ($dbCacheStatus && $isSqlSELECTQuery) {
487 487
           $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
488 488
           $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
489 489
       }
490 490
       
491
-      if ( !$cacheContent){
491
+      if (!$cacheContent) {
492 492
         $sqlQuery = $this->runSqlQuery($query, $all, $array);
493
-        if (is_object($sqlQuery)){
494
-          if ($isSqlSELECTQuery){
493
+        if (is_object($sqlQuery)) {
494
+          if ($isSqlSELECTQuery) {
495 495
             $this->setQueryResultForSelect($sqlQuery, $all, $array);
496 496
             $this->setCacheContentForQuery(
497 497
                                             $this->query, 
@@ -500,15 +500,15 @@  discard block
 block discarded – undo
500 500
                                             $dbCacheStatus && $isSqlSELECTQuery, 
501 501
                                             $cacheExpire
502 502
                                           );
503
-            if (! $this->result){
503
+            if (!$this->result) {
504 504
               $this->logger->info('No result where found for the query [' . $query . ']');
505 505
             }
506 506
           } else {
507 507
               $this->setQueryResultForNonSelect($sqlQuery);
508 508
           }
509 509
         }
510
-      } else if ($isSqlSELECTQuery){
511
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
510
+      } else if ($isSqlSELECTQuery) {
511
+          $this->logger->info('The result for query [' . $this->query . '] already cached use it');
512 512
           $this->result = $cacheContent;
513 513
           $this->numRows = count($this->result);
514 514
       }
@@ -521,11 +521,11 @@  discard block
 block discarded – undo
521 521
      * 
522 522
      * @return object|void
523 523
      */
524
-    public function runSqlQuery($query, $all, $array){
524
+    public function runSqlQuery($query, $all, $array) {
525 525
        //for database query execution time
526 526
         $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
527 527
         $benchmarkInstance = $this->getBenchmark();
528
-        if (! is_object($benchmarkInstance)){
528
+        if (!is_object($benchmarkInstance)) {
529 529
           $obj = & get_instance();
530 530
           $benchmarkInstance = $obj->benchmark; 
531 531
           $this->setBenchmark($benchmarkInstance);
@@ -538,13 +538,13 @@  discard block
 block discarded – undo
538 538
         //get response time for this query
539 539
         $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
540 540
 		    //TODO use the configuration value for the high response time currently is 1 second
541
-        if ($responseTime >= 1 ){
542
-            $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
541
+        if ($responseTime >= 1) {
542
+            $this->logger->warning('High response time while processing database query [' . $query . ']. The response time is [' . $responseTime . '] sec.');
543 543
         }
544 544
 		    //count the number of query execution to server
545 545
         $this->queryCount++;
546 546
 		
547
-        if ($sqlQuery !== false){
547
+        if ($sqlQuery !== false) {
548 548
           return $sqlQuery;
549 549
         }
550 550
         $this->setQueryError();
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 	 * Return the database configuration
556 556
 	 * @return array
557 557
 	 */
558
-	public  function getDatabaseConfiguration(){
558
+	public  function getDatabaseConfiguration() {
559 559
 	  return $this->config;
560 560
 	}
561 561
 
@@ -565,9 +565,9 @@  discard block
 block discarded – undo
565 565
     * @param boolean $useConfigFile whether to use database configuration file
566 566
 	  * @return object Database
567 567
     */
568
-    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
568
+    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
569 569
         $db = array();
570
-        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
570
+        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')) {
571 571
             //here don't use require_once because somewhere user can create database instance directly
572 572
             require CONFIG_PATH . 'database.php';
573 573
         }
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
     		//determine the port using the hostname like localhost:3307
593 593
         //hostname will be "localhost", and port "3307"
594 594
         $p = explode(':', $config['hostname']);
595
-    	  if (count($p) >= 2){
595
+    	  if (count($p) >= 2) {
596 596
     		  $config['hostname'] = $p[0];
597 597
     		  $config['port'] = $p[1];
598 598
     		}
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 		 $this->connect();
612 612
 		 
613 613
 		 //update queryBuilder with some properties needed
614
-		 if(is_object($this->getQueryBuilder())){
614
+		 if (is_object($this->getQueryBuilder())) {
615 615
 			  $this->getQueryBuilder()->setDriver($config['driver']);
616 616
 			  $this->getQueryBuilder()->setPrefix($config['prefix']);
617 617
 			  $this->getQueryBuilder()->setPdo($this->getPdo());
@@ -623,19 +623,19 @@  discard block
 block discarded – undo
623 623
    * Set the result for SELECT query using PDOStatment
624 624
    * @see Database::query
625 625
    */
626
-    protected function setQueryResultForSelect($pdoStatment, $all, $array){
626
+    protected function setQueryResultForSelect($pdoStatment, $all, $array) {
627 627
       //if need return all result like list of record
628
-      if (is_bool($all) && $all){
628
+      if (is_bool($all) && $all) {
629 629
           $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
630 630
       }
631
-      else{
631
+      else {
632 632
           $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
633 633
       }
634 634
       //Sqlite and pgsql always return 0 when using rowCount()
635
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
635
+      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))) {
636 636
         $this->numRows = count($this->result);  
637 637
       }
638
-      else{
638
+      else {
639 639
         $this->numRows = $pdoStatment->rowCount(); 
640 640
       }
641 641
     }
@@ -644,13 +644,13 @@  discard block
 block discarded – undo
644 644
      * Set the result for other command than SELECT query using PDOStatment
645 645
      * @see Database::query
646 646
      */
647
-    protected function setQueryResultForNonSelect($pdoStatment){
647
+    protected function setQueryResultForNonSelect($pdoStatment) {
648 648
       //Sqlite and pgsql always return 0 when using rowCount()
649
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
649
+      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))) {
650 650
         $this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
651 651
         $this->numRows = 1; //TODO use the correct method to get the exact affected row
652 652
       }
653
-      else{
653
+      else {
654 654
           $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
655 655
           $this->numRows = $pdoStatment->rowCount(); 
656 656
       }
@@ -662,9 +662,9 @@  discard block
 block discarded – undo
662 662
      * This method is used to get the PDO DSN string using the configured driver
663 663
      * @return string the DSN string
664 664
      */
665
-    protected function getDsnFromDriver(){
665
+    protected function getDsnFromDriver() {
666 666
       $config = $this->getDatabaseConfiguration();
667
-      if (! empty($config)){
667
+      if (!empty($config)) {
668 668
         $driver = $config['driver'];
669 669
         $driverDsnMap = array(
670 670
                                 'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
@@ -689,12 +689,12 @@  discard block
 block discarded – undo
689 689
      *
690 690
      * @return string
691 691
      */
692
-    protected function getPreparedQuery($query, $data){
693
-      if (is_array($data)){
692
+    protected function getPreparedQuery($query, $data) {
693
+      if (is_array($data)) {
694 694
   			$x = explode('?', $query);
695 695
   			$q = '';
696
-  			foreach($x as $k => $v){
697
-  			  if (! empty($v)){
696
+  			foreach ($x as $k => $v) {
697
+  			  if (!empty($v)) {
698 698
   				  $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
699 699
   			  }
700 700
   			}
@@ -709,9 +709,9 @@  discard block
 block discarded – undo
709 709
      *      
710 710
      * @return mixed
711 711
      */
712
-    protected function getCacheContentForQuery($query, $all, $array){
712
+    protected function getCacheContentForQuery($query, $all, $array) {
713 713
         $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
714
-        if (! is_object($this->getCacheInstance())){
714
+        if (!is_object($this->getCacheInstance())) {
715 715
     			//can not call method with reference in argument
716 716
     			//like $this->setCacheInstance(& get_instance()->cache);
717 717
     			//use temporary variable
@@ -729,10 +729,10 @@  discard block
 block discarded – undo
729 729
      * @param boolean $status whether can save the query result into cache
730 730
      * @param int $expire the cache TTL
731 731
      */
732
-     protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
733
-        if ($status){
734
-            $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
735
-            if (! is_object($this->getCacheInstance())){
732
+     protected function setCacheContentForQuery($query, $key, $result, $status, $expire) {
733
+        if ($status) {
734
+            $this->logger->info('Save the result for query [' . $query . '] into cache for future use');
735
+            if (!is_object($this->getCacheInstance())) {
736 736
       				//can not call method with reference in argument
737 737
       				//like $this->setCacheInstance(& get_instance()->cache);
738 738
       				//use temporary variable
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
     /**
748 748
      * Set error for database query execution
749 749
      */
750
-    protected function setQueryError(){
750
+    protected function setQueryError() {
751 751
       $error = $this->pdo->errorInfo();
752 752
       $this->error = isset($error[2]) ? $error[2] : '';
753 753
       $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
@@ -761,8 +761,8 @@  discard block
 block discarded – undo
761 761
      * 
762 762
      *  @return string
763 763
      */
764
-    protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
765
-      if (is_array($all)){
764
+    protected function getCacheBenchmarkKeyForQuery($query, $all, $array) {
765
+      if (is_array($all)) {
766 766
         $all = 'array';
767 767
       }
768 768
       return md5($query . $all . $array);
@@ -772,12 +772,12 @@  discard block
 block discarded – undo
772 772
      * Set the Log instance using argument or create new instance
773 773
      * @param object $logger the Log instance if not null
774 774
      */
775
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
776
-      if ($logger !== null){
775
+    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
776
+      if ($logger !== null) {
777 777
         $this->setLogger($logger);
778 778
       }
779
-      else{
780
-          $this->logger =& class_loader('Log', 'classes');
779
+      else {
780
+          $this->logger = & class_loader('Log', 'classes');
781 781
           $this->logger->setLogger('Library::Database');
782 782
       }
783 783
     }
@@ -786,19 +786,19 @@  discard block
 block discarded – undo
786 786
    * Set the DatabaseQueryBuilder instance using argument or create new instance
787 787
    * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
788 788
    */
789
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
790
-	  if ($queryBuilder !== null){
789
+	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null) {
790
+	  if ($queryBuilder !== null) {
791 791
       $this->setQueryBuilder($queryBuilder);
792 792
 	  }
793
-	  else{
794
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
793
+	  else {
794
+		  $this->queryBuilder = & class_loader('DatabaseQueryBuilder', 'classes');
795 795
 	  }
796 796
 	}
797 797
 
798 798
     /**
799 799
      * Reset the database class attributs to the initail values before each query.
800 800
      */
801
-    private function reset(){
801
+    private function reset() {
802 802
 	   //query builder reset
803 803
       $this->getQueryBuilder()->reset();
804 804
       $this->numRows  = 0;
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
     /**
813 813
      * The class destructor
814 814
      */
815
-    public function __destruct(){
815
+    public function __destruct() {
816 816
       $this->pdo = null;
817 817
     }
818 818
 
Please login to merge, or discard this patch.
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -1,124 +1,124 @@  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 error returned for the last query
60
-	 * @var string
61
-	*/
58
+    /**
59
+     * The error returned for the last query
60
+     * @var string
61
+     */
62 62
     private $error               = null;
63 63
 	
64
-	/**
65
-	 * The result returned for the last query
66
-	 * @var mixed
67
-	*/
64
+    /**
65
+     * The result returned for the last query
66
+     * @var mixed
67
+     */
68 68
     private $result              = array();
69 69
 	
70
-	/**
71
-	 * The cache default time to live in second. 0 means no need to use the cache feature
72
-	 * @var int
73
-	*/
74
-	private $cacheTtl              = 0;
70
+    /**
71
+     * The cache default time to live in second. 0 means no need to use the cache feature
72
+     * @var int
73
+     */
74
+    private $cacheTtl              = 0;
75 75
 	
76
-	/**
77
-	 * The cache current time to live. 0 means no need to use the cache feature
78
-	 * @var int
79
-	*/
76
+    /**
77
+     * The cache current time to live. 0 means no need to use the cache feature
78
+     * @var int
79
+     */
80 80
     private $temporaryCacheTtl   = 0;
81 81
 	
82
-	/**
83
-	 * The number of executed query for the current request
84
-	 * @var int
85
-	*/
82
+    /**
83
+     * The number of executed query for the current request
84
+     * @var int
85
+     */
86 86
     private $queryCount          = 0;
87 87
 	
88
-	/**
89
-	 * The default data to be used in the statments query INSERT, UPDATE
90
-	 * @var array
91
-	*/
88
+    /**
89
+     * The default data to be used in the statments query INSERT, UPDATE
90
+     * @var array
91
+     */
92 92
     private $data                = array();
93 93
 	
94
-	/**
95
-	 * The database configuration
96
-	 * @var array
97
-	*/
94
+    /**
95
+     * The database configuration
96
+     * @var array
97
+     */
98 98
     private $config              = array();
99 99
 	
100
-	/**
101
-	 * The logger instance
102
-	 * @var object
103
-	 */
100
+    /**
101
+     * The logger instance
102
+     * @var object
103
+     */
104 104
     private $logger              = null;
105 105
 
106 106
     /**
107
-    * The cache instance
108
-    * @var object
109
-    */
107
+     * The cache instance
108
+     * @var object
109
+     */
110 110
     private $cacheInstance       = null;
111 111
 
112 112
     /**
113
-    * The benchmark instance
114
-    * @var object
115
-    */
113
+     * The benchmark instance
114
+     * @var object
115
+     */
116 116
     private $benchmarkInstance   = null;
117 117
 	
118
-	/**
119
-    * The DatabaseQueryBuilder instance
120
-    * @var object
121
-    */
118
+    /**
119
+     * The DatabaseQueryBuilder instance
120
+     * @var object
121
+     */
122 122
     private $queryBuilder        = null;
123 123
 
124 124
 
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
         //Set Log instance to use
131 131
         $this->setLoggerFromParamOrCreateNewInstance(null);
132 132
 		
133
-		    //Set DatabaseQueryBuilder instance to use
134
-		    $this->setQueryBuilderFromParamOrCreateNewInstance(null);
133
+            //Set DatabaseQueryBuilder instance to use
134
+            $this->setQueryBuilderFromParamOrCreateNewInstance(null);
135 135
 
136 136
         //Set database configuration
137 137
         $this->setDatabaseConfiguration($overwriteConfig);
138 138
 	
139
-		    //cache time to live
140
-    	  $this->temporaryCacheTtl = $this->cacheTtl;
139
+            //cache time to live
140
+            $this->temporaryCacheTtl = $this->cacheTtl;
141 141
     }
142 142
 
143 143
     /**
@@ -145,25 +145,25 @@  discard block
 block discarded – undo
145 145
      * @return bool 
146 146
      */
147 147
     public function connect(){
148
-      $config = $this->getDatabaseConfiguration();
149
-      if (! empty($config)){
148
+        $config = $this->getDatabaseConfiguration();
149
+        if (! empty($config)){
150 150
         try{
151 151
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
152 152
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
153 153
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
154 154
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
155 155
             return true;
156
-          }
157
-          catch (PDOException $e){
156
+            }
157
+            catch (PDOException $e){
158 158
             $this->logger->fatal($e->getMessage());
159 159
             show_error('Cannot connect to Database.');
160 160
             return false;
161
-          }
162
-      }
163
-      else{
161
+            }
162
+        }
163
+        else{
164 164
         show_error('Database configuration is not set.');
165 165
         return false;
166
-      }
166
+        }
167 167
     }
168 168
 
169 169
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
      * @return int
173 173
      */
174 174
     public function numRows(){
175
-      return $this->numRows;
175
+        return $this->numRows;
176 176
     }
177 177
 
178 178
     /**
@@ -180,16 +180,16 @@  discard block
 block discarded – undo
180 180
      * @return mixed
181 181
      */
182 182
     public function insertId(){
183
-      return $this->insertId;
183
+        return $this->insertId;
184 184
     }
185 185
 
186 186
     /**
187 187
      * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
188 188
      */
189 189
     public function error(){
190
-  		if ($this->error){
191
-  			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
192
-  		}
190
+            if ($this->error){
191
+                show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
192
+            }
193 193
     }
194 194
 
195 195
     /**
@@ -199,14 +199,14 @@  discard block
 block discarded – undo
199 199
      * @return mixed       the query SQL string or the record result
200 200
      */
201 201
     public function get($returnSQLQueryOrResultType = false){
202
-      $this->getQueryBuilder()->limit(1);
203
-      $query = $this->getAll(true);
204
-      if ($returnSQLQueryOrResultType === true){
202
+        $this->getQueryBuilder()->limit(1);
203
+        $query = $this->getAll(true);
204
+        if ($returnSQLQueryOrResultType === true){
205 205
         return $query;
206
-      }
207
-      else{
206
+        }
207
+        else{
208 208
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
209
-      }
209
+        }
210 210
     }
211 211
 
212 212
     /**
@@ -216,11 +216,11 @@  discard block
 block discarded – undo
216 216
      * @return mixed       the query SQL string or the record result
217 217
      */
218 218
     public function getAll($returnSQLQueryOrResultType = false){
219
-	   $query = $this->getQueryBuilder()->getQuery();
220
-	   if ($returnSQLQueryOrResultType === true){
221
-      	return $query;
222
-      }
223
-      return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
219
+        $query = $this->getQueryBuilder()->getQuery();
220
+        if ($returnSQLQueryOrResultType === true){
221
+            return $query;
222
+        }
223
+        return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
224 224
     }
225 225
 
226 226
     /**
@@ -230,19 +230,19 @@  discard block
 block discarded – undo
230 230
      * @return mixed          the insert id of the new record or null
231 231
      */
232 232
     public function insert($data = array(), $escape = true){
233
-      if (empty($data) && $this->getData()){
233
+        if (empty($data) && $this->getData()){
234 234
         //as when using $this->setData() may be the data already escaped
235 235
         $escape = false;
236 236
         $data = $this->getData();
237
-      }
238
-      $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
239
-      $result = $this->query($query);
240
-      if ($result){
237
+        }
238
+        $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
239
+        $result = $this->query($query);
240
+        if ($result){
241 241
         $this->insertId = $this->pdo->lastInsertId();
242
-		//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
242
+        //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
243 243
         return ! $this->insertId() ? true : $this->insertId();
244
-      }
245
-      return false;
244
+        }
245
+        return false;
246 246
     }
247 247
 
248 248
     /**
@@ -252,13 +252,13 @@  discard block
 block discarded – undo
252 252
      * @return mixed          the update status
253 253
      */
254 254
     public function update($data = array(), $escape = true){
255
-      if (empty($data) && $this->getData()){
255
+        if (empty($data) && $this->getData()){
256 256
         //as when using $this->setData() may be the data already escaped
257 257
         $escape = false;
258 258
         $data = $this->getData();
259
-      }
260
-      $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
261
-      return $this->query($query);
259
+        }
260
+        $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
261
+        return $this->query($query);
262 262
     }
263 263
 
264 264
     /**
@@ -266,8 +266,8 @@  discard block
 block discarded – undo
266 266
      * @return mixed the delete status
267 267
      */
268 268
     public function delete(){
269
-		$query = $this->getQueryBuilder()->delete()->getQuery();
270
-    	return $this->query($query);
269
+        $query = $this->getQueryBuilder()->delete()->getQuery();
270
+        return $this->query($query);
271 271
     }
272 272
 
273 273
     /**
@@ -276,21 +276,21 @@  discard block
 block discarded – undo
276 276
      * @return object        the current Database instance
277 277
      */
278 278
     public function setCache($ttl = 0){
279
-      if ($ttl > 0){
279
+        if ($ttl > 0){
280 280
         $this->cacheTtl = $ttl;
281 281
         $this->temporaryCacheTtl = $ttl;
282
-      }
283
-      return $this;
282
+        }
283
+        return $this;
284 284
     }
285 285
 	
286
-	/**
287
-	 * Enabled cache temporary for the current query not globally	
288
-	 * @param  integer $ttl the cache time to live in second
289
-	 * @return object        the current Database instance
290
-	 */
291
-  	public function cached($ttl = 0){
286
+    /**
287
+     * Enabled cache temporary for the current query not globally	
288
+     * @param  integer $ttl the cache time to live in second
289
+     * @return object        the current Database instance
290
+     */
291
+        public function cached($ttl = 0){
292 292
         if ($ttl > 0){
293
-          $this->temporaryCacheTtl = $ttl;
293
+            $this->temporaryCacheTtl = $ttl;
294 294
         }
295 295
         return $this;
296 296
     }
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
      * @return mixed       the data after escaped or the same data if not
303 303
      */
304 304
     public function escape($data, $escaped = true){
305
-      return $escaped ? 
305
+        return $escaped ? 
306 306
                       $this->getPdo()->quote(trim($data)) 
307 307
                       : $data; 
308 308
     }
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
      * @return int
313 313
      */
314 314
     public function queryCount(){
315
-      return $this->queryCount;
315
+        return $this->queryCount;
316 316
     }
317 317
 
318 318
     /**
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
      * @return string
321 321
      */
322 322
     public function getQuery(){
323
-      return $this->query;
323
+        return $this->query;
324 324
     }
325 325
 
326 326
     /**
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
      * @return string
329 329
      */
330 330
     public function getDatabaseName(){
331
-      return $this->databaseName;
331
+        return $this->databaseName;
332 332
     }
333 333
 
334 334
     /**
@@ -336,17 +336,17 @@  discard block
 block discarded – undo
336 336
      * @return object
337 337
      */
338 338
     public function getPdo(){
339
-      return $this->pdo;
339
+        return $this->pdo;
340 340
     }
341 341
 
342 342
     /**
343 343
      * Set the PDO instance
344 344
      * @param object $pdo the pdo object
345
-	 * @return object Database
345
+     * @return object Database
346 346
      */
347 347
     public function setPdo(PDO $pdo){
348
-      $this->pdo = $pdo;
349
-      return $this;
348
+        $this->pdo = $pdo;
349
+        return $this;
350 350
     }
351 351
 
352 352
 
@@ -355,35 +355,35 @@  discard block
 block discarded – undo
355 355
      * @return Log
356 356
      */
357 357
     public function getLogger(){
358
-      return $this->logger;
358
+        return $this->logger;
359 359
     }
360 360
 
361 361
     /**
362 362
      * Set the log instance
363 363
      * @param Log $logger the log object
364
-	 * @return object Database
364
+     * @return object Database
365 365
      */
366 366
     public function setLogger($logger){
367
-      $this->logger = $logger;
368
-      return $this;
367
+        $this->logger = $logger;
368
+        return $this;
369 369
     }
370 370
 
371
-     /**
372
-     * Return the cache instance
373
-     * @return CacheInterface
374
-     */
371
+        /**
372
+         * Return the cache instance
373
+         * @return CacheInterface
374
+         */
375 375
     public function getCacheInstance(){
376
-      return $this->cacheInstance;
376
+        return $this->cacheInstance;
377 377
     }
378 378
 
379 379
     /**
380 380
      * Set the cache instance
381 381
      * @param CacheInterface $cache the cache object
382
-	 * @return object Database
382
+     * @return object Database
383 383
      */
384 384
     public function setCacheInstance($cache){
385
-      $this->cacheInstance = $cache;
386
-      return $this;
385
+        $this->cacheInstance = $cache;
386
+        return $this;
387 387
     }
388 388
 
389 389
     /**
@@ -391,26 +391,26 @@  discard block
 block discarded – undo
391 391
      * @return Benchmark
392 392
      */
393 393
     public function getBenchmark(){
394
-      return $this->benchmarkInstance;
394
+        return $this->benchmarkInstance;
395 395
     }
396 396
 
397 397
     /**
398 398
      * Set the benchmark instance
399 399
      * @param Benchmark $benchmark the benchmark object
400
-	 * @return object Database
400
+     * @return object Database
401 401
      */
402 402
     public function setBenchmark($benchmark){
403
-      $this->benchmarkInstance = $benchmark;
404
-      return $this;
403
+        $this->benchmarkInstance = $benchmark;
404
+        return $this;
405 405
     }
406 406
 	
407 407
 	
408
-	/**
408
+    /**
409 409
      * Return the DatabaseQueryBuilder instance
410 410
      * @return object DatabaseQueryBuilder
411 411
      */
412 412
     public function getQueryBuilder(){
413
-      return $this->queryBuilder;
413
+        return $this->queryBuilder;
414 414
     }
415 415
 
416 416
     /**
@@ -418,8 +418,8 @@  discard block
 block discarded – undo
418 418
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
419 419
      */
420 420
     public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
421
-      $this->queryBuilder = $queryBuilder;
422
-      return $this;
421
+        $this->queryBuilder = $queryBuilder;
422
+        return $this;
423 423
     }
424 424
 
425 425
     /**
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
      * @return array
428 428
      */
429 429
     public function getData(){
430
-      return $this->data;
430
+        return $this->data;
431 431
     }
432 432
 
433 433
     /**
@@ -438,60 +438,60 @@  discard block
 block discarded – undo
438 438
      * @return object        the current Database instance
439 439
      */
440 440
     public function setData($key, $value = null, $escape = true){
441
-  	  if(is_array($key)){
442
-    		foreach($key as $k => $v){
443
-    			$this->setData($k, $v, $escape);
444
-    		}	
445
-  	  } else {
441
+        if(is_array($key)){
442
+            foreach($key as $k => $v){
443
+                $this->setData($k, $v, $escape);
444
+            }	
445
+        } else {
446 446
         $this->data[$key] = $this->escape($value, $escape);
447
-  	  }
448
-      return $this;
447
+        }
448
+        return $this;
449 449
     }
450 450
 
451
-     /**
452
-     * Execute an SQL query
453
-     * @param  string  $query the query SQL string
454
-     * @param  boolean|array $all  if boolean this indicate whether to return all record or not, if array 
455
-     * will 
456
-     * @param  boolean $array return the result as array
457
-     * @return mixed         the query result
458
-     */
451
+        /**
452
+         * Execute an SQL query
453
+         * @param  string  $query the query SQL string
454
+         * @param  boolean|array $all  if boolean this indicate whether to return all record or not, if array 
455
+         * will 
456
+         * @param  boolean $array return the result as array
457
+         * @return mixed         the query result
458
+         */
459 459
     public function query($query, $all = true, $array = false){
460
-      $this->reset();
461
-      $query = $this->getPreparedQuery($query, $all);
462
-      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
460
+        $this->reset();
461
+        $query = $this->getPreparedQuery($query, $all);
462
+        $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
463 463
       
464
-      $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
464
+        $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
465 465
 
466
-      $this->logger->info(
467
-                          'Execute SQL query ['.$this->query.'], return type: ' 
468
-                          . ($array?'ARRAY':'OBJECT') .', return as list: ' 
469
-                          . (is_bool($all) && $all ? 'YES':'NO')
466
+        $this->logger->info(
467
+                            'Execute SQL query ['.$this->query.'], return type: ' 
468
+                            . ($array?'ARRAY':'OBJECT') .', return as list: ' 
469
+                            . (is_bool($all) && $all ? 'YES':'NO')
470 470
                         );
471
-      //cache expire time
472
-      $cacheExpire = $this->temporaryCacheTtl;
471
+        //cache expire time
472
+        $cacheExpire = $this->temporaryCacheTtl;
473 473
       
474
-      //return to the initial cache time
475
-      $this->temporaryCacheTtl = $this->cacheTtl;
474
+        //return to the initial cache time
475
+        $this->temporaryCacheTtl = $this->cacheTtl;
476 476
       
477
-      //config for cache
478
-      $cacheEnable = get_config('cache_enable');
477
+        //config for cache
478
+        $cacheEnable = get_config('cache_enable');
479 479
       
480
-      //the database cache content
481
-      $cacheContent = null;
480
+        //the database cache content
481
+        $cacheContent = null;
482 482
 
483
-      //if can use cache feature for this query
484
-      $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
483
+        //if can use cache feature for this query
484
+        $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
485 485
     
486
-      if ($dbCacheStatus && $isSqlSELECTQuery){
487
-          $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
488
-          $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
489
-      }
486
+        if ($dbCacheStatus && $isSqlSELECTQuery){
487
+            $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
488
+            $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
489
+        }
490 490
       
491
-      if ( !$cacheContent){
491
+        if ( !$cacheContent){
492 492
         $sqlQuery = $this->runSqlQuery($query, $all, $array);
493 493
         if (is_object($sqlQuery)){
494
-          if ($isSqlSELECTQuery){
494
+            if ($isSqlSELECTQuery){
495 495
             $this->setQueryResultForSelect($sqlQuery, $all, $array);
496 496
             $this->setCacheContentForQuery(
497 497
                                             $this->query, 
@@ -499,36 +499,36 @@  discard block
 block discarded – undo
499 499
                                             $this->result, 
500 500
                                             $dbCacheStatus && $isSqlSELECTQuery, 
501 501
                                             $cacheExpire
502
-                                          );
502
+                                            );
503 503
             if (! $this->result){
504
-              $this->logger->info('No result where found for the query [' . $query . ']');
504
+                $this->logger->info('No result where found for the query [' . $query . ']');
505
+            }
506
+            } else {
507
+                $this->setQueryResultForNonSelect($sqlQuery);
505 508
             }
506
-          } else {
507
-              $this->setQueryResultForNonSelect($sqlQuery);
508
-          }
509 509
         }
510
-      } else if ($isSqlSELECTQuery){
511
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
512
-          $this->result = $cacheContent;
513
-          $this->numRows = count($this->result);
514
-      }
515
-      return $this->result;
510
+        } else if ($isSqlSELECTQuery){
511
+            $this->logger->info('The result for query [' .$this->query. '] already cached use it');
512
+            $this->result = $cacheContent;
513
+            $this->numRows = count($this->result);
514
+        }
515
+        return $this->result;
516 516
     }
517 517
 	
518
-	/**
518
+    /**
519 519
      * Run the database SQL query and return the PDOStatment object
520 520
      * @see Database::query
521 521
      * 
522 522
      * @return object|void
523 523
      */
524 524
     public function runSqlQuery($query, $all, $array){
525
-       //for database query execution time
525
+        //for database query execution time
526 526
         $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
527 527
         $benchmarkInstance = $this->getBenchmark();
528 528
         if (! is_object($benchmarkInstance)){
529
-          $obj = & get_instance();
530
-          $benchmarkInstance = $obj->benchmark; 
531
-          $this->setBenchmark($benchmarkInstance);
529
+            $obj = & get_instance();
530
+            $benchmarkInstance = $obj->benchmark; 
531
+            $this->setBenchmark($benchmarkInstance);
532 532
         }
533 533
         
534 534
         $benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
@@ -537,34 +537,34 @@  discard block
 block discarded – undo
537 537
         
538 538
         //get response time for this query
539 539
         $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
540
-		    //TODO use the configuration value for the high response time currently is 1 second
540
+            //TODO use the configuration value for the high response time currently is 1 second
541 541
         if ($responseTime >= 1 ){
542 542
             $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
543 543
         }
544
-		    //count the number of query execution to server
544
+            //count the number of query execution to server
545 545
         $this->queryCount++;
546 546
 		
547 547
         if ($sqlQuery !== false){
548
-          return $sqlQuery;
548
+            return $sqlQuery;
549 549
         }
550 550
         $this->setQueryError();
551 551
     }
552 552
 	
553 553
 	
554
-	 /**
555
-	 * Return the database configuration
556
-	 * @return array
557
-	 */
558
-	public  function getDatabaseConfiguration(){
559
-	  return $this->config;
560
-	}
561
-
562
-   /**
563
-    * Setting the database configuration using the configuration file and additional configuration from param
564
-    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
565
-    * @param boolean $useConfigFile whether to use database configuration file
566
-	  * @return object Database
567
-    */
554
+        /**
555
+         * Return the database configuration
556
+         * @return array
557
+         */
558
+    public  function getDatabaseConfiguration(){
559
+        return $this->config;
560
+    }
561
+
562
+    /**
563
+     * Setting the database configuration using the configuration file and additional configuration from param
564
+     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
565
+     * @param boolean $useConfigFile whether to use database configuration file
566
+     * @return object Database
567
+     */
568 568
     public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
569 569
         $db = array();
570 570
         if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
@@ -577,67 +577,67 @@  discard block
 block discarded – undo
577 577
         
578 578
         //default configuration
579 579
         $config = array(
580
-          'driver' => 'mysql',
581
-          'username' => 'root',
582
-          'password' => '',
583
-          'database' => '',
584
-          'hostname' => 'localhost',
585
-          'charset' => 'utf8',
586
-          'collation' => 'utf8_general_ci',
587
-          'prefix' => '',
588
-          'port' => ''
580
+            'driver' => 'mysql',
581
+            'username' => 'root',
582
+            'password' => '',
583
+            'database' => '',
584
+            'hostname' => 'localhost',
585
+            'charset' => 'utf8',
586
+            'collation' => 'utf8_general_ci',
587
+            'prefix' => '',
588
+            'port' => ''
589 589
         );
590 590
 		
591
-    		$config = array_merge($config, $db);
592
-    		//determine the port using the hostname like localhost:3307
591
+            $config = array_merge($config, $db);
592
+            //determine the port using the hostname like localhost:3307
593 593
         //hostname will be "localhost", and port "3307"
594 594
         $p = explode(':', $config['hostname']);
595
-    	  if (count($p) >= 2){
596
-    		  $config['hostname'] = $p[0];
597
-    		  $config['port'] = $p[1];
598
-    		}
595
+            if (count($p) >= 2){
596
+                $config['hostname'] = $p[0];
597
+                $config['port'] = $p[1];
598
+            }
599 599
 		
600
-		 $this->databaseName = $config['database'];
601
-		 $this->config = $config;
602
-		 $this->logger->info(
603
-								'The database configuration are listed below: ' 
604
-								. stringfy_vars(array_merge(
605
-															$this->config, 
606
-															array('password' => string_hidden($this->config['password']))
607
-												))
608
-							);
600
+            $this->databaseName = $config['database'];
601
+            $this->config = $config;
602
+            $this->logger->info(
603
+                                'The database configuration are listed below: ' 
604
+                                . stringfy_vars(array_merge(
605
+                                                            $this->config, 
606
+                                                            array('password' => string_hidden($this->config['password']))
607
+                                                ))
608
+                            );
609 609
 	  
610
-		 //Now connect to the database
611
-		 $this->connect();
610
+            //Now connect to the database
611
+            $this->connect();
612 612
 		 
613
-		 //update queryBuilder with some properties needed
614
-		 if(is_object($this->getQueryBuilder())){
615
-			  $this->getQueryBuilder()->setDriver($config['driver']);
616
-			  $this->getQueryBuilder()->setPrefix($config['prefix']);
617
-			  $this->getQueryBuilder()->setPdo($this->getPdo());
618
-		 }
619
-		 return $this;
620
-  }
613
+            //update queryBuilder with some properties needed
614
+            if(is_object($this->getQueryBuilder())){
615
+                $this->getQueryBuilder()->setDriver($config['driver']);
616
+                $this->getQueryBuilder()->setPrefix($config['prefix']);
617
+                $this->getQueryBuilder()->setPdo($this->getPdo());
618
+            }
619
+            return $this;
620
+    }
621 621
 	
622
-   /**
623
-   * Set the result for SELECT query using PDOStatment
624
-   * @see Database::query
625
-   */
622
+    /**
623
+     * Set the result for SELECT query using PDOStatment
624
+     * @see Database::query
625
+     */
626 626
     protected function setQueryResultForSelect($pdoStatment, $all, $array){
627
-      //if need return all result like list of record
628
-      if (is_bool($all) && $all){
629
-          $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
630
-      }
631
-      else{
632
-          $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
633
-      }
634
-      //Sqlite and pgsql always return 0 when using rowCount()
635
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
627
+        //if need return all result like list of record
628
+        if (is_bool($all) && $all){
629
+            $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
630
+        }
631
+        else{
632
+            $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
633
+        }
634
+        //Sqlite and pgsql always return 0 when using rowCount()
635
+        if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
636 636
         $this->numRows = count($this->result);  
637
-      }
638
-      else{
637
+        }
638
+        else{
639 639
         $this->numRows = $pdoStatment->rowCount(); 
640
-      }
640
+        }
641 641
     }
642 642
 
643 643
     /**
@@ -645,15 +645,15 @@  discard block
 block discarded – undo
645 645
      * @see Database::query
646 646
      */
647 647
     protected function setQueryResultForNonSelect($pdoStatment){
648
-      //Sqlite and pgsql always return 0 when using rowCount()
649
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
648
+        //Sqlite and pgsql always return 0 when using rowCount()
649
+        if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
650 650
         $this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
651 651
         $this->numRows = 1; //TODO use the correct method to get the exact affected row
652
-      }
653
-      else{
654
-          $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
655
-          $this->numRows = $pdoStatment->rowCount(); 
656
-      }
652
+        }
653
+        else{
654
+            $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
655
+            $this->numRows = $pdoStatment->rowCount(); 
656
+        }
657 657
     }
658 658
 
659 659
 	
@@ -663,8 +663,8 @@  discard block
 block discarded – undo
663 663
      * @return string the DSN string
664 664
      */
665 665
     protected function getDsnFromDriver(){
666
-      $config = $this->getDatabaseConfiguration();
667
-      if (! empty($config)){
666
+        $config = $this->getDatabaseConfiguration();
667
+        if (! empty($config)){
668 668
         $driver = $config['driver'];
669 669
         $driverDsnMap = array(
670 670
                                 'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
@@ -677,30 +677,30 @@  discard block
 block discarded – undo
677 677
                                 'oracle' => 'oci:dbname=' . $config['hostname'] 
678 678
                                             . (($config['port']) != '' ? ':' . $config['port'] : '')
679 679
                                             . '/' . $config['database']
680
-                              );
680
+                                );
681 681
         return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : '';
682
-      }                   
683
-      return null;
682
+        }                   
683
+        return null;
684 684
     }
685 685
 
686
-     /**
687
-     * Transform the prepared query like (?, ?, ?) into string format
688
-     * @see Database::query
689
-     *
690
-     * @return string
691
-     */
686
+        /**
687
+         * Transform the prepared query like (?, ?, ?) into string format
688
+         * @see Database::query
689
+         *
690
+         * @return string
691
+         */
692 692
     protected function getPreparedQuery($query, $data){
693
-      if (is_array($data)){
694
-  			$x = explode('?', $query);
695
-  			$q = '';
696
-  			foreach($x as $k => $v){
697
-  			  if (! empty($v)){
698
-  				  $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
699
-  			  }
700
-  			}
701
-  			return $q;
702
-      }
703
-      return $query;
693
+        if (is_array($data)){
694
+                $x = explode('?', $query);
695
+                $q = '';
696
+                foreach($x as $k => $v){
697
+                if (! empty($v)){
698
+                    $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
699
+                }
700
+                }
701
+                return $q;
702
+        }
703
+        return $query;
704 704
     }
705 705
 
706 706
     /**
@@ -712,11 +712,11 @@  discard block
 block discarded – undo
712 712
     protected function getCacheContentForQuery($query, $all, $array){
713 713
         $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
714 714
         if (! is_object($this->getCacheInstance())){
715
-    			//can not call method with reference in argument
716
-    			//like $this->setCacheInstance(& get_instance()->cache);
717
-    			//use temporary variable
718
-    			$instance = & get_instance()->cache;
719
-    			$this->setCacheInstance($instance);
715
+                //can not call method with reference in argument
716
+                //like $this->setCacheInstance(& get_instance()->cache);
717
+                //use temporary variable
718
+                $instance = & get_instance()->cache;
719
+                $this->setCacheInstance($instance);
720 720
         }
721 721
         return $this->getCacheInstance()->get($cacheKey);
722 722
     }
@@ -729,91 +729,91 @@  discard block
 block discarded – undo
729 729
      * @param boolean $status whether can save the query result into cache
730 730
      * @param int $expire the cache TTL
731 731
      */
732
-     protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
732
+        protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
733 733
         if ($status){
734 734
             $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
735 735
             if (! is_object($this->getCacheInstance())){
736
-      				//can not call method with reference in argument
737
-      				//like $this->setCacheInstance(& get_instance()->cache);
738
-      				//use temporary variable
739
-      				$instance = & get_instance()->cache;
740
-      				$this->setCacheInstance($instance);
741
-      			}
736
+                        //can not call method with reference in argument
737
+                        //like $this->setCacheInstance(& get_instance()->cache);
738
+                        //use temporary variable
739
+                        $instance = & get_instance()->cache;
740
+                        $this->setCacheInstance($instance);
741
+                    }
742 742
             $this->getCacheInstance()->set($key, $result, $expire);
743 743
         }
744
-     }
744
+        }
745 745
 
746 746
     
747 747
     /**
748 748
      * Set error for database query execution
749 749
      */
750 750
     protected function setQueryError(){
751
-      $error = $this->pdo->errorInfo();
752
-      $this->error = isset($error[2]) ? $error[2] : '';
753
-      $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
754
-	    //show error message
755
-      $this->error();
756
-    }
757
-
758
-	  /**
759
-     * Return the cache key for the given query
760
-     * @see Database::query
761
-     * 
762
-     *  @return string
763
-     */
751
+        $error = $this->pdo->errorInfo();
752
+        $this->error = isset($error[2]) ? $error[2] : '';
753
+        $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
754
+        //show error message
755
+        $this->error();
756
+    }
757
+
758
+        /**
759
+         * Return the cache key for the given query
760
+         * @see Database::query
761
+         * 
762
+         *  @return string
763
+         */
764 764
     protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
765
-      if (is_array($all)){
765
+        if (is_array($all)){
766 766
         $all = 'array';
767
-      }
768
-      return md5($query . $all . $array);
767
+        }
768
+        return md5($query . $all . $array);
769 769
     }
770 770
     
771
-	   /**
772
-     * Set the Log instance using argument or create new instance
773
-     * @param object $logger the Log instance if not null
774
-     */
771
+        /**
772
+         * Set the Log instance using argument or create new instance
773
+         * @param object $logger the Log instance if not null
774
+         */
775 775
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
776
-      if ($logger !== null){
776
+        if ($logger !== null){
777 777
         $this->setLogger($logger);
778
-      }
779
-      else{
780
-          $this->logger =& class_loader('Log', 'classes');
781
-          $this->logger->setLogger('Library::Database');
782
-      }
778
+        }
779
+        else{
780
+            $this->logger =& class_loader('Log', 'classes');
781
+            $this->logger->setLogger('Library::Database');
782
+        }
783 783
     }
784 784
 	
785
-   /**
786
-   * Set the DatabaseQueryBuilder instance using argument or create new instance
787
-   * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
788
-   */
789
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
790
-	  if ($queryBuilder !== null){
791
-      $this->setQueryBuilder($queryBuilder);
792
-	  }
793
-	  else{
794
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
795
-	  }
796
-	}
785
+    /**
786
+     * Set the DatabaseQueryBuilder instance using argument or create new instance
787
+     * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
788
+     */
789
+    protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
790
+        if ($queryBuilder !== null){
791
+        $this->setQueryBuilder($queryBuilder);
792
+        }
793
+        else{
794
+            $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
795
+        }
796
+    }
797 797
 
798 798
     /**
799 799
      * Reset the database class attributs to the initail values before each query.
800 800
      */
801 801
     private function reset(){
802
-	   //query builder reset
803
-      $this->getQueryBuilder()->reset();
804
-      $this->numRows  = 0;
805
-      $this->insertId = null;
806
-      $this->query    = null;
807
-      $this->error    = null;
808
-      $this->result   = array();
809
-      $this->data     = array();
802
+        //query builder reset
803
+        $this->getQueryBuilder()->reset();
804
+        $this->numRows  = 0;
805
+        $this->insertId = null;
806
+        $this->query    = null;
807
+        $this->error    = null;
808
+        $this->result   = array();
809
+        $this->data     = array();
810 810
     }
811 811
 
812 812
     /**
813 813
      * The class destructor
814 814
      */
815 815
     public function __destruct(){
816
-      $this->pdo = null;
816
+        $this->pdo = null;
817 817
     }
818 818
 
819 819
 }
Please login to merge, or discard this patch.
core/classes/DatabaseQueryBuilder.php 3 patches
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 = true);
@@ -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->getPdo()->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 PDO
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.
Braces   +7 added lines, -14 removed lines patch added patch discarded remove patch
@@ -225,8 +225,7 @@  discard block
 block discarded – undo
225 225
       }
226 226
       if (empty($this->join)){
227 227
         $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
228
-      }
229
-      else{
228
+      } else{
230 229
         $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
231 230
       }
232 231
       return $this;
@@ -334,8 +333,7 @@  discard block
 block discarded – undo
334 333
       $whereStr = '';
335 334
       if (is_array($where)){
336 335
         $whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
337
-      }
338
-      else{
336
+      } else{
339 337
         if (is_array($op)){
340 338
           $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
341 339
         } else {
@@ -585,8 +583,7 @@  discard block
 block discarded – undo
585 583
       }
586 584
       if (! is_null($limitEnd)){
587 585
         $this->limit = $limit . ', ' . $limitEnd;
588
-      }
589
-      else{
586
+      } else{
590 587
         $this->limit = $limit;
591 588
       }
592 589
       return $this;
@@ -601,8 +598,7 @@  discard block
 block discarded – undo
601 598
     public function orderBy($orderBy, $orderDir = ' ASC'){
602 599
       if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
603 600
         $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
604
-      }
605
-      else{
601
+      } else{
606 602
         $this->orderBy = empty($this->orderBy) 
607 603
 						? ($orderBy . ' ' . strtoupper($orderDir)) 
608 604
 						: $this->orderBy . ', ' . $orderBy . ' ' . strtoupper($orderDir);
@@ -618,8 +614,7 @@  discard block
 block discarded – undo
618 614
     public function groupBy($field){
619 615
       if (is_array($field)){
620 616
         $this->groupBy = implode(', ', $field);
621
-      }
622
-      else{
617
+      } else{
623 618
         $this->groupBy = $field;
624 619
       }
625 620
       return $this;
@@ -636,14 +631,12 @@  discard block
 block discarded – undo
636 631
     public function having($field, $op = null, $val = null, $escape = true){
637 632
       if (is_array($op)){
638 633
         $this->having = $this->getHavingStrIfOperatorIsArray($field, $op, $escape);
639
-      }
640
-      else if (! in_array($op, $this->operatorList)){
634
+      } else if (! in_array($op, $this->operatorList)){
641 635
         if (is_null($op)){
642 636
           $op = '';
643 637
         }
644 638
         $this->having = $field . ' > ' . ($this->escape($op, $escape));
645
-      }
646
-      else{
639
+      } else{
647 640
         if (is_null($val)){
648 641
           $val = '';
649 642
         }
Please login to merge, or discard this patch.
Indentation   +390 added lines, -390 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
-  /**
96
-	 * The PDO instance
97
-	 * @var object
98
-	*/
99
-  private $pdo                 = null;
95
+    /**
96
+     * The PDO instance
97
+     * @var object
98
+     */
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
+        }
300
+        } else {
301
+            $this->setWhereStr($field.' IS NULL ', $andOr);
299 302
         }
300
-      } else {
301
-          $this->setWhereStr($field.' IS NULL ', $andOr);
302
-      }
303
-      return $this;
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 316
         }
317
-      } else {
318
-          $this->setWhereStr($field.' IS NOT NULL ', $andOr);
319
-      }
320
-      return $this;
317
+        } else {
318
+            $this->setWhereStr($field.' IS NOT NULL ', $andOr);
319
+        }
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 = true);
342
+            $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape = true);
343 343
         }
344
-      }
345
-      $this->setWhereStr($whereStr, $andOr);
346
-      return $this;
344
+        }
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->getPdo()->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 PDO
777
-     */
774
+        /**
775
+         * Return the PDO instance
776
+         * @return PDO
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.
core/classes/Response.php 3 patches
Spacing   +74 added lines, -74 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,9 +65,9 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Construct new response instance
67 67
 		 */
68
-		public function __construct(){
69
-			$this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
-					. (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
68
+		public function __construct() {
69
+			$this->_currentUrl = (!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '')
70
+					. (!empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '');
71 71
 					
72 72
 			$this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
@@ -82,9 +82,9 @@  discard block
 block discarded – undo
82 82
 		 * Get the logger singleton instance
83 83
 		 * @return Log the logger instance
84 84
 		 */
85
-		private static function getLogger(){
86
-			if(self::$logger == null){
87
-				self::$logger[0] =& class_loader('Log', 'classes');
85
+		private static function getLogger() {
86
+			if (self::$logger == null) {
87
+				self::$logger[0] = & class_loader('Log', 'classes');
88 88
 				self::$logger[0]->setLogger('Library::Response');
89 89
 			}
90 90
 			return self::$logger[0];
@@ -95,12 +95,12 @@  discard block
 block discarded – undo
95 95
 		 * @param  integer $httpCode the HTTP status code
96 96
 		 * @param  array   $headers   the additional headers to add to the existing headers list
97 97
 		 */
98
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
98
+		public static function sendHeaders($httpCode = 200, array $headers = array()) {
99 99
 			set_http_status_header($httpCode);
100 100
 			self::setHeaders($headers);
101
-			if(! headers_sent()){
102
-				foreach(self::getHeaders() as $key => $value){
103
-					header($key .': '.$value);
101
+			if (!headers_sent()) {
102
+				foreach (self::getHeaders() as $key => $value) {
103
+					header($key . ': ' . $value);
104 104
 				}
105 105
 			}
106 106
 		}
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		 * Get the list of the headers
110 110
 		 * @return array the headers list
111 111
 		 */
112
-		public static function getHeaders(){
112
+		public static function getHeaders() {
113 113
 			return self::$headers;
114 114
 		}
115 115
 
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 		 * @param  string $name the header name
119 119
 		 * @return string       the header value
120 120
 		 */
121
-		public static function getHeader($name){
121
+		public static function getHeader($name) {
122 122
 			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123 123
 		}
124 124
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		 * @param string $name  the header name
129 129
 		 * @param string $value the header value to be set
130 130
 		 */
131
-		public static function setHeader($name, $value){
131
+		public static function setHeader($name, $value) {
132 132
 			self::$headers[$name] = $value;
133 133
 		}
134 134
 
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 		 * @param array $headers the list of the headers to set. 
138 138
 		 * Note: this will merge with the existing headers
139 139
 		 */
140
-		public static function setHeaders(array $headers){
140
+		public static function setHeaders(array $headers) {
141 141
 			self::$headers = array_merge(self::getHeaders(), $headers);
142 142
 		}
143 143
 		
@@ -145,17 +145,17 @@  discard block
 block discarded – undo
145 145
 		 * Redirect user in the specified page
146 146
 		 * @param  string $path the URL or URI to be redirect to
147 147
 		 */
148
-		public static function redirect($path = ''){
148
+		public static function redirect($path = '') {
149 149
 			$logger = self::getLogger();
150 150
 			$url = Url::site_url($path);
151
-			$logger->info('Redirect to URL [' .$url. ']');
152
-			if(! headers_sent()){
153
-				header('Location: '.$url);
151
+			$logger->info('Redirect to URL [' . $url . ']');
152
+			if (!headers_sent()) {
153
+				header('Location: ' . $url);
154 154
 				exit;
155 155
 			}
156
-			else{
156
+			else {
157 157
 				echo '<script>
158
-						location.href = "'.$url.'";
158
+						location.href = "'.$url . '";
159 159
 					</script>';
160 160
 			}
161 161
 		}
@@ -168,10 +168,10 @@  discard block
 block discarded – undo
168 168
 		 * @return void|string          if $return is true will return the view content otherwise
169 169
 		 * will display the view content.
170 170
 		 */
171
-		public function render($view, $data = null, $return = false){
171
+		public function render($view, $data = null, $return = false) {
172 172
 			$logger = self::getLogger();
173 173
 			//convert data to an array
174
-			$data = ! is_array($data) ? (array) $data : $data;
174
+			$data = !is_array($data) ? (array) $data : $data;
175 175
 			$view = str_ireplace('.php', '', $view);
176 176
 			$view = trim($view, '/\\');
177 177
 			$viewFile = $view . '.php';
@@ -180,42 +180,42 @@  discard block
 block discarded – undo
180 180
 			//super instance
181 181
 			$obj = & get_instance();
182 182
 			
183
-			if(Module::hasModule()){
183
+			if (Module::hasModule()) {
184 184
 				//check in module first
185 185
 				$logger->debug('Checking the view [' . $view . '] from module list ...');
186 186
 				$mod = null;
187 187
 				//check if the request class contains module name
188
-				if(strpos($view, '/') !== false){
188
+				if (strpos($view, '/') !== false) {
189 189
 					$viewPath = explode('/', $view);
190
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
190
+					if (isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())) {
191 191
 						$mod = $viewPath[0];
192 192
 						array_shift($viewPath);
193 193
 						$view = implode('/', $viewPath);
194 194
 						$viewFile = $view . '.php';
195 195
 					}
196 196
 				}
197
-				if(! $mod && !empty($obj->moduleName)){
197
+				if (!$mod && !empty($obj->moduleName)) {
198 198
 					$mod = $obj->moduleName;
199 199
 				}
200
-				if($mod){
200
+				if ($mod) {
201 201
 					$moduleViewPath = Module::findViewFullPath($view, $mod);
202
-					if($moduleViewPath){
202
+					if ($moduleViewPath) {
203 203
 						$path = $moduleViewPath;
204
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
204
+						$logger->info('Found view [' . $view . '] in module [' . $mod . '], the file path is [' . $moduleViewPath . '] we will used it');
205 205
 					}
206
-					else{
207
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
206
+					else {
207
+						$logger->info('Cannot find view [' . $view . '] in module [' . $mod . '] using the default location');
208 208
 					}
209 209
 				}
210
-				else{
210
+				else {
211 211
 					$logger->info('The current request does not use module using the default location.');
212 212
 				}
213 213
 			}
214 214
 			$logger->info('The view file path to be loaded is [' . $path . ']');
215 215
 			$found = false;
216
-			if(file_exists($path)){
217
-				foreach(get_object_vars($obj) as $key => $value){
218
-					if(! isset($this->{$key})){
216
+			if (file_exists($path)) {
217
+				foreach (get_object_vars($obj) as $key => $value) {
218
+					if (!isset($this->{$key})) {
219 219
 						$this->{$key} = & $obj->{$key};
220 220
 					}
221 221
 				}
@@ -224,44 +224,44 @@  discard block
 block discarded – undo
224 224
 				//need use require() instead of require_once because can load this view many time
225 225
 				require $path;
226 226
 				$content = ob_get_clean();
227
-				if($return){
227
+				if ($return) {
228 228
 					return $content;
229 229
 				}
230 230
 				$this->_pageRender .= $content;
231 231
 				$found = true;
232 232
 			}
233
-			if(! $found){
234
-				show_error('Unable to find view [' .$view . ']');
233
+			if (!$found) {
234
+				show_error('Unable to find view [' . $view . ']');
235 235
 			}
236 236
 		}
237 237
 		
238 238
 		/**
239 239
 		* Send the final page output to user
240 240
 		*/
241
-		public function renderFinalPage(){
241
+		public function renderFinalPage() {
242 242
 			$logger = self::getLogger();
243 243
 			$obj = & get_instance();
244 244
 			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245 245
 			$dispatcher = $obj->eventdispatcher;
246 246
 			$content = $this->_pageRender;
247
-			if(! $content){
247
+			if (!$content) {
248 248
 				$logger->warning('The final view content is empty.');
249 249
 				return;
250 250
 			}
251 251
 			//dispatch
252 252
 			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
-			$content = ! empty($event->payload) ? $event->payload : null;
254
-			if(empty($content)){
253
+			$content = !empty($event->payload) ? $event->payload : null;
254
+			if (empty($content)) {
255 255
 				$logger->warning('The view content is empty after dispatch to event listeners.');
256 256
 			}
257 257
 			
258 258
 			//check whether need save the page into cache.
259
-			if($cachePageStatus){
259
+			if ($cachePageStatus) {
260 260
 				//current page URL
261 261
 				$url = $this->_currentUrl;
262 262
 				//Cache view Time to live in second
263 263
 				$viewCacheTtl = get_config('cache_ttl');
264
-				if (!empty($obj->view_cache_ttl)){
264
+				if (!empty($obj->view_cache_ttl)) {
265 265
 					$viewCacheTtl = $obj->view_cache_ttl;
266 266
 				}
267 267
 				//the cache handler instance
@@ -274,14 +274,14 @@  discard block
 block discarded – undo
274 274
 				
275 275
 				//get the cache information to prepare header to send to browser
276 276
 				$cacheInfo = $cacheInstance->getInfo($cacheKey);
277
-				if($cacheInfo){
277
+				if ($cacheInfo) {
278 278
 					$lastModified = $cacheInfo['mtime'];
279 279
 					$expire = $cacheInfo['expire'];
280 280
 					$maxAge = $expire - time();
281 281
 					self::setHeader('Pragma', 'public');
282 282
 					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
283
+					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
284
+					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');	
285 285
 				}
286 286
 			}
287 287
 			
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 			
294 294
 			//compress the output if is available
295 295
 			$type = null;
296
-			if (self::$_canCompressOutput){
296
+			if (self::$_canCompressOutput) {
297 297
 				$type = 'ob_gzhandler';
298 298
 			}
299 299
 			ob_start($type);
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 		/**
306 306
 		* Send the final page output to user if is cached
307 307
 		*/
308
-		public function renderFinalPageFromCache(&$cache){
308
+		public function renderFinalPageFromCache(&$cache) {
309 309
 			$logger = self::getLogger();
310 310
 			$url = $this->_currentUrl;					
311 311
 			//the current page cache key for identification
@@ -314,25 +314,25 @@  discard block
 block discarded – undo
314 314
 			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315 315
 			//get the cache information to prepare header to send to browser
316 316
 			$cacheInfo = $cache->getInfo($pageCacheKey);
317
-			if($cacheInfo){
317
+			if ($cacheInfo) {
318 318
 				$lastModified = $cacheInfo['mtime'];
319 319
 				$expire = $cacheInfo['expire'];
320 320
 				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
321 321
 				self::setHeader('Pragma', 'public');
322 322
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
323
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
324
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
325
+				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
326 326
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327 327
 					self::sendHeaders(304);
328 328
 					return;
329 329
 				}
330
-				else{
330
+				else {
331 331
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332 332
 					self::sendHeaders(200);
333 333
 					//get the cache content
334 334
 					$content = $cache->get($pageCacheKey);
335
-					if($content){
335
+					if ($content) {
336 336
 						$logger->info('The page content for the URL [' . $url . '] already cached just display it');
337 337
 						//load benchmark class
338 338
 						$benchmark = & class_loader('Benchmark');
@@ -345,17 +345,17 @@  discard block
 block discarded – undo
345 345
 						
346 346
 						///display the final output
347 347
 						//compress the output if is available
348
-						if (self::$_canCompressOutput){
348
+						if (self::$_canCompressOutput) {
349 349
 							ob_start('ob_gzhandler');
350 350
 						}
351
-						else{
351
+						else {
352 352
 							ob_start();
353 353
 						}
354 354
 						echo $content;
355 355
 						ob_end_flush();
356 356
 						return;
357 357
 					}
358
-					else{
358
+					else {
359 359
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360 360
 						$cache->delete($pageCacheKey);
361 361
 					}
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		* Get the final page to be rendered
368 368
 		* @return string
369 369
 		*/
370
-		public function getFinalPageRendered(){
370
+		public function getFinalPageRendered() {
371 371
 			return $this->_pageRender;
372 372
 		}
373 373
 
@@ -375,14 +375,14 @@  discard block
 block discarded – undo
375 375
 		 * Send the HTTP 404 error if can not found the 
376 376
 		 * routing information for the current request
377 377
 		 */
378
-		public static function send404(){
378
+		public static function send404() {
379 379
 			/********* for logs **************/
380 380
 			//can't use $obj = & get_instance()  here because the global super object will be available until
381 381
 			//the main controller is loaded even for Loader::library('xxxx');
382 382
 			$logger = self::getLogger();
383
-			$request =& class_loader('Request', 'classes');
384
-			$userAgent =& class_loader('Browser');
385
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
383
+			$request = & class_loader('Request', 'classes');
384
+			$userAgent = & class_loader('Browser');
385
+			$browser = $userAgent->getPlatform() . ', ' . $userAgent->getBrowser() . ' ' . $userAgent->getVersion();
386 386
 			
387 387
 			//here can't use Loader::functions just include the helper manually
388 388
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
@@ -392,12 +392,12 @@  discard block
 block discarded – undo
392 392
 			$logger->error($str);
393 393
 			/***********************************/
394 394
 			$path = CORE_VIEWS_PATH . '404.php';
395
-			if(file_exists($path)){
395
+			if (file_exists($path)) {
396 396
 				//compress the output if is available
397
-				if (self::$_canCompressOutput){
397
+				if (self::$_canCompressOutput) {
398 398
 					ob_start('ob_gzhandler');
399 399
 				}
400
-				else{
400
+				else {
401 401
 					ob_start();
402 402
 				}
403 403
 				require_once $path;
@@ -405,8 +405,8 @@  discard block
 block discarded – undo
405 405
 				self::sendHeaders(404);
406 406
 				echo $output;
407 407
 			}
408
-			else{
409
-				show_error('The 404 view [' .$path. '] does not exist');
408
+			else {
409
+				show_error('The 404 view [' . $path . '] does not exist');
410 410
 			}
411 411
 		}
412 412
 
@@ -414,14 +414,14 @@  discard block
 block discarded – undo
414 414
 		 * Display the error to user
415 415
 		 * @param  array  $data the error information
416 416
 		 */
417
-		public static function sendError(array $data = array()){
417
+		public static function sendError(array $data = array()) {
418 418
 			$path = CORE_VIEWS_PATH . 'errors.php';
419
-			if(file_exists($path)){
419
+			if (file_exists($path)) {
420 420
 				//compress the output if exists
421
-				if (self::$_canCompressOutput){
421
+				if (self::$_canCompressOutput) {
422 422
 					ob_start('ob_gzhandler');
423 423
 				}
424
-				else{
424
+				else {
425 425
 					ob_start();
426 426
 				}
427 427
 				extract($data);
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 				self::sendHeaders(503);
431 431
 				echo $output;
432 432
 			}
433
-			else{
433
+			else {
434 434
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435 435
 				set_http_status_header(503);
436 436
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Braces   +10 added lines, -20 removed lines patch added patch discarded remove patch
@@ -152,8 +152,7 @@  discard block
 block discarded – undo
152 152
 			if(! headers_sent()){
153 153
 				header('Location: '.$url);
154 154
 				exit;
155
-			}
156
-			else{
155
+			} else{
157 156
 				echo '<script>
158 157
 						location.href = "'.$url.'";
159 158
 					</script>';
@@ -202,12 +201,10 @@  discard block
 block discarded – undo
202 201
 					if($moduleViewPath){
203 202
 						$path = $moduleViewPath;
204 203
 						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
-					}
206
-					else{
204
+					} else{
207 205
 						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208 206
 					}
209
-				}
210
-				else{
207
+				} else{
211 208
 					$logger->info('The current request does not use module using the default location.');
212 209
 				}
213 210
 			}
@@ -326,8 +323,7 @@  discard block
 block discarded – undo
326 323
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327 324
 					self::sendHeaders(304);
328 325
 					return;
329
-				}
330
-				else{
326
+				} else{
331 327
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332 328
 					self::sendHeaders(200);
333 329
 					//get the cache content
@@ -347,15 +343,13 @@  discard block
 block discarded – undo
347 343
 						//compress the output if is available
348 344
 						if (self::$_canCompressOutput){
349 345
 							ob_start('ob_gzhandler');
350
-						}
351
-						else{
346
+						} else{
352 347
 							ob_start();
353 348
 						}
354 349
 						echo $content;
355 350
 						ob_end_flush();
356 351
 						return;
357
-					}
358
-					else{
352
+					} else{
359 353
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360 354
 						$cache->delete($pageCacheKey);
361 355
 					}
@@ -396,16 +390,14 @@  discard block
 block discarded – undo
396 390
 				//compress the output if is available
397 391
 				if (self::$_canCompressOutput){
398 392
 					ob_start('ob_gzhandler');
399
-				}
400
-				else{
393
+				} else{
401 394
 					ob_start();
402 395
 				}
403 396
 				require_once $path;
404 397
 				$output = ob_get_clean();
405 398
 				self::sendHeaders(404);
406 399
 				echo $output;
407
-			}
408
-			else{
400
+			} else{
409 401
 				show_error('The 404 view [' .$path. '] does not exist');
410 402
 			}
411 403
 		}
@@ -420,8 +412,7 @@  discard block
 block discarded – undo
420 412
 				//compress the output if exists
421 413
 				if (self::$_canCompressOutput){
422 414
 					ob_start('ob_gzhandler');
423
-				}
424
-				else{
415
+				} else{
425 416
 					ob_start();
426 417
 				}
427 418
 				extract($data);
@@ -429,8 +420,7 @@  discard block
 block discarded – undo
429 420
 				$output = ob_get_clean();
430 421
 				self::sendHeaders(503);
431 422
 				echo $output;
432
-			}
433
-			else{
423
+			} else{
434 424
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435 425
 				set_http_status_header(503);
436 426
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Indentation   +400 added lines, -400 removed lines patch added patch discarded remove patch
@@ -1,439 +1,439 @@
 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
-			$this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
-					. (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
65
+        /**
66
+         * Construct new response instance
67
+         */
68
+        public function __construct(){
69
+            $this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
+                    . (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
71 71
 					
72
-			$this->_currentUrlCacheKey = md5($this->_currentUrl);
72
+            $this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
74
-			self::$_canCompressOutput = get_config('compress_output')
75
-										  && isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
76
-										  && stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false 
77
-										  && extension_loaded('zlib')
78
-										  && (bool) ini_get('zlib.output_compression') === false;
79
-		}
74
+            self::$_canCompressOutput = get_config('compress_output')
75
+                                          && isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
76
+                                          && stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false 
77
+                                          && extension_loaded('zlib')
78
+                                          && (bool) ini_get('zlib.output_compression') === false;
79
+        }
80 80
 
81
-		/**
82
-		 * Get the logger singleton instance
83
-		 * @return Log the logger instance
84
-		 */
85
-		private static function getLogger(){
86
-			if(self::$logger == null){
87
-				self::$logger[0] =& class_loader('Log', 'classes');
88
-				self::$logger[0]->setLogger('Library::Response');
89
-			}
90
-			return self::$logger[0];
91
-		}
81
+        /**
82
+         * Get the logger singleton instance
83
+         * @return Log the logger instance
84
+         */
85
+        private static function getLogger(){
86
+            if(self::$logger == null){
87
+                self::$logger[0] =& class_loader('Log', 'classes');
88
+                self::$logger[0]->setLogger('Library::Response');
89
+            }
90
+            return self::$logger[0];
91
+        }
92 92
 
93
-		/**
94
-		 * Send the HTTP Response headers
95
-		 * @param  integer $httpCode the HTTP status code
96
-		 * @param  array   $headers   the additional headers to add to the existing headers list
97
-		 */
98
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
99
-			set_http_status_header($httpCode);
100
-			self::setHeaders($headers);
101
-			if(! headers_sent()){
102
-				foreach(self::getHeaders() as $key => $value){
103
-					header($key .': '.$value);
104
-				}
105
-			}
106
-		}
93
+        /**
94
+         * Send the HTTP Response headers
95
+         * @param  integer $httpCode the HTTP status code
96
+         * @param  array   $headers   the additional headers to add to the existing headers list
97
+         */
98
+        public static function sendHeaders($httpCode = 200, array $headers = array()){
99
+            set_http_status_header($httpCode);
100
+            self::setHeaders($headers);
101
+            if(! headers_sent()){
102
+                foreach(self::getHeaders() as $key => $value){
103
+                    header($key .': '.$value);
104
+                }
105
+            }
106
+        }
107 107
 
108
-		/**
109
-		 * Get the list of the headers
110
-		 * @return array the headers list
111
-		 */
112
-		public static function getHeaders(){
113
-			return self::$headers;
114
-		}
108
+        /**
109
+         * Get the list of the headers
110
+         * @return array the headers list
111
+         */
112
+        public static function getHeaders(){
113
+            return self::$headers;
114
+        }
115 115
 
116
-		/**
117
-		 * Get the header value for the given name
118
-		 * @param  string $name the header name
119
-		 * @return string       the header value
120
-		 */
121
-		public static function getHeader($name){
122
-			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123
-		}
116
+        /**
117
+         * Get the header value for the given name
118
+         * @param  string $name the header name
119
+         * @return string       the header value
120
+         */
121
+        public static function getHeader($name){
122
+            return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123
+        }
124 124
 
125 125
 
126
-		/**
127
-		 * Set the header value for the specified name
128
-		 * @param string $name  the header name
129
-		 * @param string $value the header value to be set
130
-		 */
131
-		public static function setHeader($name, $value){
132
-			self::$headers[$name] = $value;
133
-		}
126
+        /**
127
+         * Set the header value for the specified name
128
+         * @param string $name  the header name
129
+         * @param string $value the header value to be set
130
+         */
131
+        public static function setHeader($name, $value){
132
+            self::$headers[$name] = $value;
133
+        }
134 134
 
135
-		/**
136
-		 * Set the headers using array
137
-		 * @param array $headers the list of the headers to set. 
138
-		 * Note: this will merge with the existing headers
139
-		 */
140
-		public static function setHeaders(array $headers){
141
-			self::$headers = array_merge(self::getHeaders(), $headers);
142
-		}
135
+        /**
136
+         * Set the headers using array
137
+         * @param array $headers the list of the headers to set. 
138
+         * Note: this will merge with the existing headers
139
+         */
140
+        public static function setHeaders(array $headers){
141
+            self::$headers = array_merge(self::getHeaders(), $headers);
142
+        }
143 143
 		
144
-		/**
145
-		 * Redirect user in the specified page
146
-		 * @param  string $path the URL or URI to be redirect to
147
-		 */
148
-		public static function redirect($path = ''){
149
-			$logger = self::getLogger();
150
-			$url = Url::site_url($path);
151
-			$logger->info('Redirect to URL [' .$url. ']');
152
-			if(! headers_sent()){
153
-				header('Location: '.$url);
154
-				exit;
155
-			}
156
-			else{
157
-				echo '<script>
144
+        /**
145
+         * Redirect user in the specified page
146
+         * @param  string $path the URL or URI to be redirect to
147
+         */
148
+        public static function redirect($path = ''){
149
+            $logger = self::getLogger();
150
+            $url = Url::site_url($path);
151
+            $logger->info('Redirect to URL [' .$url. ']');
152
+            if(! headers_sent()){
153
+                header('Location: '.$url);
154
+                exit;
155
+            }
156
+            else{
157
+                echo '<script>
158 158
 						location.href = "'.$url.'";
159 159
 					</script>';
160
-			}
161
-		}
160
+            }
161
+        }
162 162
 
163
-		/**
164
-		 * Render the view to display later or return the content
165
-		 * @param  string  $view   the view name or path
166
-		 * @param  array|object   $data   the variable data to use in the view
167
-		 * @param  boolean $return whether to return the view generated content or display it directly
168
-		 * @return void|string          if $return is true will return the view content otherwise
169
-		 * will display the view content.
170
-		 */
171
-		public function render($view, $data = null, $return = false){
172
-			$logger = self::getLogger();
173
-			//convert data to an array
174
-			$data = ! is_array($data) ? (array) $data : $data;
175
-			$view = str_ireplace('.php', '', $view);
176
-			$view = trim($view, '/\\');
177
-			$viewFile = $view . '.php';
178
-			$path = APPS_VIEWS_PATH . $viewFile;
163
+        /**
164
+         * Render the view to display later or return the content
165
+         * @param  string  $view   the view name or path
166
+         * @param  array|object   $data   the variable data to use in the view
167
+         * @param  boolean $return whether to return the view generated content or display it directly
168
+         * @return void|string          if $return is true will return the view content otherwise
169
+         * will display the view content.
170
+         */
171
+        public function render($view, $data = null, $return = false){
172
+            $logger = self::getLogger();
173
+            //convert data to an array
174
+            $data = ! is_array($data) ? (array) $data : $data;
175
+            $view = str_ireplace('.php', '', $view);
176
+            $view = trim($view, '/\\');
177
+            $viewFile = $view . '.php';
178
+            $path = APPS_VIEWS_PATH . $viewFile;
179 179
 			
180
-			//super instance
181
-			$obj = & get_instance();
180
+            //super instance
181
+            $obj = & get_instance();
182 182
 			
183
-			if(Module::hasModule()){
184
-				//check in module first
185
-				$logger->debug('Checking the view [' . $view . '] from module list ...');
186
-				$mod = null;
187
-				//check if the request class contains module name
188
-				if(strpos($view, '/') !== false){
189
-					$viewPath = explode('/', $view);
190
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
191
-						$mod = $viewPath[0];
192
-						array_shift($viewPath);
193
-						$view = implode('/', $viewPath);
194
-						$viewFile = $view . '.php';
195
-					}
196
-				}
197
-				if(! $mod && !empty($obj->moduleName)){
198
-					$mod = $obj->moduleName;
199
-				}
200
-				if($mod){
201
-					$moduleViewPath = Module::findViewFullPath($view, $mod);
202
-					if($moduleViewPath){
203
-						$path = $moduleViewPath;
204
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
-					}
206
-					else{
207
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208
-					}
209
-				}
210
-				else{
211
-					$logger->info('The current request does not use module using the default location.');
212
-				}
213
-			}
214
-			$logger->info('The view file path to be loaded is [' . $path . ']');
215
-			$found = false;
216
-			if(file_exists($path)){
217
-				foreach(get_object_vars($obj) as $key => $value){
218
-					if(! isset($this->{$key})){
219
-						$this->{$key} = & $obj->{$key};
220
-					}
221
-				}
222
-				ob_start();
223
-				extract($data);
224
-				//need use require() instead of require_once because can load this view many time
225
-				require $path;
226
-				$content = ob_get_clean();
227
-				if($return){
228
-					return $content;
229
-				}
230
-				$this->_pageRender .= $content;
231
-				$found = true;
232
-			}
233
-			if(! $found){
234
-				show_error('Unable to find view [' .$view . ']');
235
-			}
236
-		}
183
+            if(Module::hasModule()){
184
+                //check in module first
185
+                $logger->debug('Checking the view [' . $view . '] from module list ...');
186
+                $mod = null;
187
+                //check if the request class contains module name
188
+                if(strpos($view, '/') !== false){
189
+                    $viewPath = explode('/', $view);
190
+                    if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
191
+                        $mod = $viewPath[0];
192
+                        array_shift($viewPath);
193
+                        $view = implode('/', $viewPath);
194
+                        $viewFile = $view . '.php';
195
+                    }
196
+                }
197
+                if(! $mod && !empty($obj->moduleName)){
198
+                    $mod = $obj->moduleName;
199
+                }
200
+                if($mod){
201
+                    $moduleViewPath = Module::findViewFullPath($view, $mod);
202
+                    if($moduleViewPath){
203
+                        $path = $moduleViewPath;
204
+                        $logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
+                    }
206
+                    else{
207
+                        $logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208
+                    }
209
+                }
210
+                else{
211
+                    $logger->info('The current request does not use module using the default location.');
212
+                }
213
+            }
214
+            $logger->info('The view file path to be loaded is [' . $path . ']');
215
+            $found = false;
216
+            if(file_exists($path)){
217
+                foreach(get_object_vars($obj) as $key => $value){
218
+                    if(! isset($this->{$key})){
219
+                        $this->{$key} = & $obj->{$key};
220
+                    }
221
+                }
222
+                ob_start();
223
+                extract($data);
224
+                //need use require() instead of require_once because can load this view many time
225
+                require $path;
226
+                $content = ob_get_clean();
227
+                if($return){
228
+                    return $content;
229
+                }
230
+                $this->_pageRender .= $content;
231
+                $found = true;
232
+            }
233
+            if(! $found){
234
+                show_error('Unable to find view [' .$view . ']');
235
+            }
236
+        }
237 237
 		
238
-		/**
239
-		* Send the final page output to user
240
-		*/
241
-		public function renderFinalPage(){
242
-			$logger = self::getLogger();
243
-			$obj = & get_instance();
244
-			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245
-			$dispatcher = $obj->eventdispatcher;
246
-			$content = $this->_pageRender;
247
-			if(! $content){
248
-				$logger->warning('The final view content is empty.');
249
-				return;
250
-			}
251
-			//dispatch
252
-			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
-			$content = ! empty($event->payload) ? $event->payload : null;
254
-			if(empty($content)){
255
-				$logger->warning('The view content is empty after dispatch to event listeners.');
256
-			}
238
+        /**
239
+         * Send the final page output to user
240
+         */
241
+        public function renderFinalPage(){
242
+            $logger = self::getLogger();
243
+            $obj = & get_instance();
244
+            $cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245
+            $dispatcher = $obj->eventdispatcher;
246
+            $content = $this->_pageRender;
247
+            if(! $content){
248
+                $logger->warning('The final view content is empty.');
249
+                return;
250
+            }
251
+            //dispatch
252
+            $event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
+            $content = ! empty($event->payload) ? $event->payload : null;
254
+            if(empty($content)){
255
+                $logger->warning('The view content is empty after dispatch to event listeners.');
256
+            }
257 257
 			
258
-			//check whether need save the page into cache.
259
-			if($cachePageStatus){
260
-				//current page URL
261
-				$url = $this->_currentUrl;
262
-				//Cache view Time to live in second
263
-				$viewCacheTtl = get_config('cache_ttl');
264
-				if (!empty($obj->view_cache_ttl)){
265
-					$viewCacheTtl = $obj->view_cache_ttl;
266
-				}
267
-				//the cache handler instance
268
-				$cacheInstance = $obj->cache;
269
-				//the current page cache key for identification
270
-				$cacheKey = $this->_currentUrlCacheKey;
258
+            //check whether need save the page into cache.
259
+            if($cachePageStatus){
260
+                //current page URL
261
+                $url = $this->_currentUrl;
262
+                //Cache view Time to live in second
263
+                $viewCacheTtl = get_config('cache_ttl');
264
+                if (!empty($obj->view_cache_ttl)){
265
+                    $viewCacheTtl = $obj->view_cache_ttl;
266
+                }
267
+                //the cache handler instance
268
+                $cacheInstance = $obj->cache;
269
+                //the current page cache key for identification
270
+                $cacheKey = $this->_currentUrlCacheKey;
271 271
 				
272
-				$logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
273
-				$cacheInstance->set($cacheKey, $content, $viewCacheTtl);
272
+                $logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
273
+                $cacheInstance->set($cacheKey, $content, $viewCacheTtl);
274 274
 				
275
-				//get the cache information to prepare header to send to browser
276
-				$cacheInfo = $cacheInstance->getInfo($cacheKey);
277
-				if($cacheInfo){
278
-					$lastModified = $cacheInfo['mtime'];
279
-					$expire = $cacheInfo['expire'];
280
-					$maxAge = $expire - time();
281
-					self::setHeader('Pragma', 'public');
282
-					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
285
-				}
286
-			}
275
+                //get the cache information to prepare header to send to browser
276
+                $cacheInfo = $cacheInstance->getInfo($cacheKey);
277
+                if($cacheInfo){
278
+                    $lastModified = $cacheInfo['mtime'];
279
+                    $expire = $cacheInfo['expire'];
280
+                    $maxAge = $expire - time();
281
+                    self::setHeader('Pragma', 'public');
282
+                    self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
+                    self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
+                    self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
285
+                }
286
+            }
287 287
 			
288
-			// Parse out the elapsed time and memory usage,
289
-			// then swap the pseudo-variables with the data
290
-			$elapsedTime = $obj->benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
291
-			$memoryUsage	= round($obj->benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
292
-			$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
288
+            // Parse out the elapsed time and memory usage,
289
+            // then swap the pseudo-variables with the data
290
+            $elapsedTime = $obj->benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
291
+            $memoryUsage	= round($obj->benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
292
+            $content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
293 293
 			
294
-			//compress the output if is available
295
-			$type = null;
296
-			if (self::$_canCompressOutput){
297
-				$type = 'ob_gzhandler';
298
-			}
299
-			ob_start($type);
300
-			self::sendHeaders(200);
301
-			echo $content;
302
-			ob_end_flush();
303
-		}
294
+            //compress the output if is available
295
+            $type = null;
296
+            if (self::$_canCompressOutput){
297
+                $type = 'ob_gzhandler';
298
+            }
299
+            ob_start($type);
300
+            self::sendHeaders(200);
301
+            echo $content;
302
+            ob_end_flush();
303
+        }
304 304
 		
305
-		/**
306
-		* Send the final page output to user if is cached
307
-		*/
308
-		public function renderFinalPageFromCache(&$cache){
309
-			$logger = self::getLogger();
310
-			$url = $this->_currentUrl;					
311
-			//the current page cache key for identification
312
-			$pageCacheKey = $this->_currentUrlCacheKey;
305
+        /**
306
+         * Send the final page output to user if is cached
307
+         */
308
+        public function renderFinalPageFromCache(&$cache){
309
+            $logger = self::getLogger();
310
+            $url = $this->_currentUrl;					
311
+            //the current page cache key for identification
312
+            $pageCacheKey = $this->_currentUrlCacheKey;
313 313
 			
314
-			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315
-			//get the cache information to prepare header to send to browser
316
-			$cacheInfo = $cache->getInfo($pageCacheKey);
317
-			if($cacheInfo){
318
-				$lastModified = $cacheInfo['mtime'];
319
-				$expire = $cacheInfo['expire'];
320
-				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
321
-				self::setHeader('Pragma', 'public');
322
-				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
326
-					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327
-					self::sendHeaders(304);
328
-					return;
329
-				}
330
-				else{
331
-					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332
-					self::sendHeaders(200);
333
-					//get the cache content
334
-					$content = $cache->get($pageCacheKey);
335
-					if($content){
336
-						$logger->info('The page content for the URL [' . $url . '] already cached just display it');
337
-						//load benchmark class
338
-						$benchmark = & class_loader('Benchmark');
314
+            $logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315
+            //get the cache information to prepare header to send to browser
316
+            $cacheInfo = $cache->getInfo($pageCacheKey);
317
+            if($cacheInfo){
318
+                $lastModified = $cacheInfo['mtime'];
319
+                $expire = $cacheInfo['expire'];
320
+                $maxAge = $expire - $_SERVER['REQUEST_TIME'];
321
+                self::setHeader('Pragma', 'public');
322
+                self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
+                self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
+                self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
+                if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
326
+                    $logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327
+                    self::sendHeaders(304);
328
+                    return;
329
+                }
330
+                else{
331
+                    $logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332
+                    self::sendHeaders(200);
333
+                    //get the cache content
334
+                    $content = $cache->get($pageCacheKey);
335
+                    if($content){
336
+                        $logger->info('The page content for the URL [' . $url . '] already cached just display it');
337
+                        //load benchmark class
338
+                        $benchmark = & class_loader('Benchmark');
339 339
 						
340
-						// Parse out the elapsed time and memory usage,
341
-						// then swap the pseudo-variables with the data
342
-						$elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
343
-						$memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
344
-						$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
340
+                        // Parse out the elapsed time and memory usage,
341
+                        // then swap the pseudo-variables with the data
342
+                        $elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
343
+                        $memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
344
+                        $content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
345 345
 						
346
-						///display the final output
347
-						//compress the output if is available
348
-						if (self::$_canCompressOutput){
349
-							ob_start('ob_gzhandler');
350
-						}
351
-						else{
352
-							ob_start();
353
-						}
354
-						echo $content;
355
-						ob_end_flush();
356
-						return;
357
-					}
358
-					else{
359
-						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360
-						$cache->delete($pageCacheKey);
361
-					}
362
-				}
363
-			}
364
-		}
346
+                        ///display the final output
347
+                        //compress the output if is available
348
+                        if (self::$_canCompressOutput){
349
+                            ob_start('ob_gzhandler');
350
+                        }
351
+                        else{
352
+                            ob_start();
353
+                        }
354
+                        echo $content;
355
+                        ob_end_flush();
356
+                        return;
357
+                    }
358
+                    else{
359
+                        $logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360
+                        $cache->delete($pageCacheKey);
361
+                    }
362
+                }
363
+            }
364
+        }
365 365
 		
366
-		/**
367
-		* Get the final page to be rendered
368
-		* @return string
369
-		*/
370
-		public function getFinalPageRendered(){
371
-			return $this->_pageRender;
372
-		}
366
+        /**
367
+         * Get the final page to be rendered
368
+         * @return string
369
+         */
370
+        public function getFinalPageRendered(){
371
+            return $this->_pageRender;
372
+        }
373 373
 
374
-		/**
375
-		 * Send the HTTP 404 error if can not found the 
376
-		 * routing information for the current request
377
-		 */
378
-		public static function send404(){
379
-			/********* for logs **************/
380
-			//can't use $obj = & get_instance()  here because the global super object will be available until
381
-			//the main controller is loaded even for Loader::library('xxxx');
382
-			$logger = self::getLogger();
383
-			$request =& class_loader('Request', 'classes');
384
-			$userAgent =& class_loader('Browser');
385
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
374
+        /**
375
+         * Send the HTTP 404 error if can not found the 
376
+         * routing information for the current request
377
+         */
378
+        public static function send404(){
379
+            /********* for logs **************/
380
+            //can't use $obj = & get_instance()  here because the global super object will be available until
381
+            //the main controller is loaded even for Loader::library('xxxx');
382
+            $logger = self::getLogger();
383
+            $request =& class_loader('Request', 'classes');
384
+            $userAgent =& class_loader('Browser');
385
+            $browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
386 386
 			
387
-			//here can't use Loader::functions just include the helper manually
388
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
387
+            //here can't use Loader::functions just include the helper manually
388
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
389 389
 
390
-			$str = '[404 page not found] : ';
391
-			$str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
392
-			$logger->error($str);
393
-			/***********************************/
394
-			$path = CORE_VIEWS_PATH . '404.php';
395
-			if(file_exists($path)){
396
-				//compress the output if is available
397
-				if (self::$_canCompressOutput){
398
-					ob_start('ob_gzhandler');
399
-				}
400
-				else{
401
-					ob_start();
402
-				}
403
-				require_once $path;
404
-				$output = ob_get_clean();
405
-				self::sendHeaders(404);
406
-				echo $output;
407
-			}
408
-			else{
409
-				show_error('The 404 view [' .$path. '] does not exist');
410
-			}
411
-		}
390
+            $str = '[404 page not found] : ';
391
+            $str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
392
+            $logger->error($str);
393
+            /***********************************/
394
+            $path = CORE_VIEWS_PATH . '404.php';
395
+            if(file_exists($path)){
396
+                //compress the output if is available
397
+                if (self::$_canCompressOutput){
398
+                    ob_start('ob_gzhandler');
399
+                }
400
+                else{
401
+                    ob_start();
402
+                }
403
+                require_once $path;
404
+                $output = ob_get_clean();
405
+                self::sendHeaders(404);
406
+                echo $output;
407
+            }
408
+            else{
409
+                show_error('The 404 view [' .$path. '] does not exist');
410
+            }
411
+        }
412 412
 
413
-		/**
414
-		 * Display the error to user
415
-		 * @param  array  $data the error information
416
-		 */
417
-		public static function sendError(array $data = array()){
418
-			$path = CORE_VIEWS_PATH . 'errors.php';
419
-			if(file_exists($path)){
420
-				//compress the output if exists
421
-				if (self::$_canCompressOutput){
422
-					ob_start('ob_gzhandler');
423
-				}
424
-				else{
425
-					ob_start();
426
-				}
427
-				extract($data);
428
-				require_once $path;
429
-				$output = ob_get_clean();
430
-				self::sendHeaders(503);
431
-				echo $output;
432
-			}
433
-			else{
434
-				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435
-				set_http_status_header(503);
436
-				echo 'The error view [' . $path . '] does not exist';
437
-			}
438
-		}
439
-	}
413
+        /**
414
+         * Display the error to user
415
+         * @param  array  $data the error information
416
+         */
417
+        public static function sendError(array $data = array()){
418
+            $path = CORE_VIEWS_PATH . 'errors.php';
419
+            if(file_exists($path)){
420
+                //compress the output if exists
421
+                if (self::$_canCompressOutput){
422
+                    ob_start('ob_gzhandler');
423
+                }
424
+                else{
425
+                    ob_start();
426
+                }
427
+                extract($data);
428
+                require_once $path;
429
+                $output = ob_get_clean();
430
+                self::sendHeaders(503);
431
+                echo $output;
432
+            }
433
+            else{
434
+                //can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435
+                set_http_status_header(503);
436
+                echo 'The error view [' . $path . '] does not exist';
437
+            }
438
+        }
439
+    }
Please login to merge, or discard this patch.
core/classes/Module.php 3 patches
Spacing   +76 added lines, -76 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 Module{
27
+	class Module {
28 28
 		
29 29
 		/**
30 30
 		 * list of loaded module
@@ -42,9 +42,9 @@  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){
47
-				self::$logger[0] =& class_loader('Log', 'classes');
45
+		private static function getLogger() {
46
+			if (self::$logger == null) {
47
+				self::$logger[0] = & class_loader('Log', 'classes');
48 48
 				self::$logger[0]->setLogger('Library::Module');
49 49
 			}
50 50
 			return self::$logger[0];
@@ -53,24 +53,24 @@  discard block
 block discarded – undo
53 53
 		/**
54 54
 		 * Initialise the module list by scanning the directory MODULE_PATH
55 55
 		 */
56
-		public function init(){
56
+		public function init() {
57 57
 			$logger = self::getLogger();
58 58
 			$logger->debug('Check if the application contains the modules ...');
59 59
 			$moduleDir = opendir(MODULE_PATH);
60
-			if(is_resource($moduleDir)){
61
-				while(($module = readdir($moduleDir)) !== false){
62
-					if(preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
60
+			if (is_resource($moduleDir)) {
61
+				while (($module = readdir($moduleDir)) !== false) {
62
+					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)) {
63 63
 						self::$list[] = $module;
64 64
 					}
65
-					else{
66
-						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
65
+					else {
66
+						$logger->info('Skipping [' . $module . '], may be this is not a directory or does not exists or is invalid name');
67 67
 					}
68 68
 				}
69 69
 				closedir($moduleDir);
70 70
 			}
71 71
 			ksort(self::$list);
72 72
 			
73
-			if(self::hasModule()){
73
+			if (self::hasModule()) {
74 74
 				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
75 75
 			}
76 76
 		}
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 		 * Get the list of the custom autoload configuration from module if exists
80 80
 		 * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
81 81
 		 */
82
-		public static function getModulesAutoloadConfig(){
82
+		public static function getModulesAutoloadConfig() {
83 83
 			$logger = self::getLogger();
84
-			if(! self::hasModule()){
84
+			if (!self::hasModule()) {
85 85
 				$logger->info('No module was loaded skipping.');
86 86
 				return false;
87 87
 			}
@@ -94,10 +94,10 @@  discard block
 block discarded – undo
94 94
 			
95 95
 			foreach (self::$list as $module) {
96 96
 				$file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
97
-				if(file_exists($file)){
97
+				if (file_exists($file)) {
98 98
 					$autoload = array();
99 99
 					require_once $file;
100
-					if(! empty($autoload) && is_array($autoload)){
100
+					if (!empty($autoload) && is_array($autoload)) {
101 101
 						$autoloads = array_merge_recursive($autoloads, $autoload);
102 102
 						unset($autoload);
103 103
 					}
@@ -110,19 +110,19 @@  discard block
 block discarded – undo
110 110
 		 * Get the list of the custom routes configuration from module if exists
111 111
 		 * @return array|boolean the routes list or false if no module contains the routes configuration
112 112
 		 */
113
-		public static function getModulesRoutes(){
113
+		public static function getModulesRoutes() {
114 114
 			$logger = self::getLogger();
115
-			if(! self::hasModule()){
115
+			if (!self::hasModule()) {
116 116
 				$logger->info('No module was loaded skipping.');
117 117
 				return false;
118 118
 			}
119 119
 			$routes = array();
120 120
 			foreach (self::$list as $module) {
121 121
 				$file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
122
-				if(file_exists($file)){
122
+				if (file_exists($file)) {
123 123
 					$route = array();
124 124
 					require_once $file;
125
-					if(! empty($route) && is_array($route)){
125
+					if (!empty($route) && is_array($route)) {
126 126
 						$routes = array_merge($routes, $route);
127 127
 						unset($route);
128 128
 					}
@@ -138,23 +138,23 @@  discard block
 block discarded – undo
138 138
 		 * @param  string $module  the module name
139 139
 		 * @return boolean|string  false or null if no module have this controller, path the full path of the controller
140 140
 		 */
141
-		public static function findControllerFullPath($class, $module = null){
141
+		public static function findControllerFullPath($class, $module = null) {
142 142
 			$logger = self::getLogger();
143
-			if(! self::hasModule()){
143
+			if (!self::hasModule()) {
144 144
 				$logger->info('No module was loaded skiping.');
145 145
 				return false;
146 146
 			}
147 147
 			$class = str_ireplace('.php', '', $class);
148 148
 			$class = ucfirst($class);
149
-			$classFile = $class.'.php';
150
-			$logger->debug('Checking the controller [' . $class . '] in module [' .$module. '] ...');
149
+			$classFile = $class . '.php';
150
+			$logger->debug('Checking the controller [' . $class . '] in module [' . $module . '] ...');
151 151
 			$filePath = MODULE_PATH . $module . DS . 'controllers' . DS . $classFile;
152
-			if(file_exists($filePath)){
153
-				$logger->info('Found controller [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
152
+			if (file_exists($filePath)) {
153
+				$logger->info('Found controller [' . $class . '] in module [' . $module . '], the file path is [' . $filePath . ']');
154 154
 				return $filePath;
155 155
 			}
156
-			else{
157
-				$logger->info('Controller [' . $class . '] does not exist in the module [' .$module. ']');
156
+			else {
157
+				$logger->info('Controller [' . $class . '] does not exist in the module [' . $module . ']');
158 158
 				return false;
159 159
 			}
160 160
 		}
@@ -165,23 +165,23 @@  discard block
 block discarded – undo
165 165
 		 * @param string $module the module name
166 166
 		 * @return boolean|string  false or null if no module have this model, return the full path of this model
167 167
 		 */
168
-		public static function findModelFullPath($class, $module = null){
168
+		public static function findModelFullPath($class, $module = null) {
169 169
 			$logger = self::getLogger();
170
-			if(! self::hasModule()){
170
+			if (!self::hasModule()) {
171 171
 				$logger->info('No module was loaded skiping.');
172 172
 				return false;
173 173
 			}
174 174
 			$class = str_ireplace('.php', '', $class);
175 175
 			$class = ucfirst($class);
176
-			$classFile = $class.'.php';
177
-			$logger->debug('Checking model [' . $class . '] in module [' .$module. '] ...');
176
+			$classFile = $class . '.php';
177
+			$logger->debug('Checking model [' . $class . '] in module [' . $module . '] ...');
178 178
 			$filePath = MODULE_PATH . $module . DS . 'models' . DS . $classFile;
179
-			if(file_exists($filePath)){
180
-				$logger->info('Found model [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
179
+			if (file_exists($filePath)) {
180
+				$logger->info('Found model [' . $class . '] in module [' . $module . '], the file path is [' . $filePath . ']');
181 181
 				return $filePath;
182 182
 			}
183
-			else{
184
-				$logger->info('Model [' . $class . '] does not exist in the module [' .$module. ']');
183
+			else {
184
+				$logger->info('Model [' . $class . '] does not exist in the module [' . $module . ']');
185 185
 				return false;
186 186
 			}
187 187
 		}
@@ -192,22 +192,22 @@  discard block
 block discarded – undo
192 192
 		 * @param string $module the module name
193 193
 		 * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
194 194
 		 */
195
-		public static function findConfigFullPath($configuration, $module = null){
195
+		public static function findConfigFullPath($configuration, $module = null) {
196 196
 			$logger = self::getLogger();
197
-			if(! self::hasModule()){
197
+			if (!self::hasModule()) {
198 198
 				$logger->info('No module was loaded skiping.');
199 199
 				return false;
200 200
 			}
201 201
 			$configuration = str_ireplace('.php', '', $configuration);
202
-			$file = $configuration.'.php';
203
-			$logger->debug('Checking configuration [' . $configuration . '] in module [' .$module. '] ...');
202
+			$file = $configuration . '.php';
203
+			$logger->debug('Checking configuration [' . $configuration . '] in module [' . $module . '] ...');
204 204
 			$filePath = MODULE_PATH . $module . DS . 'config' . DS . $file;
205
-			if(file_exists($filePath)){
206
-				$logger->info('Found configuration [' . $configuration . '] in module [' .$module. '], the file path is [' .$filePath. ']');
205
+			if (file_exists($filePath)) {
206
+				$logger->info('Found configuration [' . $configuration . '] in module [' . $module . '], the file path is [' . $filePath . ']');
207 207
 				return $filePath;
208 208
 			}
209
-			else{
210
-				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' .$module. ']');
209
+			else {
210
+				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' . $module . ']');
211 211
 				return false;
212 212
 			}
213 213
 		}
@@ -218,23 +218,23 @@  discard block
 block discarded – undo
218 218
 		 * @param string $module the module name
219 219
 		 * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
220 220
 		 */
221
-		public static function findFunctionFullPath($helper, $module = null){
221
+		public static function findFunctionFullPath($helper, $module = null) {
222 222
 			$logger = self::getLogger();
223
-			if(! self::hasModule()){
223
+			if (!self::hasModule()) {
224 224
 				$logger->info('No module was loaded skiping.');
225 225
 				return false;
226 226
 			}
227 227
 			$helper = str_ireplace('.php', '', $helper);
228 228
 			$helper = str_ireplace('function_', '', $helper);
229
-			$file = 'function_'.$helper.'.php';
230
-			$logger->debug('Checking helper [' . $helper . '] in module [' .$module. '] ...');
229
+			$file = 'function_' . $helper . '.php';
230
+			$logger->debug('Checking helper [' . $helper . '] in module [' . $module . '] ...');
231 231
 			$filePath = MODULE_PATH . $module . DS . 'functions' . DS . $file;
232
-			if(file_exists($filePath)){
233
-				$logger->info('Found helper [' . $helper . '] in module [' .$module. '], the file path is [' .$filePath. ']');
232
+			if (file_exists($filePath)) {
233
+				$logger->info('Found helper [' . $helper . '] in module [' . $module . '], the file path is [' . $filePath . ']');
234 234
 				return $filePath;
235 235
 			}
236
-			else{
237
-				$logger->info('Helper [' . $helper . '] does not exist in the module [' .$module. ']');
236
+			else {
237
+				$logger->info('Helper [' . $helper . '] does not exist in the module [' . $module . ']');
238 238
 				return false;
239 239
 			}
240 240
 		}
@@ -246,22 +246,22 @@  discard block
 block discarded – undo
246 246
 		 * @param string $module the module name
247 247
 		 * @return boolean|string  false or null if no module have this library,  return the full path of this library
248 248
 		 */
249
-		public static function findLibraryFullPath($class, $module = null){
249
+		public static function findLibraryFullPath($class, $module = null) {
250 250
 			$logger = self::getLogger();
251
-			if(! self::hasModule()){
251
+			if (!self::hasModule()) {
252 252
 				$logger->info('No module was loaded skiping.');
253 253
 				return false;
254 254
 			}
255 255
 			$class = str_ireplace('.php', '', $class);
256
-			$file = $class.'.php';
257
-			$logger->debug('Checking library [' . $class . '] in module [' .$module. '] ...');
256
+			$file = $class . '.php';
257
+			$logger->debug('Checking library [' . $class . '] in module [' . $module . '] ...');
258 258
 			$filePath = MODULE_PATH . $module . DS . 'libraries' . DS . $file;
259
-			if(file_exists($filePath)){
260
-				$logger->info('Found library [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
259
+			if (file_exists($filePath)) {
260
+				$logger->info('Found library [' . $class . '] in module [' . $module . '], the file path is [' . $filePath . ']');
261 261
 				return $filePath;
262 262
 			}
263
-			else{
264
-				$logger->info('Library [' . $class . '] does not exist in the module [' .$module. ']');
263
+			else {
264
+				$logger->info('Library [' . $class . '] does not exist in the module [' . $module . ']');
265 265
 				return false;
266 266
 			}
267 267
 		}
@@ -273,9 +273,9 @@  discard block
 block discarded – undo
273 273
 		 * @param string $module the module name to check
274 274
 		 * @return boolean|string  false or null if no module have this view, path the full path of the view
275 275
 		 */
276
-		public static function findViewFullPath($view, $module = null){
276
+		public static function findViewFullPath($view, $module = null) {
277 277
 			$logger = self::getLogger();
278
-			if(! self::hasModule()){
278
+			if (!self::hasModule()) {
279 279
 				$logger->info('No module was loaded skiping.');
280 280
 				return false;
281 281
 			}
@@ -283,14 +283,14 @@  discard block
 block discarded – undo
283 283
 			$view = trim($view, '/\\');
284 284
 			$view = str_ireplace('/', DS, $view);
285 285
 			$viewFile = $view . '.php';
286
-			$logger->debug('Checking view [' . $view . '] in module [' .$module. '] ...');
286
+			$logger->debug('Checking view [' . $view . '] in module [' . $module . '] ...');
287 287
 			$filePath = MODULE_PATH . $module . DS . 'views' . DS . $viewFile;
288
-			if(file_exists($filePath)){
289
-				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$filePath. ']');
288
+			if (file_exists($filePath)) {
289
+				$logger->info('Found view [' . $view . '] in module [' . $module . '], the file path is [' . $filePath . ']');
290 290
 				return $filePath;
291 291
 			}
292
-			else{
293
-				$logger->info('View [' . $view . '] does not exist in the module [' .$module. ']');
292
+			else {
293
+				$logger->info('View [' . $view . '] does not exist in the module [' . $module . ']');
294 294
 				return false;
295 295
 			}
296 296
 		}
@@ -302,23 +302,23 @@  discard block
 block discarded – undo
302 302
 		 * @param string $appLang the application language like 'en', 'fr'
303 303
 		 * @return boolean|string  false or null if no module have this language,  return the full path of this language
304 304
 		 */
305
-		public static function findLanguageFullPath($language, $module = null, $appLang){
305
+		public static function findLanguageFullPath($language, $module = null, $appLang) {
306 306
 			$logger = self::getLogger();
307
-			if(! self::hasModule()){
307
+			if (!self::hasModule()) {
308 308
 				$logger->info('No module was loaded skiping.');
309 309
 				return false;
310 310
 			}
311 311
 			$language = str_ireplace('.php', '', $language);
312 312
 			$language = str_ireplace('lang_', '', $language);
313
-			$file = 'lang_'.$language.'.php';
314
-			$logger->debug('Checking language [' . $language . '] in module [' .$module. '] ...');
313
+			$file = 'lang_' . $language . '.php';
314
+			$logger->debug('Checking language [' . $language . '] in module [' . $module . '] ...');
315 315
 			$filePath = MODULE_PATH . $module . DS . 'lang' . DS . $appLang . DS . $file;
316
-			if(file_exists($filePath)){
317
-				$logger->info('Found language [' . $language . '] in module [' .$module. '], the file path is [' .$filePath. ']');
316
+			if (file_exists($filePath)) {
317
+				$logger->info('Found language [' . $language . '] in module [' . $module . '], the file path is [' . $filePath . ']');
318 318
 				return $filePath;
319 319
 			}
320
-			else{
321
-				$logger->info('Language [' . $language . '] does not exist in the module [' .$module. ']');
320
+			else {
321
+				$logger->info('Language [' . $language . '] does not exist in the module [' . $module . ']');
322 322
 				return false;
323 323
 			}
324 324
 		}
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 		 * Get the list of module loaded
328 328
 		 * @return array the module list
329 329
 		 */
330
-		public static function getModuleList(){
330
+		public static function getModuleList() {
331 331
 			return self::$list;
332 332
 		}
333 333
 
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
 		 * Check if the application has an module
336 336
 		 * @return boolean
337 337
 		 */
338
-		public static function hasModule(){
338
+		public static function hasModule() {
339 339
 			return !empty(self::$list);
340 340
 		}
341 341
 
Please login to merge, or discard this patch.
Braces   +8 added lines, -16 removed lines patch added patch discarded remove patch
@@ -61,8 +61,7 @@  discard block
 block discarded – undo
61 61
 				while(($module = readdir($moduleDir)) !== false){
62 62
 					if(preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
63 63
 						self::$list[] = $module;
64
-					}
65
-					else{
64
+					} else{
66 65
 						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
67 66
 					}
68 67
 				}
@@ -152,8 +151,7 @@  discard block
 block discarded – undo
152 151
 			if(file_exists($filePath)){
153 152
 				$logger->info('Found controller [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
154 153
 				return $filePath;
155
-			}
156
-			else{
154
+			} else{
157 155
 				$logger->info('Controller [' . $class . '] does not exist in the module [' .$module. ']');
158 156
 				return false;
159 157
 			}
@@ -179,8 +177,7 @@  discard block
 block discarded – undo
179 177
 			if(file_exists($filePath)){
180 178
 				$logger->info('Found model [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
181 179
 				return $filePath;
182
-			}
183
-			else{
180
+			} else{
184 181
 				$logger->info('Model [' . $class . '] does not exist in the module [' .$module. ']');
185 182
 				return false;
186 183
 			}
@@ -205,8 +202,7 @@  discard block
 block discarded – undo
205 202
 			if(file_exists($filePath)){
206 203
 				$logger->info('Found configuration [' . $configuration . '] in module [' .$module. '], the file path is [' .$filePath. ']');
207 204
 				return $filePath;
208
-			}
209
-			else{
205
+			} else{
210 206
 				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' .$module. ']');
211 207
 				return false;
212 208
 			}
@@ -232,8 +228,7 @@  discard block
 block discarded – undo
232 228
 			if(file_exists($filePath)){
233 229
 				$logger->info('Found helper [' . $helper . '] in module [' .$module. '], the file path is [' .$filePath. ']');
234 230
 				return $filePath;
235
-			}
236
-			else{
231
+			} else{
237 232
 				$logger->info('Helper [' . $helper . '] does not exist in the module [' .$module. ']');
238 233
 				return false;
239 234
 			}
@@ -259,8 +254,7 @@  discard block
 block discarded – undo
259 254
 			if(file_exists($filePath)){
260 255
 				$logger->info('Found library [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
261 256
 				return $filePath;
262
-			}
263
-			else{
257
+			} else{
264 258
 				$logger->info('Library [' . $class . '] does not exist in the module [' .$module. ']');
265 259
 				return false;
266 260
 			}
@@ -288,8 +282,7 @@  discard block
 block discarded – undo
288 282
 			if(file_exists($filePath)){
289 283
 				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$filePath. ']');
290 284
 				return $filePath;
291
-			}
292
-			else{
285
+			} else{
293 286
 				$logger->info('View [' . $view . '] does not exist in the module [' .$module. ']');
294 287
 				return false;
295 288
 			}
@@ -316,8 +309,7 @@  discard block
 block discarded – undo
316 309
 			if(file_exists($filePath)){
317 310
 				$logger->info('Found language [' . $language . '] in module [' .$module. '], the file path is [' .$filePath. ']');
318 311
 				return $filePath;
319
-			}
320
-			else{
312
+			} else{
321 313
 				$logger->info('Language [' . $language . '] does not exist in the module [' .$module. ']');
322 314
 				return false;
323 315
 			}
Please login to merge, or discard this patch.
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4 4
      * TNH Framework
5 5
      *
6 6
      * A simple PHP framework using HMVC architecture
@@ -22,321 +22,321 @@  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
-	class Module{
27
+    class Module{
28 28
 		
29
-		/**
30
-		 * list of loaded module
31
-		 * @var array
32
-		 */
33
-		private static $list = array();
29
+        /**
30
+         * list of loaded module
31
+         * @var array
32
+         */
33
+        private static $list = array();
34 34
 
35
-		/**
36
-		 * logger instance
37
-		 * @var Log
38
-		 */
39
-		private static $logger;
35
+        /**
36
+         * 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
-				self::$logger[0] =& class_loader('Log', 'classes');
48
-				self::$logger[0]->setLogger('Library::Module');
49
-			}
50
-			return self::$logger[0];
51
-		}
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
+                self::$logger[0] =& class_loader('Log', 'classes');
48
+                self::$logger[0]->setLogger('Library::Module');
49
+            }
50
+            return self::$logger[0];
51
+        }
52 52
 
53
-		/**
54
-		 * Initialise the module list by scanning the directory MODULE_PATH
55
-		 */
56
-		public function init(){
57
-			$logger = self::getLogger();
58
-			$logger->debug('Check if the application contains the modules ...');
59
-			$moduleDir = opendir(MODULE_PATH);
60
-			if(is_resource($moduleDir)){
61
-				while(($module = readdir($moduleDir)) !== false){
62
-					if(preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
63
-						self::$list[] = $module;
64
-					}
65
-					else{
66
-						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
67
-					}
68
-				}
69
-				closedir($moduleDir);
70
-			}
71
-			ksort(self::$list);
53
+        /**
54
+         * Initialise the module list by scanning the directory MODULE_PATH
55
+         */
56
+        public function init(){
57
+            $logger = self::getLogger();
58
+            $logger->debug('Check if the application contains the modules ...');
59
+            $moduleDir = opendir(MODULE_PATH);
60
+            if(is_resource($moduleDir)){
61
+                while(($module = readdir($moduleDir)) !== false){
62
+                    if(preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
63
+                        self::$list[] = $module;
64
+                    }
65
+                    else{
66
+                        $logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
67
+                    }
68
+                }
69
+                closedir($moduleDir);
70
+            }
71
+            ksort(self::$list);
72 72
 			
73
-			if(self::hasModule()){
74
-				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
75
-			}
76
-		}
73
+            if(self::hasModule()){
74
+                $logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
75
+            }
76
+        }
77 77
 		
78
-		/**
79
-		 * Get the list of the custom autoload configuration from module if exists
80
-		 * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
81
-		 */
82
-		public static function getModulesAutoloadConfig(){
83
-			$logger = self::getLogger();
84
-			if(! self::hasModule()){
85
-				$logger->info('No module was loaded skipping.');
86
-				return false;
87
-			}
88
-			$autoloads = array();
89
-			$autoloads['libraries'] = array();
90
-			$autoloads['config']    = array();
91
-			$autoloads['models']    = array();
92
-			$autoloads['functions'] = array();
93
-			$autoloads['languages'] = array();
78
+        /**
79
+         * Get the list of the custom autoload configuration from module if exists
80
+         * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
81
+         */
82
+        public static function getModulesAutoloadConfig(){
83
+            $logger = self::getLogger();
84
+            if(! self::hasModule()){
85
+                $logger->info('No module was loaded skipping.');
86
+                return false;
87
+            }
88
+            $autoloads = array();
89
+            $autoloads['libraries'] = array();
90
+            $autoloads['config']    = array();
91
+            $autoloads['models']    = array();
92
+            $autoloads['functions'] = array();
93
+            $autoloads['languages'] = array();
94 94
 			
95
-			foreach (self::$list as $module) {
96
-				$file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
97
-				if(file_exists($file)){
98
-					$autoload = array();
99
-					require_once $file;
100
-					if(! empty($autoload) && is_array($autoload)){
101
-						$autoloads = array_merge_recursive($autoloads, $autoload);
102
-						unset($autoload);
103
-					}
104
-				}
105
-			}
106
-			return $autoloads;
107
-		}
95
+            foreach (self::$list as $module) {
96
+                $file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
97
+                if(file_exists($file)){
98
+                    $autoload = array();
99
+                    require_once $file;
100
+                    if(! empty($autoload) && is_array($autoload)){
101
+                        $autoloads = array_merge_recursive($autoloads, $autoload);
102
+                        unset($autoload);
103
+                    }
104
+                }
105
+            }
106
+            return $autoloads;
107
+        }
108 108
 
109
-		/**
110
-		 * Get the list of the custom routes configuration from module if exists
111
-		 * @return array|boolean the routes list or false if no module contains the routes configuration
112
-		 */
113
-		public static function getModulesRoutes(){
114
-			$logger = self::getLogger();
115
-			if(! self::hasModule()){
116
-				$logger->info('No module was loaded skipping.');
117
-				return false;
118
-			}
119
-			$routes = array();
120
-			foreach (self::$list as $module) {
121
-				$file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
122
-				if(file_exists($file)){
123
-					$route = array();
124
-					require_once $file;
125
-					if(! empty($route) && is_array($route)){
126
-						$routes = array_merge($routes, $route);
127
-						unset($route);
128
-					}
129
-				}
130
-			}
131
-			return $routes;
132
-		}
109
+        /**
110
+         * Get the list of the custom routes configuration from module if exists
111
+         * @return array|boolean the routes list or false if no module contains the routes configuration
112
+         */
113
+        public static function getModulesRoutes(){
114
+            $logger = self::getLogger();
115
+            if(! self::hasModule()){
116
+                $logger->info('No module was loaded skipping.');
117
+                return false;
118
+            }
119
+            $routes = array();
120
+            foreach (self::$list as $module) {
121
+                $file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
122
+                if(file_exists($file)){
123
+                    $route = array();
124
+                    require_once $file;
125
+                    if(! empty($route) && is_array($route)){
126
+                        $routes = array_merge($routes, $route);
127
+                        unset($route);
128
+                    }
129
+                }
130
+            }
131
+            return $routes;
132
+        }
133 133
 
134 134
 
135
-		/**
136
-		 * Check if in module list can have this controller
137
-		 * @param  string $class the controller class
138
-		 * @param  string $module  the module name
139
-		 * @return boolean|string  false or null if no module have this controller, path the full path of the controller
140
-		 */
141
-		public static function findControllerFullPath($class, $module = null){
142
-			$logger = self::getLogger();
143
-			if(! self::hasModule()){
144
-				$logger->info('No module was loaded skiping.');
145
-				return false;
146
-			}
147
-			$class = str_ireplace('.php', '', $class);
148
-			$class = ucfirst($class);
149
-			$classFile = $class.'.php';
150
-			$logger->debug('Checking the controller [' . $class . '] in module [' .$module. '] ...');
151
-			$filePath = MODULE_PATH . $module . DS . 'controllers' . DS . $classFile;
152
-			if(file_exists($filePath)){
153
-				$logger->info('Found controller [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
154
-				return $filePath;
155
-			}
156
-			else{
157
-				$logger->info('Controller [' . $class . '] does not exist in the module [' .$module. ']');
158
-				return false;
159
-			}
160
-		}
135
+        /**
136
+         * Check if in module list can have this controller
137
+         * @param  string $class the controller class
138
+         * @param  string $module  the module name
139
+         * @return boolean|string  false or null if no module have this controller, path the full path of the controller
140
+         */
141
+        public static function findControllerFullPath($class, $module = null){
142
+            $logger = self::getLogger();
143
+            if(! self::hasModule()){
144
+                $logger->info('No module was loaded skiping.');
145
+                return false;
146
+            }
147
+            $class = str_ireplace('.php', '', $class);
148
+            $class = ucfirst($class);
149
+            $classFile = $class.'.php';
150
+            $logger->debug('Checking the controller [' . $class . '] in module [' .$module. '] ...');
151
+            $filePath = MODULE_PATH . $module . DS . 'controllers' . DS . $classFile;
152
+            if(file_exists($filePath)){
153
+                $logger->info('Found controller [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
154
+                return $filePath;
155
+            }
156
+            else{
157
+                $logger->info('Controller [' . $class . '] does not exist in the module [' .$module. ']');
158
+                return false;
159
+            }
160
+        }
161 161
 
162
-		/**
163
-		 * Check if in module list can have this model
164
-		 * @param  string $class the model class
165
-		 * @param string $module the module name
166
-		 * @return boolean|string  false or null if no module have this model, return the full path of this model
167
-		 */
168
-		public static function findModelFullPath($class, $module = null){
169
-			$logger = self::getLogger();
170
-			if(! self::hasModule()){
171
-				$logger->info('No module was loaded skiping.');
172
-				return false;
173
-			}
174
-			$class = str_ireplace('.php', '', $class);
175
-			$class = ucfirst($class);
176
-			$classFile = $class.'.php';
177
-			$logger->debug('Checking model [' . $class . '] in module [' .$module. '] ...');
178
-			$filePath = MODULE_PATH . $module . DS . 'models' . DS . $classFile;
179
-			if(file_exists($filePath)){
180
-				$logger->info('Found model [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
181
-				return $filePath;
182
-			}
183
-			else{
184
-				$logger->info('Model [' . $class . '] does not exist in the module [' .$module. ']');
185
-				return false;
186
-			}
187
-		}
162
+        /**
163
+         * Check if in module list can have this model
164
+         * @param  string $class the model class
165
+         * @param string $module the module name
166
+         * @return boolean|string  false or null if no module have this model, return the full path of this model
167
+         */
168
+        public static function findModelFullPath($class, $module = null){
169
+            $logger = self::getLogger();
170
+            if(! self::hasModule()){
171
+                $logger->info('No module was loaded skiping.');
172
+                return false;
173
+            }
174
+            $class = str_ireplace('.php', '', $class);
175
+            $class = ucfirst($class);
176
+            $classFile = $class.'.php';
177
+            $logger->debug('Checking model [' . $class . '] in module [' .$module. '] ...');
178
+            $filePath = MODULE_PATH . $module . DS . 'models' . DS . $classFile;
179
+            if(file_exists($filePath)){
180
+                $logger->info('Found model [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
181
+                return $filePath;
182
+            }
183
+            else{
184
+                $logger->info('Model [' . $class . '] does not exist in the module [' .$module. ']');
185
+                return false;
186
+            }
187
+        }
188 188
 		
189
-		/**
190
-		 * Check if in module list can have this config
191
-		 * @param  string $configuration the config name
192
-		 * @param string $module the module name
193
-		 * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
194
-		 */
195
-		public static function findConfigFullPath($configuration, $module = null){
196
-			$logger = self::getLogger();
197
-			if(! self::hasModule()){
198
-				$logger->info('No module was loaded skiping.');
199
-				return false;
200
-			}
201
-			$configuration = str_ireplace('.php', '', $configuration);
202
-			$file = $configuration.'.php';
203
-			$logger->debug('Checking configuration [' . $configuration . '] in module [' .$module. '] ...');
204
-			$filePath = MODULE_PATH . $module . DS . 'config' . DS . $file;
205
-			if(file_exists($filePath)){
206
-				$logger->info('Found configuration [' . $configuration . '] in module [' .$module. '], the file path is [' .$filePath. ']');
207
-				return $filePath;
208
-			}
209
-			else{
210
-				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' .$module. ']');
211
-				return false;
212
-			}
213
-		}
189
+        /**
190
+         * Check if in module list can have this config
191
+         * @param  string $configuration the config name
192
+         * @param string $module the module name
193
+         * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
194
+         */
195
+        public static function findConfigFullPath($configuration, $module = null){
196
+            $logger = self::getLogger();
197
+            if(! self::hasModule()){
198
+                $logger->info('No module was loaded skiping.');
199
+                return false;
200
+            }
201
+            $configuration = str_ireplace('.php', '', $configuration);
202
+            $file = $configuration.'.php';
203
+            $logger->debug('Checking configuration [' . $configuration . '] in module [' .$module. '] ...');
204
+            $filePath = MODULE_PATH . $module . DS . 'config' . DS . $file;
205
+            if(file_exists($filePath)){
206
+                $logger->info('Found configuration [' . $configuration . '] in module [' .$module. '], the file path is [' .$filePath. ']');
207
+                return $filePath;
208
+            }
209
+            else{
210
+                $logger->info('Configuration [' . $configuration . '] does not exist in the module [' .$module. ']');
211
+                return false;
212
+            }
213
+        }
214 214
 
215
-		/**
216
-		 * Check if in module list can have this helper
217
-		 * @param  string $helper the helper name
218
-		 * @param string $module the module name
219
-		 * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
220
-		 */
221
-		public static function findFunctionFullPath($helper, $module = null){
222
-			$logger = self::getLogger();
223
-			if(! self::hasModule()){
224
-				$logger->info('No module was loaded skiping.');
225
-				return false;
226
-			}
227
-			$helper = str_ireplace('.php', '', $helper);
228
-			$helper = str_ireplace('function_', '', $helper);
229
-			$file = 'function_'.$helper.'.php';
230
-			$logger->debug('Checking helper [' . $helper . '] in module [' .$module. '] ...');
231
-			$filePath = MODULE_PATH . $module . DS . 'functions' . DS . $file;
232
-			if(file_exists($filePath)){
233
-				$logger->info('Found helper [' . $helper . '] in module [' .$module. '], the file path is [' .$filePath. ']');
234
-				return $filePath;
235
-			}
236
-			else{
237
-				$logger->info('Helper [' . $helper . '] does not exist in the module [' .$module. ']');
238
-				return false;
239
-			}
240
-		}
215
+        /**
216
+         * Check if in module list can have this helper
217
+         * @param  string $helper the helper name
218
+         * @param string $module the module name
219
+         * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
220
+         */
221
+        public static function findFunctionFullPath($helper, $module = null){
222
+            $logger = self::getLogger();
223
+            if(! self::hasModule()){
224
+                $logger->info('No module was loaded skiping.');
225
+                return false;
226
+            }
227
+            $helper = str_ireplace('.php', '', $helper);
228
+            $helper = str_ireplace('function_', '', $helper);
229
+            $file = 'function_'.$helper.'.php';
230
+            $logger->debug('Checking helper [' . $helper . '] in module [' .$module. '] ...');
231
+            $filePath = MODULE_PATH . $module . DS . 'functions' . DS . $file;
232
+            if(file_exists($filePath)){
233
+                $logger->info('Found helper [' . $helper . '] in module [' .$module. '], the file path is [' .$filePath. ']');
234
+                return $filePath;
235
+            }
236
+            else{
237
+                $logger->info('Helper [' . $helper . '] does not exist in the module [' .$module. ']');
238
+                return false;
239
+            }
240
+        }
241 241
 
242 242
 
243
-		/**
244
-		 * Check if in module list can have this library
245
-		 * @param  string $class the library name
246
-		 * @param string $module the module name
247
-		 * @return boolean|string  false or null if no module have this library,  return the full path of this library
248
-		 */
249
-		public static function findLibraryFullPath($class, $module = null){
250
-			$logger = self::getLogger();
251
-			if(! self::hasModule()){
252
-				$logger->info('No module was loaded skiping.');
253
-				return false;
254
-			}
255
-			$class = str_ireplace('.php', '', $class);
256
-			$file = $class.'.php';
257
-			$logger->debug('Checking library [' . $class . '] in module [' .$module. '] ...');
258
-			$filePath = MODULE_PATH . $module . DS . 'libraries' . DS . $file;
259
-			if(file_exists($filePath)){
260
-				$logger->info('Found library [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
261
-				return $filePath;
262
-			}
263
-			else{
264
-				$logger->info('Library [' . $class . '] does not exist in the module [' .$module. ']');
265
-				return false;
266
-			}
267
-		}
243
+        /**
244
+         * Check if in module list can have this library
245
+         * @param  string $class the library name
246
+         * @param string $module the module name
247
+         * @return boolean|string  false or null if no module have this library,  return the full path of this library
248
+         */
249
+        public static function findLibraryFullPath($class, $module = null){
250
+            $logger = self::getLogger();
251
+            if(! self::hasModule()){
252
+                $logger->info('No module was loaded skiping.');
253
+                return false;
254
+            }
255
+            $class = str_ireplace('.php', '', $class);
256
+            $file = $class.'.php';
257
+            $logger->debug('Checking library [' . $class . '] in module [' .$module. '] ...');
258
+            $filePath = MODULE_PATH . $module . DS . 'libraries' . DS . $file;
259
+            if(file_exists($filePath)){
260
+                $logger->info('Found library [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
261
+                return $filePath;
262
+            }
263
+            else{
264
+                $logger->info('Library [' . $class . '] does not exist in the module [' .$module. ']');
265
+                return false;
266
+            }
267
+        }
268 268
 
269 269
 
270
-		/**
271
-		 * Check if in module list can have this view
272
-		 * @param  string $view the view path
273
-		 * @param string $module the module name to check
274
-		 * @return boolean|string  false or null if no module have this view, path the full path of the view
275
-		 */
276
-		public static function findViewFullPath($view, $module = null){
277
-			$logger = self::getLogger();
278
-			if(! self::hasModule()){
279
-				$logger->info('No module was loaded skiping.');
280
-				return false;
281
-			}
282
-			$view = str_ireplace('.php', '', $view);
283
-			$view = trim($view, '/\\');
284
-			$view = str_ireplace('/', DS, $view);
285
-			$viewFile = $view . '.php';
286
-			$logger->debug('Checking view [' . $view . '] in module [' .$module. '] ...');
287
-			$filePath = MODULE_PATH . $module . DS . 'views' . DS . $viewFile;
288
-			if(file_exists($filePath)){
289
-				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$filePath. ']');
290
-				return $filePath;
291
-			}
292
-			else{
293
-				$logger->info('View [' . $view . '] does not exist in the module [' .$module. ']');
294
-				return false;
295
-			}
296
-		}
270
+        /**
271
+         * Check if in module list can have this view
272
+         * @param  string $view the view path
273
+         * @param string $module the module name to check
274
+         * @return boolean|string  false or null if no module have this view, path the full path of the view
275
+         */
276
+        public static function findViewFullPath($view, $module = null){
277
+            $logger = self::getLogger();
278
+            if(! self::hasModule()){
279
+                $logger->info('No module was loaded skiping.');
280
+                return false;
281
+            }
282
+            $view = str_ireplace('.php', '', $view);
283
+            $view = trim($view, '/\\');
284
+            $view = str_ireplace('/', DS, $view);
285
+            $viewFile = $view . '.php';
286
+            $logger->debug('Checking view [' . $view . '] in module [' .$module. '] ...');
287
+            $filePath = MODULE_PATH . $module . DS . 'views' . DS . $viewFile;
288
+            if(file_exists($filePath)){
289
+                $logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$filePath. ']');
290
+                return $filePath;
291
+            }
292
+            else{
293
+                $logger->info('View [' . $view . '] does not exist in the module [' .$module. ']');
294
+                return false;
295
+            }
296
+        }
297 297
 
298
-		/**
299
-		 * Check if in module list can have this language
300
-		 * @param  string $language the language name
301
-		 * @param string $module the module name
302
-		 * @param string $appLang the application language like 'en', 'fr'
303
-		 * @return boolean|string  false or null if no module have this language,  return the full path of this language
304
-		 */
305
-		public static function findLanguageFullPath($language, $module = null, $appLang){
306
-			$logger = self::getLogger();
307
-			if(! self::hasModule()){
308
-				$logger->info('No module was loaded skiping.');
309
-				return false;
310
-			}
311
-			$language = str_ireplace('.php', '', $language);
312
-			$language = str_ireplace('lang_', '', $language);
313
-			$file = 'lang_'.$language.'.php';
314
-			$logger->debug('Checking language [' . $language . '] in module [' .$module. '] ...');
315
-			$filePath = MODULE_PATH . $module . DS . 'lang' . DS . $appLang . DS . $file;
316
-			if(file_exists($filePath)){
317
-				$logger->info('Found language [' . $language . '] in module [' .$module. '], the file path is [' .$filePath. ']');
318
-				return $filePath;
319
-			}
320
-			else{
321
-				$logger->info('Language [' . $language . '] does not exist in the module [' .$module. ']');
322
-				return false;
323
-			}
324
-		}
298
+        /**
299
+         * Check if in module list can have this language
300
+         * @param  string $language the language name
301
+         * @param string $module the module name
302
+         * @param string $appLang the application language like 'en', 'fr'
303
+         * @return boolean|string  false or null if no module have this language,  return the full path of this language
304
+         */
305
+        public static function findLanguageFullPath($language, $module = null, $appLang){
306
+            $logger = self::getLogger();
307
+            if(! self::hasModule()){
308
+                $logger->info('No module was loaded skiping.');
309
+                return false;
310
+            }
311
+            $language = str_ireplace('.php', '', $language);
312
+            $language = str_ireplace('lang_', '', $language);
313
+            $file = 'lang_'.$language.'.php';
314
+            $logger->debug('Checking language [' . $language . '] in module [' .$module. '] ...');
315
+            $filePath = MODULE_PATH . $module . DS . 'lang' . DS . $appLang . DS . $file;
316
+            if(file_exists($filePath)){
317
+                $logger->info('Found language [' . $language . '] in module [' .$module. '], the file path is [' .$filePath. ']');
318
+                return $filePath;
319
+            }
320
+            else{
321
+                $logger->info('Language [' . $language . '] does not exist in the module [' .$module. ']');
322
+                return false;
323
+            }
324
+        }
325 325
 
326
-		/**
327
-		 * Get the list of module loaded
328
-		 * @return array the module list
329
-		 */
330
-		public static function getModuleList(){
331
-			return self::$list;
332
-		}
326
+        /**
327
+         * Get the list of module loaded
328
+         * @return array the module list
329
+         */
330
+        public static function getModuleList(){
331
+            return self::$list;
332
+        }
333 333
 
334
-		/**
335
-		 * Check if the application has an module
336
-		 * @return boolean
337
-		 */
338
-		public static function hasModule(){
339
-			return !empty(self::$list);
340
-		}
334
+        /**
335
+         * Check if the application has an module
336
+         * @return boolean
337
+         */
338
+        public static function hasModule(){
339
+            return !empty(self::$list);
340
+        }
341 341
 
342
-	}
342
+    }
Please login to merge, or discard this patch.
core/libraries/Upload.php 3 patches
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     *    @package FileUpload
38 38
     *    @version 1.5
39 39
     */
40
-    class Upload{
40
+    class Upload {
41 41
 
42 42
         /**
43 43
         *   Version
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
         *    @version    1.0
70 70
         *    @var        array
71 71
         */
72
-        private $file_array    = array();
72
+        private $file_array = array();
73 73
 
74 74
         /**
75 75
         *    If the file you are trying to upload already exists it will
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
         *    @version    1.0
120 120
         *    @var        float
121 121
         */
122
-        private $max_file_size= 0.0;
122
+        private $max_file_size = 0.0;
123 123
 
124 124
         /**
125 125
         *    List of allowed mime types
@@ -217,12 +217,12 @@  discard block
 block discarded – undo
217 217
         *    @return    object
218 218
         *    @method    object    __construct
219 219
         */
220
-        public function __construct(){
221
-            $this->logger =& class_loader('Log', 'classes');
220
+        public function __construct() {
221
+            $this->logger = & class_loader('Log', 'classes');
222 222
             $this->logger->setLogger('Library::Upload');
223 223
 
224 224
             Loader::lang('file_upload');
225
-            $obj =& get_instance();
225
+            $obj = & get_instance();
226 226
 
227 227
             $this->error_messages = array(
228 228
                 'upload_err_ini_size' => $obj->lang->get('fu_upload_err_ini_size'),
@@ -239,15 +239,15 @@  discard block
 block discarded – undo
239 239
             );
240 240
 
241 241
             $this->file = array(
242
-                'status'                =>    false,    // True: success upload
243
-                'mime'                  =>    '',       // Empty string
244
-                'filename'              =>    '',       // Empty string
245
-                'original'              =>    '',       // Empty string
246
-                'size'                  =>    0,        // 0 Bytes
247
-                'sizeFormated'          =>    '0B',     // 0 Bytes
248
-                'destination'           =>    './',     // Default: ./
249
-                'allowed_mime_types'    =>    array(),  // Allowed mime types
250
-                'error'                 =>    null,        // File error
242
+                'status'                =>    false, // True: success upload
243
+                'mime'                  =>    '', // Empty string
244
+                'filename'              =>    '', // Empty string
245
+                'original'              =>    '', // Empty string
246
+                'size'                  =>    0, // 0 Bytes
247
+                'sizeFormated'          =>    '0B', // 0 Bytes
248
+                'destination'           =>    './', // Default: ./
249
+                'allowed_mime_types'    =>    array(), // Allowed mime types
250
+                'error'                 =>    null, // File error
251 251
             );
252 252
 
253 253
             // Change dir to current dir
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             if (isset($_FILES) && is_array($_FILES)) {
258 258
                 $this->file_array = $_FILES;
259 259
             }
260
-            $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
260
+            $this->logger->info('The upload file information are : ' . stringfy_vars($this->file_array));
261 261
         }
262 262
         /**
263 263
         *    Set input.
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
         */
274 274
         public function setInput($input)
275 275
         {
276
-            if (!empty($input) && (is_string($input) || is_numeric($input) )) {
276
+            if (!empty($input) && (is_string($input) || is_numeric($input))) {
277 277
                 $this->input = $input;
278 278
             }
279 279
             return $this;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
         */
310 310
         public function setAutoFilename()
311 311
         {
312
-            $this->filename = sha1(mt_rand(1, 9999).uniqid());
312
+            $this->filename = sha1(mt_rand(1, 9999) . uniqid());
313 313
             $this->filename .= time();
314 314
             return $this;
315 315
         }
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
                 $php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
331 331
                 // Calculate difference
332 332
                 if ($php_size < $file_size) {
333
-                    $this->logger->warning('The upload max file size you set [' .$file_size. '] is greather than the PHP configuration for upload max file size [' .$php_size. ']');
333
+                    $this->logger->warning('The upload max file size you set [' . $file_size . '] is greather than the PHP configuration for upload max file size [' . $php_size . ']');
334 334
                 }
335 335
                 $this->max_file_size = $file_size;
336 336
             }
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
         public function setAllowedMimeTypes(array $mimes)
349 349
         {
350 350
             if (count($mimes) > 0) {
351
-                array_map(array($this , 'setAllowMimeType'), $mimes);
351
+                array_map(array($this, 'setAllowMimeType'), $mimes);
352 352
             }
353 353
             return $this;
354 354
         }
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
         {
414 414
             if (!empty($name) && is_string($name)) {
415 415
                 if (array_key_exists($name, $this->mime_helping)) {
416
-                    return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
416
+                    return $this->setAllowedMimeTypes($this->mime_helping[$name]);
417 417
                 }
418 418
             }
419 419
             return $this;
@@ -432,8 +432,8 @@  discard block
 block discarded – undo
432 432
         */
433 433
         public function setUploadFunction($function)
434 434
         {
435
-            if (!empty($function) && (is_array($function) || is_string($function) )) {
436
-                if (is_callable( $function)) {
435
+            if (!empty($function) && (is_array($function) || is_string($function))) {
436
+                if (is_callable($function)) {
437 437
                     $this->upload_function = $function;
438 438
                 }
439 439
             }
@@ -478,8 +478,8 @@  discard block
 block discarded – undo
478 478
                         $this->destination_directory = $destination_directory;
479 479
                         chdir($destination_directory);
480 480
                     }
481
-                    else{
482
-                        $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
481
+                    else {
482
+                        $this->logger->warning('Can not create the upload directory [' . $destination_directory . ']');
483 483
                     }
484 484
                 }
485 485
             }
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
         public function isFilename($filename)
530 530
         {
531 531
             $filename = basename($filename);
532
-            return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
532
+            return (!empty($filename) && (is_string($filename) || is_numeric($filename)));
533 533
         }
534 534
         /**
535 535
         *    Validate mime type with allowed mime types,
@@ -571,11 +571,11 @@  discard block
 block discarded – undo
571 571
         */
572 572
         public function isDirpath($path)
573 573
         {
574
-            if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
574
+            if (!empty($path) && (is_string($path) || is_numeric($path))) {
575 575
                 if (DIRECTORY_SEPARATOR == '/') {
576
-                    return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
576
+                    return (preg_match('/^[^*?"<>|:]*$/', $path) == 1);
577 577
                 } else {
578
-                    return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
578
+                    return (preg_match("/^[^*?\"<>|:]*$/", substr($path, 2)) == 1);
579 579
                 }
580 580
             }
581 581
             return false;
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
         */
604 604
         public function getInfo()
605 605
         {
606
-            return (object)$this->file;
606
+            return (object) $this->file;
607 607
         }
608 608
 
609 609
 
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
          * Check if the file is uploaded
612 612
          * @return boolean
613 613
          */
614
-        public function isUploaded(){
614
+        public function isUploaded() {
615 615
             return isset($this->file_array[$this->input])
616 616
             && is_uploaded_file($this->file_array[$this->input]['tmp_name']);
617 617
         }
@@ -625,13 +625,13 @@  discard block
 block discarded – undo
625 625
         *    @return    boolean
626 626
         *    @method    boolean    save
627 627
         */
628
-        public function save(){
628
+        public function save() {
629 629
             if (count($this->file_array) > 0 && array_key_exists($this->input, $this->file_array)) {
630 630
                 // set original filename if not have a new name
631 631
                 if (empty($this->filename)) {
632 632
                     $this->filename = $this->file_array[$this->input]['name'];
633 633
                 }
634
-                else{
634
+                else {
635 635
                     // Replace %s for extension in filename
636 636
                     // Before: /[\w\d]*(.[\d\w]+)$/i
637 637
                     // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
@@ -655,10 +655,10 @@  discard block
 block discarded – undo
655 655
                 $this->file['filename']     = $this->filename;
656 656
                 $this->file['error']        = $this->file_array[$this->input]['error'];
657 657
 
658
-                $this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
658
+                $this->logger->info('The upload file information to process is : ' . stringfy_vars($this->file));
659 659
 
660 660
                 $error = $this->uploadHasError();
661
-                if($error){
661
+                if ($error) {
662 662
                     return false;
663 663
                 }
664 664
                 // Execute input callback
@@ -692,10 +692,10 @@  discard block
 block discarded – undo
692 692
         */
693 693
         public function sizeFormat($size, $precision = 2)
694 694
         {
695
-            if($size > 0){
695
+            if ($size > 0) {
696 696
                 $base       = log($size) / log(1024);
697 697
                 $suffixes   = array('B', 'K', 'M', 'G', 'T');
698
-                return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
698
+                return round(pow(1024, $base - floor($base)), $precision) . (isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
699 699
             }
700 700
             return null;
701 701
         }
@@ -719,14 +719,14 @@  discard block
 block discarded – undo
719 719
             if (array_key_exists('unit', $matches)) {
720 720
                 $unit = strtoupper($matches['unit']);
721 721
             }
722
-            return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
722
+            return (floatval($matches['size']) * pow(1024, $units[$unit]));
723 723
         }
724 724
 
725 725
         /**
726 726
          * Get the upload error message
727 727
          * @return string
728 728
          */
729
-        public function getError(){
729
+        public function getError() {
730 730
             return $this->error;
731 731
         }
732 732
 
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
          * Set the upload error message
735 735
          * @param string $message the upload error message to set
736 736
          */
737
-        public function setError($message){
737
+        public function setError($message) {
738 738
             $this->logger->info('The file upload got error : ' . $message);
739 739
             $this->error = $message;
740 740
         }
@@ -744,9 +744,9 @@  discard block
 block discarded – undo
744 744
          * @param string $type the type of callback "input" or "output"
745 745
          * @return void 
746 746
          */
747
-        protected function runCallback($type){
748
-            if (!empty( $this->callbacks[$type])) {
749
-                call_user_func($this->callbacks[$type], (object)$this->file);
747
+        protected function runCallback($type) {
748
+            if (!empty($this->callbacks[$type])) {
749
+                call_user_func($this->callbacks[$type], (object) $this->file);
750 750
             }
751 751
         }
752 752
 
@@ -754,21 +754,21 @@  discard block
 block discarded – undo
754 754
          * Check if file upload has error
755 755
          * @return boolean
756 756
          */
757
-        protected function uploadHasError(){
757
+        protected function uploadHasError() {
758 758
             //check if file upload is  allowed in the configuration
759
-            if(! ini_get('file_uploads')){
759
+            if (!ini_get('file_uploads')) {
760 760
                 $this->setError($this->error_messages['file_uploads']);
761 761
                 return true;
762 762
             }
763 763
 
764 764
              //check for php upload error
765
-            if(is_numeric($this->file['error']) && $this->file['error'] > 0){
765
+            if (is_numeric($this->file['error']) && $this->file['error'] > 0) {
766 766
                 $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
767 767
                 return true;
768 768
             }
769 769
             
770 770
             //check for mime type
771
-            if (! $this->checkMimeType($this->file['mime'])) {
771
+            if (!$this->checkMimeType($this->file['mime'])) {
772 772
                 $this->setError($this->error_messages['accept_file_types']);
773 773
                 return true;
774 774
             }
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
          * @param  int $code the error code
793 793
          * @return string the error message
794 794
          */
795
-        private function getPhpUploadErrorMessageByCode($code){
795
+        private function getPhpUploadErrorMessageByCode($code) {
796 796
             $codeMessageMaps = array(
797 797
                 1 => $this->error_messages['upload_err_ini_size'],
798 798
                 2 => $this->error_messages['upload_err_form_size'],
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -477,8 +477,7 @@  discard block
 block discarded – undo
477 477
                     if (mkdir($destination_directory, 0775, true)) {
478 478
                         $this->destination_directory = $destination_directory;
479 479
                         chdir($destination_directory);
480
-                    }
481
-                    else{
480
+                    } else{
482 481
                         $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
483 482
                     }
484 483
                 }
@@ -630,8 +629,7 @@  discard block
 block discarded – undo
630 629
                 // set original filename if not have a new name
631 630
                 if (empty($this->filename)) {
632 631
                     $this->filename = $this->file_array[$this->input]['name'];
633
-                }
634
-                else{
632
+                } else{
635 633
                     // Replace %s for extension in filename
636 634
                     // Before: /[\w\d]*(.[\d\w]+)$/i
637 635
                     // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
Please login to merge, or discard this patch.
Indentation   +293 added lines, -293 removed lines patch added patch discarded remove patch
@@ -22,139 +22,139 @@  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 28
 
29 29
     /**
30
-    *    Upload
31
-    *
32
-    *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
33
-    *
34
-    *    @author Olaf Erlandsen <[email protected]>
35
-    *    @author http://www.webdevfreelance.com/
36
-    *
37
-    *    @package FileUpload
38
-    *    @version 1.5
39
-    */
30
+     *    Upload
31
+     *
32
+     *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
33
+     *
34
+     *    @author Olaf Erlandsen <[email protected]>
35
+     *    @author http://www.webdevfreelance.com/
36
+     *
37
+     *    @package FileUpload
38
+     *    @version 1.5
39
+     */
40 40
     class Upload{
41 41
 
42 42
         /**
43
-        *   Version
44
-        *
45
-        *   @since      1.5
46
-        *   @version    1.0
47
-        */
43
+         *   Version
44
+         *
45
+         *   @since      1.5
46
+         *   @version    1.0
47
+         */
48 48
         const VERSION = '1.5';
49 49
 
50 50
         /**
51
-        *    Upload function name
52
-        *    Remember:
53
-        *        Default function: move_uploaded_file
54
-        *        Native options:
55
-        *            - move_uploaded_file (Default and best option)
56
-        *            - copy
57
-        *
58
-        *    @since        1.0
59
-        *    @version    1.0
60
-        *    @var        string
61
-        */
51
+         *    Upload function name
52
+         *    Remember:
53
+         *        Default function: move_uploaded_file
54
+         *        Native options:
55
+         *            - move_uploaded_file (Default and best option)
56
+         *            - copy
57
+         *
58
+         *    @since        1.0
59
+         *    @version    1.0
60
+         *    @var        string
61
+         */
62 62
         private $upload_function = 'move_uploaded_file';
63 63
 
64 64
         /**
65
-        *    Array with the information obtained from the
66
-        *    variable $_FILES or $HTTP_POST_FILES.
67
-        *
68
-        *    @since        1.0
69
-        *    @version    1.0
70
-        *    @var        array
71
-        */
65
+         *    Array with the information obtained from the
66
+         *    variable $_FILES or $HTTP_POST_FILES.
67
+         *
68
+         *    @since        1.0
69
+         *    @version    1.0
70
+         *    @var        array
71
+         */
72 72
         private $file_array    = array();
73 73
 
74 74
         /**
75
-        *    If the file you are trying to upload already exists it will
76
-        *    be overwritten if you set the variable to true.
77
-        *
78
-        *    @since        1.0
79
-        *    @version    1.0
80
-        *    @var        boolean
81
-        */
75
+         *    If the file you are trying to upload already exists it will
76
+         *    be overwritten if you set the variable to true.
77
+         *
78
+         *    @since        1.0
79
+         *    @version    1.0
80
+         *    @var        boolean
81
+         */
82 82
         private $overwrite_file = false;
83 83
 
84 84
         /**
85
-        *    Input element
86
-        *    Example:
87
-        *        <input type="file" name="file" />
88
-        *    Result:
89
-        *        FileUpload::$input = file
90
-        *
91
-        *    @since        1.0
92
-        *    @version    1.0
93
-        *    @var        string
94
-        */
85
+         *    Input element
86
+         *    Example:
87
+         *        <input type="file" name="file" />
88
+         *    Result:
89
+         *        FileUpload::$input = file
90
+         *
91
+         *    @since        1.0
92
+         *    @version    1.0
93
+         *    @var        string
94
+         */
95 95
         private $input;
96 96
 
97 97
         /**
98
-        *    Path output
99
-        *
100
-        *    @since        1.0
101
-        *    @version    1.0
102
-        *    @var        string
103
-        */
98
+         *    Path output
99
+         *
100
+         *    @since        1.0
101
+         *    @version    1.0
102
+         *    @var        string
103
+         */
104 104
         private $destination_directory;
105 105
 
106 106
         /**
107
-        *    Output filename
108
-        *
109
-        *    @since        1.0
110
-        *    @version    1.0
111
-        *    @var        string
112
-        */
107
+         *    Output filename
108
+         *
109
+         *    @since        1.0
110
+         *    @version    1.0
111
+         *    @var        string
112
+         */
113 113
         private $filename;
114 114
 
115 115
         /**
116
-        *    Max file size
117
-        *
118
-        *    @since        1.0
119
-        *    @version    1.0
120
-        *    @var        float
121
-        */
116
+         *    Max file size
117
+         *
118
+         *    @since        1.0
119
+         *    @version    1.0
120
+         *    @var        float
121
+         */
122 122
         private $max_file_size= 0.0;
123 123
 
124 124
         /**
125
-        *    List of allowed mime types
126
-        *
127
-        *    @since        1.0
128
-        *    @version    1.0
129
-        *    @var        array
130
-        */
125
+         *    List of allowed mime types
126
+         *
127
+         *    @since        1.0
128
+         *    @version    1.0
129
+         *    @var        array
130
+         */
131 131
         private $allowed_mime_types = array();
132 132
 
133 133
         /**
134
-        *    Callbacks
135
-        *
136
-        *    @since        1.0
137
-        *    @version    1.0
138
-        *    @var        array
139
-        */
134
+         *    Callbacks
135
+         *
136
+         *    @since        1.0
137
+         *    @version    1.0
138
+         *    @var        array
139
+         */
140 140
         private $callbacks = array('before' => null, 'after' => null);
141 141
 
142 142
         /**
143
-        *    File object
144
-        *
145
-        *    @since        1.0
146
-        *    @version    1.0
147
-        *    @var        object
148
-        */
143
+         *    File object
144
+         *
145
+         *    @since        1.0
146
+         *    @version    1.0
147
+         *    @var        object
148
+         */
149 149
         private $file;
150 150
 
151 151
         /**
152
-        *    Helping mime types
153
-        *
154
-        *    @since        1.0
155
-        *    @version    1.0
156
-        *    @var        array
157
-        */
152
+         *    Helping mime types
153
+         *
154
+         *    @since        1.0
155
+         *    @version    1.0
156
+         *    @var        array
157
+         */
158 158
         private $mime_helping = array(
159 159
             'text'      =>    array('text/plain',),
160 160
             'image'     =>    array(
@@ -210,13 +210,13 @@  discard block
 block discarded – undo
210 210
 
211 211
 
212 212
         /**
213
-        *    Construct
214
-        *
215
-        *    @since     0.1
216
-        *    @version   1.0.1
217
-        *    @return    object
218
-        *    @method    object    __construct
219
-        */
213
+         *    Construct
214
+         *
215
+         *    @since     0.1
216
+         *    @version   1.0.1
217
+         *    @return    object
218
+         *    @method    object    __construct
219
+         */
220 220
         public function __construct(){
221 221
             $this->logger =& class_loader('Log', 'classes');
222 222
             $this->logger->setLogger('Library::Upload');
@@ -260,17 +260,17 @@  discard block
 block discarded – undo
260 260
             $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
261 261
         }
262 262
         /**
263
-        *    Set input.
264
-        *    If you have $_FILES["file"], you must use the key "file"
265
-        *    Example:
266
-        *        $object->setInput("file");
267
-        *
268
-        *    @since     1.0
269
-        *    @version   1.0
270
-        *    @param     string      $input
271
-        *    @return    object
272
-        *    @method    boolean     setInput
273
-        */
263
+         *    Set input.
264
+         *    If you have $_FILES["file"], you must use the key "file"
265
+         *    Example:
266
+         *        $object->setInput("file");
267
+         *
268
+         *    @since     1.0
269
+         *    @version   1.0
270
+         *    @param     string      $input
271
+         *    @return    object
272
+         *    @method    boolean     setInput
273
+         */
274 274
         public function setInput($input)
275 275
         {
276 276
             if (!empty($input) && (is_string($input) || is_numeric($input) )) {
@@ -279,18 +279,18 @@  discard block
 block discarded – undo
279 279
             return $this;
280 280
         }
281 281
         /**
282
-        *    Set new filename
283
-        *    Example:
284
-        *        FileUpload::setFilename("new file.txt")
285
-        *    Remember:
286
-        *        Use %s to retrive file extension
287
-        *
288
-        *    @since     1.0
289
-        *    @version   1.0
290
-        *    @param     string      $filename
291
-        *    @return    object
292
-        *    @method    boolean     setFilename
293
-        */
282
+         *    Set new filename
283
+         *    Example:
284
+         *        FileUpload::setFilename("new file.txt")
285
+         *    Remember:
286
+         *        Use %s to retrive file extension
287
+         *
288
+         *    @since     1.0
289
+         *    @version   1.0
290
+         *    @param     string      $filename
291
+         *    @return    object
292
+         *    @method    boolean     setFilename
293
+         */
294 294
         public function setFilename($filename)
295 295
         {
296 296
             if ($this->isFilename($filename)) {
@@ -299,14 +299,14 @@  discard block
 block discarded – undo
299 299
             return $this;
300 300
         }
301 301
         /**
302
-        *    Set automatic filename
303
-        *
304
-        *    @since     1.0
305
-        *    @version   1.5
306
-        *    @param     string      $extension
307
-        *    @return    object
308
-        *    @method    boolean     setAutoFilename
309
-        */
302
+         *    Set automatic filename
303
+         *
304
+         *    @since     1.0
305
+         *    @version   1.5
306
+         *    @param     string      $extension
307
+         *    @return    object
308
+         *    @method    boolean     setAutoFilename
309
+         */
310 310
         public function setAutoFilename()
311 311
         {
312 312
             $this->filename = sha1(mt_rand(1, 9999).uniqid());
@@ -314,14 +314,14 @@  discard block
 block discarded – undo
314 314
             return $this;
315 315
         }
316 316
         /**
317
-        *    Set file size limit
318
-        *
319
-        *    @since     1.0
320
-        *    @version   1.0
321
-        *    @param     double     $file_size
322
-        *    @return    object
323
-        *    @method    boolean     setMaxFileSize
324
-        */
317
+         *    Set file size limit
318
+         *
319
+         *    @since     1.0
320
+         *    @version   1.0
321
+         *    @param     double     $file_size
322
+         *    @return    object
323
+         *    @method    boolean     setMaxFileSize
324
+         */
325 325
         public function setMaxFileSize($file_size)
326 326
         {
327 327
             $file_size = $this->sizeInBytes($file_size);
@@ -337,14 +337,14 @@  discard block
 block discarded – undo
337 337
             return $this;
338 338
         }
339 339
         /**
340
-        *    Set array mime types
341
-        *
342
-        *    @since     1.0
343
-        *    @version   1.0
344
-        *    @param     array       $mimes
345
-        *    @return    object
346
-        *    @method    boolean     setAllowedMimeTypes
347
-        */
340
+         *    Set array mime types
341
+         *
342
+         *    @since     1.0
343
+         *    @version   1.0
344
+         *    @param     array       $mimes
345
+         *    @return    object
346
+         *    @method    boolean     setAllowedMimeTypes
347
+         */
348 348
         public function setAllowedMimeTypes(array $mimes)
349 349
         {
350 350
             if (count($mimes) > 0) {
@@ -353,14 +353,14 @@  discard block
 block discarded – undo
353 353
             return $this;
354 354
         }
355 355
         /**
356
-        *    Set input callback
357
-        *
358
-        *    @since     1.0
359
-        *    @version   1.0
360
-        *    @param     mixed       $callback
361
-        *    @return    object
362
-        *    @method    boolean     setCallbackInput
363
-        */
356
+         *    Set input callback
357
+         *
358
+         *    @since     1.0
359
+         *    @version   1.0
360
+         *    @param     mixed       $callback
361
+         *    @return    object
362
+         *    @method    boolean     setCallbackInput
363
+         */
364 364
         public function setCallbackInput($callback)
365 365
         {
366 366
             if (is_callable($callback, false)) {
@@ -369,14 +369,14 @@  discard block
 block discarded – undo
369 369
             return $this;
370 370
         }
371 371
         /**
372
-        *    Set output callback
373
-        *
374
-        *    @since     1.0
375
-        *    @version   1.0
376
-        *    @param     mixed       $callback
377
-        *    @return    object
378
-        *    @method    boolean     setCallbackOutput
379
-        */
372
+         *    Set output callback
373
+         *
374
+         *    @since     1.0
375
+         *    @version   1.0
376
+         *    @param     mixed       $callback
377
+         *    @return    object
378
+         *    @method    boolean     setCallbackOutput
379
+         */
380 380
         public function setCallbackOutput($callback)
381 381
         {
382 382
             if (is_callable($callback, false)) {
@@ -385,14 +385,14 @@  discard block
 block discarded – undo
385 385
             return $this;
386 386
         }
387 387
         /**
388
-        *    Append a mime type to allowed mime types
389
-        *
390
-        *    @since     1.0
391
-        *    @version   1.0.1
392
-        *    @param     string      $mime
393
-        *    @return    object
394
-        *    @method    boolean     setAllowMimeType
395
-        */
388
+         *    Append a mime type to allowed mime types
389
+         *
390
+         *    @since     1.0
391
+         *    @version   1.0.1
392
+         *    @param     string      $mime
393
+         *    @return    object
394
+         *    @method    boolean     setAllowMimeType
395
+         */
396 396
         public function setAllowMimeType($mime)
397 397
         {
398 398
             if (!empty($mime) && is_string($mime)) {
@@ -402,13 +402,13 @@  discard block
 block discarded – undo
402 402
             return $this;
403 403
         }
404 404
         /**
405
-        *    Set allowed mime types from mime helping
406
-        *
407
-        *    @since     1.0.1
408
-        *    @version   1.0.1
409
-        *    @return    object
410
-        *    @method    boolean    setMimeHelping
411
-        */
405
+         *    Set allowed mime types from mime helping
406
+         *
407
+         *    @since     1.0.1
408
+         *    @version   1.0.1
409
+         *    @return    object
410
+         *    @method    boolean    setMimeHelping
411
+         */
412 412
         public function setMimeHelping($name)
413 413
         {
414 414
             if (!empty($name) && is_string($name)) {
@@ -419,17 +419,17 @@  discard block
 block discarded – undo
419 419
             return $this;
420 420
         }
421 421
         /**
422
-        *    Set function to upload file
423
-        *    Examples:
424
-        *        1.- FileUpload::setUploadFunction("move_uploaded_file");
425
-        *        2.- FileUpload::setUploadFunction("copy");
426
-        *
427
-        *    @since     1.0
428
-        *    @version   1.0
429
-        *    @param     string      $function
430
-        *    @return    object
431
-        *    @method    boolean     setUploadFunction
432
-        */
422
+         *    Set function to upload file
423
+         *    Examples:
424
+         *        1.- FileUpload::setUploadFunction("move_uploaded_file");
425
+         *        2.- FileUpload::setUploadFunction("copy");
426
+         *
427
+         *    @since     1.0
428
+         *    @version   1.0
429
+         *    @param     string      $function
430
+         *    @return    object
431
+         *    @method    boolean     setUploadFunction
432
+         */
433 433
         public function setUploadFunction($function)
434 434
         {
435 435
             if (!empty($function) && (is_array($function) || is_string($function) )) {
@@ -440,13 +440,13 @@  discard block
 block discarded – undo
440 440
             return $this;
441 441
         }
442 442
         /**
443
-        *    Clear allowed mime types cache
444
-        *
445
-        *    @since     1.0
446
-        *    @version   1.0
447
-        *    @return    object
448
-        *    @method    boolean    clearAllowedMimeTypes
449
-        */
443
+         *    Clear allowed mime types cache
444
+         *
445
+         *    @since     1.0
446
+         *    @version   1.0
447
+         *    @return    object
448
+         *    @method    boolean    clearAllowedMimeTypes
449
+         */
450 450
         public function clearAllowedMimeTypes()
451 451
         {
452 452
             $this->allowed_mime_types = array();
@@ -454,15 +454,15 @@  discard block
 block discarded – undo
454 454
             return $this;
455 455
         }
456 456
         /**
457
-        *    Set destination output
458
-        *
459
-        *    @since     1.0
460
-        *    @version   1.0
461
-        *    @param     string      $destination_directory      Destination path
462
-        *    @param     boolean     $create_if_not_exist
463
-        *    @return    object
464
-        *    @method    boolean     setDestinationDirectory
465
-        */
457
+         *    Set destination output
458
+         *
459
+         *    @since     1.0
460
+         *    @version   1.0
461
+         *    @param     string      $destination_directory      Destination path
462
+         *    @param     boolean     $create_if_not_exist
463
+         *    @return    object
464
+         *    @method    boolean     setDestinationDirectory
465
+         */
466 466
         public function setDestinationDirectory($destination_directory, $create_if_not_exist = false) {
467 467
             $destination_directory = realpath($destination_directory);
468 468
             if (substr($destination_directory, -1) != DIRECTORY_SEPARATOR) {
@@ -486,14 +486,14 @@  discard block
 block discarded – undo
486 486
             return $this;
487 487
         }
488 488
         /**
489
-        *    Check file exists
490
-        *
491
-        *    @since      1.0
492
-        *    @version    1.0.1
493
-        *    @param      string     $file_destination
494
-        *    @return     boolean
495
-        *    @method     boolean    fileExists
496
-        */
489
+         *    Check file exists
490
+         *
491
+         *    @since      1.0
492
+         *    @version    1.0.1
493
+         *    @param      string     $file_destination
494
+         *    @return     boolean
495
+         *    @method     boolean    fileExists
496
+         */
497 497
         public function fileExists($file_destination)
498 498
         {
499 499
             if ($this->isFilename($file_destination)) {
@@ -502,14 +502,14 @@  discard block
 block discarded – undo
502 502
             return false;
503 503
         }
504 504
         /**
505
-        *    Check dir exists
506
-        *
507
-        *    @since        1.0
508
-        *    @version    1.0.1
509
-        *    @param      string     $path
510
-        *    @return     boolean
511
-        *    @method     boolean    dirExists
512
-        */
505
+         *    Check dir exists
506
+         *
507
+         *    @since        1.0
508
+         *    @version    1.0.1
509
+         *    @param      string     $path
510
+         *    @return     boolean
511
+         *    @method     boolean    dirExists
512
+         */
513 513
         public function dirExists($path)
514 514
         {
515 515
             if ($this->isDirpath($path)) {
@@ -518,29 +518,29 @@  discard block
 block discarded – undo
518 518
             return false;
519 519
         }
520 520
         /**
521
-        *    Check valid filename
522
-        *
523
-        *    @since     1.0
524
-        *    @version   1.0.1
525
-        *    @param     string      $filename
526
-        *    @return    boolean
527
-        *    @method    boolean     isFilename
528
-        */
521
+         *    Check valid filename
522
+         *
523
+         *    @since     1.0
524
+         *    @version   1.0.1
525
+         *    @param     string      $filename
526
+         *    @return    boolean
527
+         *    @method    boolean     isFilename
528
+         */
529 529
         public function isFilename($filename)
530 530
         {
531 531
             $filename = basename($filename);
532 532
             return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
533 533
         }
534 534
         /**
535
-        *    Validate mime type with allowed mime types,
536
-        *    but if allowed mime types is empty, this method return true
537
-        *
538
-        *    @since     1.0
539
-        *    @version   1.0
540
-        *    @param     string      $mime
541
-        *    @return    boolean
542
-        *    @method    boolean     checkMimeType
543
-        */
535
+         *    Validate mime type with allowed mime types,
536
+         *    but if allowed mime types is empty, this method return true
537
+         *
538
+         *    @since     1.0
539
+         *    @version   1.0
540
+         *    @param     string      $mime
541
+         *    @return    boolean
542
+         *    @method    boolean     checkMimeType
543
+         */
544 544
         public function checkMimeType($mime)
545 545
         {
546 546
             if (count($this->allowed_mime_types) == 0) {
@@ -549,26 +549,26 @@  discard block
 block discarded – undo
549 549
             return in_array(strtolower($mime), $this->allowed_mime_types);
550 550
         }
551 551
         /**
552
-        *    Retrive status of upload
553
-        *
554
-        *    @since     1.0
555
-        *    @version   1.0
556
-        *    @return    boolean
557
-        *    @method    boolean    getStatus
558
-        */
552
+         *    Retrive status of upload
553
+         *
554
+         *    @since     1.0
555
+         *    @version   1.0
556
+         *    @return    boolean
557
+         *    @method    boolean    getStatus
558
+         */
559 559
         public function getStatus()
560 560
         {
561 561
             return $this->file['status'];
562 562
         }
563 563
         /**
564
-        *    Check valid path
565
-        *
566
-        *    @since        1.0
567
-        *    @version    1.0.1
568
-        *    @param        string    $filename
569
-        *    @return     boolean
570
-        *    @method     boolean    isDirpath
571
-        */
564
+         *    Check valid path
565
+         *
566
+         *    @since        1.0
567
+         *    @version    1.0.1
568
+         *    @param        string    $filename
569
+         *    @return     boolean
570
+         *    @method     boolean    isDirpath
571
+         */
572 572
         public function isDirpath($path)
573 573
         {
574 574
             if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
@@ -581,26 +581,26 @@  discard block
 block discarded – undo
581 581
             return false;
582 582
         }
583 583
         /**
584
-        *    Allow overwriting files
585
-        *
586
-        *    @since      1.0
587
-        *    @version    1.0
588
-        *    @return     object
589
-        *    @method     boolean    allowOverwriting
590
-        */
584
+         *    Allow overwriting files
585
+         *
586
+         *    @since      1.0
587
+         *    @version    1.0
588
+         *    @return     object
589
+         *    @method     boolean    allowOverwriting
590
+         */
591 591
         public function allowOverwriting()
592 592
         {
593 593
             $this->overwrite_file = true;
594 594
             return $this;
595 595
         }
596 596
         /**
597
-        *    File info
598
-        *
599
-        *    @since      1.0
600
-        *    @version    1.0
601
-        *    @return     object
602
-        *    @method     object    getInfo
603
-        */
597
+         *    File info
598
+         *
599
+         *    @since      1.0
600
+         *    @version    1.0
601
+         *    @return     object
602
+         *    @method     object    getInfo
603
+         */
604 604
         public function getInfo()
605 605
         {
606 606
             return (object)$this->file;
@@ -618,13 +618,13 @@  discard block
 block discarded – undo
618 618
 
619 619
         
620 620
         /**
621
-        *    Upload file
622
-        *
623
-        *    @since     1.0
624
-        *    @version   1.0.1
625
-        *    @return    boolean
626
-        *    @method    boolean    save
627
-        */
621
+         *    Upload file
622
+         *
623
+         *    @since     1.0
624
+         *    @version   1.0.1
625
+         *    @return    boolean
626
+         *    @method    boolean    save
627
+         */
628 628
         public function save(){
629 629
             if (count($this->file_array) > 0 && array_key_exists($this->input, $this->file_array)) {
630 630
                 // set original filename if not have a new name
@@ -681,15 +681,15 @@  discard block
 block discarded – undo
681 681
 
682 682
 
683 683
         /**
684
-        *    File size for humans.
685
-        *
686
-        *    @since      1.0
687
-        *    @version    1.0
688
-        *    @param      integer    $bytes
689
-        *    @param      integer    $precision
690
-        *    @return     string
691
-        *    @method     string     sizeFormat
692
-        */
684
+         *    File size for humans.
685
+         *
686
+         *    @since      1.0
687
+         *    @version    1.0
688
+         *    @param      integer    $bytes
689
+         *    @param      integer    $precision
690
+         *    @return     string
691
+         *    @method     string     sizeFormat
692
+         */
693 693
         public function sizeFormat($size, $precision = 2)
694 694
         {
695 695
             if($size > 0){
@@ -702,14 +702,14 @@  discard block
 block discarded – undo
702 702
 
703 703
         
704 704
         /**
705
-        *    Convert human file size to bytes
706
-        *
707
-        *    @since      1.0
708
-        *    @version    1.0.1
709
-        *    @param      integer|double    $size
710
-        *    @return     integer|double
711
-        *    @method     string     sizeInBytes
712
-        */
705
+         *    Convert human file size to bytes
706
+         *
707
+         *    @since      1.0
708
+         *    @version    1.0.1
709
+         *    @param      integer|double    $size
710
+         *    @return     integer|double
711
+         *    @method     string     sizeInBytes
712
+         */
713 713
         public function sizeInBytes($size)
714 714
         {
715 715
             $unit = 'B';
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
                 return true;
762 762
             }
763 763
 
764
-             //check for php upload error
764
+                //check for php upload error
765 765
             if(is_numeric($this->file['error']) && $this->file['error'] > 0){
766 766
                 $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
767 767
                 return true;
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
                 return true;
774 774
             }
775 775
 
776
-             // Check file size
776
+                // Check file size
777 777
             if ($this->max_file_size > 0 && $this->max_file_size < $this->file['size']) {
778 778
                 $this->setError(sprintf($this->error_messages['max_file_size'], $this->sizeFormat($this->max_file_size)));
779 779
                 return true;
Please login to merge, or discard this patch.