Passed
Push — 1.0.0-dev ( 93958a...e1c8ef )
by nguereza
02:26
created
core/classes/Response.php 3 patches
Braces   +3 added lines, -6 removed lines patch added patch discarded remove patch
@@ -210,8 +210,7 @@  discard block
 block discarded – undo
210 210
 			if($moduleViewPath){
211 211
 				$path = $moduleViewPath;
212 212
 				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$moduleViewPath. '] we will used it');
213
-			}
214
-			else{
213
+			} else{
215 214
 				$logger->info('Cannot find view [' . $view . '] in module [' .$module. '] using the default location');
216 215
 			}
217 216
 			
@@ -335,8 +334,7 @@  discard block
 block discarded – undo
335 334
 				$output = ob_get_clean();
336 335
 				self::sendHeaders(404);
337 336
 				echo $output;
338
-			}
339
-			else{
337
+			} else{
340 338
 				show_error('The 404 view [' .$path. '] does not exist');
341 339
 			}
342 340
 		}
@@ -359,8 +357,7 @@  discard block
 block discarded – undo
359 357
 				$output = ob_get_clean();
360 358
 				self::sendHeaders(503);
361 359
 				echo $output;
362
-			}
363
-			else{
360
+			} else{
364 361
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
365 362
 				set_http_status_header(503);
366 363
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Indentation   +463 added lines, -463 removed lines patch added patch discarded remove patch
@@ -1,511 +1,511 @@
 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 extends BaseStaticClass{
27
+    class Response extends BaseStaticClass{
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 final page content to display to user
37
-		 * @var string
38
-		 */
39
-		private $_pageRender = null;
35
+        /**
36
+         * The final page content to display to user
37
+         * @var string
38
+         */
39
+        private $_pageRender = null;
40 40
 		
41
-		/**
42
-		 * The current request URL
43
-		 * @var string
44
-		 */
45
-		private $_currentUrl = null;
41
+        /**
42
+         * The current request URL
43
+         * @var string
44
+         */
45
+        private $_currentUrl = null;
46 46
 		
47
-		/**
48
-		 * The current request URL cache key
49
-		 * @var string
50
-		 */
51
-		private $_currentUrlCacheKey = null;
47
+        /**
48
+         * The current request URL cache key
49
+         * @var string
50
+         */
51
+        private $_currentUrlCacheKey = null;
52 52
 		
53
-		/**
54
-		* Whether we can compress the output using Gzip
55
-		* @var boolean
56
-		*/
57
-		private static $_canCompressOutput = false;
53
+        /**
54
+         * Whether we can compress the output using Gzip
55
+         * @var boolean
56
+         */
57
+        private static $_canCompressOutput = false;
58 58
 		
59
-		/**
60
-		 * Construct new response instance
61
-		 */
62
-		public function __construct(){
63
-			$currentUrl = '';
64
-			if (! empty($_SERVER['REQUEST_URI'])){
65
-				$currentUrl = $_SERVER['REQUEST_URI'];
66
-			}
67
-			if (! empty($_SERVER['QUERY_STRING'])){
68
-				$currentUrl .= '?' . $_SERVER['QUERY_STRING'];
69
-			}
70
-			$this->_currentUrl =  $currentUrl;
59
+        /**
60
+         * Construct new response instance
61
+         */
62
+        public function __construct(){
63
+            $currentUrl = '';
64
+            if (! empty($_SERVER['REQUEST_URI'])){
65
+                $currentUrl = $_SERVER['REQUEST_URI'];
66
+            }
67
+            if (! empty($_SERVER['QUERY_STRING'])){
68
+                $currentUrl .= '?' . $_SERVER['QUERY_STRING'];
69
+            }
70
+            $this->_currentUrl =  $currentUrl;
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 81
 		
82
-		/**
83
-		 * Send the HTTP Response headers
84
-		 * @param  integer $httpCode the HTTP status code
85
-		 * @param  array   $headers   the additional headers to add to the existing headers list
86
-		 */
87
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
88
-			set_http_status_header($httpCode);
89
-			self::setHeaders($headers);
90
-			if(! headers_sent()){
91
-				foreach(self::getHeaders() as $key => $value){
92
-					header($key .': '.$value);
93
-				}
94
-			}
95
-		}
82
+        /**
83
+         * Send the HTTP Response headers
84
+         * @param  integer $httpCode the HTTP status code
85
+         * @param  array   $headers   the additional headers to add to the existing headers list
86
+         */
87
+        public static function sendHeaders($httpCode = 200, array $headers = array()){
88
+            set_http_status_header($httpCode);
89
+            self::setHeaders($headers);
90
+            if(! headers_sent()){
91
+                foreach(self::getHeaders() as $key => $value){
92
+                    header($key .': '.$value);
93
+                }
94
+            }
95
+        }
96 96
 
97
-		/**
98
-		 * Get the list of the headers
99
-		 * @return array the headers list
100
-		 */
101
-		public static function getHeaders(){
102
-			return self::$headers;
103
-		}
97
+        /**
98
+         * Get the list of the headers
99
+         * @return array the headers list
100
+         */
101
+        public static function getHeaders(){
102
+            return self::$headers;
103
+        }
104 104
 
105
-		/**
106
-		 * Get the header value for the given name
107
-		 * @param  string $name the header name
108
-		 * @return string|null       the header value
109
-		 */
110
-		public static function getHeader($name){
111
-			if(array_key_exists($name, self::$headers)){
112
-				return self::$headers[$name];
113
-			}
114
-			return null;
115
-		}
105
+        /**
106
+         * Get the header value for the given name
107
+         * @param  string $name the header name
108
+         * @return string|null       the header value
109
+         */
110
+        public static function getHeader($name){
111
+            if(array_key_exists($name, self::$headers)){
112
+                return self::$headers[$name];
113
+            }
114
+            return null;
115
+        }
116 116
 
117 117
 
118
-		/**
119
-		 * Set the header value for the specified name
120
-		 * @param string $name  the header name
121
-		 * @param string $value the header value to be set
122
-		 */
123
-		public static function setHeader($name, $value){
124
-			self::$headers[$name] = $value;
125
-		}
118
+        /**
119
+         * Set the header value for the specified name
120
+         * @param string $name  the header name
121
+         * @param string $value the header value to be set
122
+         */
123
+        public static function setHeader($name, $value){
124
+            self::$headers[$name] = $value;
125
+        }
126 126
 
127
-		/**
128
-		 * Set the headers using array
129
-		 * @param array $headers the list of the headers to set. 
130
-		 * Note: this will merge with the existing headers
131
-		 */
132
-		public static function setHeaders(array $headers){
133
-			self::$headers = array_merge(self::getHeaders(), $headers);
134
-		}
127
+        /**
128
+         * Set the headers using array
129
+         * @param array $headers the list of the headers to set. 
130
+         * Note: this will merge with the existing headers
131
+         */
132
+        public static function setHeaders(array $headers){
133
+            self::$headers = array_merge(self::getHeaders(), $headers);
134
+        }
135 135
 		
136
-		/**
137
-		 * Redirect user to the specified page
138
-		 * @param  string $path the URL or URI to be redirect to
139
-		 */
140
-		public static function redirect($path = ''){
141
-			$logger = self::getLogger();
142
-			$url = Url::site_url($path);
143
-			$logger->info('Redirect to URL [' .$url. ']');
144
-			if(! headers_sent()){
145
-				header('Location: '.$url);
146
-				exit;
147
-			}
148
-			echo '<script>
136
+        /**
137
+         * Redirect user to the specified page
138
+         * @param  string $path the URL or URI to be redirect to
139
+         */
140
+        public static function redirect($path = ''){
141
+            $logger = self::getLogger();
142
+            $url = Url::site_url($path);
143
+            $logger->info('Redirect to URL [' .$url. ']');
144
+            if(! headers_sent()){
145
+                header('Location: '.$url);
146
+                exit;
147
+            }
148
+            echo '<script>
149 149
 					location.href = "'.$url.'";
150 150
 				</script>';
151
-		}
151
+        }
152 152
 
153
-		/**
154
-		 * Render the view to display later or return the content
155
-		 * @param  string  $view   the view name or path
156
-		 * @param  array|object   $data   the variable data to use in the view
157
-		 * @param  boolean $return whether to return the view generated content or display it directly
158
-		 * @return void|string          if $return is true will return the view content otherwise
159
-		 * will display the view content.
160
-		 */
161
-		public function render($view, $data = null, $return = false){
162
-			$logger = self::getLogger();
163
-			//convert data to an array
164
-			$data = (array) $data;
165
-			$view = str_ireplace('.php', '', $view);
166
-			$view = trim($view, '/\\');
167
-			$viewFile = $view . '.php';
168
-			$path = APPS_VIEWS_PATH . $viewFile;
153
+        /**
154
+         * Render the view to display later or return the content
155
+         * @param  string  $view   the view name or path
156
+         * @param  array|object   $data   the variable data to use in the view
157
+         * @param  boolean $return whether to return the view generated content or display it directly
158
+         * @return void|string          if $return is true will return the view content otherwise
159
+         * will display the view content.
160
+         */
161
+        public function render($view, $data = null, $return = false){
162
+            $logger = self::getLogger();
163
+            //convert data to an array
164
+            $data = (array) $data;
165
+            $view = str_ireplace('.php', '', $view);
166
+            $view = trim($view, '/\\');
167
+            $viewFile = $view . '.php';
168
+            $path = APPS_VIEWS_PATH . $viewFile;
169 169
 			
170
-			//check in module first
171
-			$logger->debug('Checking the view [' . $view . '] from module list ...');
172
-			$moduleInfo = $this->getModuleInfoForView($view);
173
-			$module    = $moduleInfo['module'];
174
-			$view  = $moduleInfo['view'];
170
+            //check in module first
171
+            $logger->debug('Checking the view [' . $view . '] from module list ...');
172
+            $moduleInfo = $this->getModuleInfoForView($view);
173
+            $module    = $moduleInfo['module'];
174
+            $view  = $moduleInfo['view'];
175 175
 			
176
-			$moduleViewPath = Module::findViewFullPath($view, $module);
177
-			if($moduleViewPath){
178
-				$path = $moduleViewPath;
179
-				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$moduleViewPath. '] we will used it');
180
-			}
181
-			else{
182
-				$logger->info('Cannot find view [' . $view . '] in module [' .$module. '] using the default location');
183
-			}
176
+            $moduleViewPath = Module::findViewFullPath($view, $module);
177
+            if($moduleViewPath){
178
+                $path = $moduleViewPath;
179
+                $logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$moduleViewPath. '] we will used it');
180
+            }
181
+            else{
182
+                $logger->info('Cannot find view [' . $view . '] in module [' .$module. '] using the default location');
183
+            }
184 184
 			
185
-			$logger->info('The view file path to be loaded is [' . $path . ']');
185
+            $logger->info('The view file path to be loaded is [' . $path . ']');
186 186
 			
187
-			/////////
188
-			if($return){
189
-				return $this->loadView($path, $data, true);
190
-			}
191
-			$this->loadView($path, $data, false);
192
-		}
187
+            /////////
188
+            if($return){
189
+                return $this->loadView($path, $data, true);
190
+            }
191
+            $this->loadView($path, $data, false);
192
+        }
193 193
 
194 194
 		
195
-		/**
196
-		* Send the final page output to user
197
-		*/
198
-		public function renderFinalPage(){
199
-			$logger = self::getLogger();
200
-			$obj = & get_instance();
201
-			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
202
-			$dispatcher = $obj->eventdispatcher;
203
-			$content = $this->_pageRender;
204
-			if(! $content){
205
-				$logger->warning('The final view content is empty.');
206
-				return;
207
-			}
208
-			//dispatch
209
-			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
210
-			$content = null;
211
-			if(! empty($event->payload)){
212
-				$content = $event->payload;
213
-			}
214
-			if(empty($content)){
215
-				$logger->warning('The view content is empty after dispatch to event listeners.');
216
-			}
217
-			//remove unsed space in the content
218
-			$content = preg_replace('~>\s*\n\s*<~', '><', $content);
219
-			//check whether need save the page into cache.
220
-			if($cachePageStatus){
221
-				$this->savePageContentIntoCache($content);
222
-			}
223
-			$content = $this->replaceElapseTimeAndMemoryUsage($content);
195
+        /**
196
+         * Send the final page output to user
197
+         */
198
+        public function renderFinalPage(){
199
+            $logger = self::getLogger();
200
+            $obj = & get_instance();
201
+            $cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
202
+            $dispatcher = $obj->eventdispatcher;
203
+            $content = $this->_pageRender;
204
+            if(! $content){
205
+                $logger->warning('The final view content is empty.');
206
+                return;
207
+            }
208
+            //dispatch
209
+            $event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
210
+            $content = null;
211
+            if(! empty($event->payload)){
212
+                $content = $event->payload;
213
+            }
214
+            if(empty($content)){
215
+                $logger->warning('The view content is empty after dispatch to event listeners.');
216
+            }
217
+            //remove unsed space in the content
218
+            $content = preg_replace('~>\s*\n\s*<~', '><', $content);
219
+            //check whether need save the page into cache.
220
+            if($cachePageStatus){
221
+                $this->savePageContentIntoCache($content);
222
+            }
223
+            $content = $this->replaceElapseTimeAndMemoryUsage($content);
224 224
 
225
-			//compress the output if is available
226
-			$type = null;
227
-			if (self::$_canCompressOutput){
228
-				$type = 'ob_gzhandler';
229
-			}
230
-			ob_start($type);
231
-			self::sendHeaders(200);
232
-			echo $content;
233
-			ob_end_flush();
234
-		}
225
+            //compress the output if is available
226
+            $type = null;
227
+            if (self::$_canCompressOutput){
228
+                $type = 'ob_gzhandler';
229
+            }
230
+            ob_start($type);
231
+            self::sendHeaders(200);
232
+            echo $content;
233
+            ob_end_flush();
234
+        }
235 235
 
236 236
 		
237
-		/**
238
-		* Send the final page output to user if is cached
239
-		* @param object $cache the cache instance
240
-		*
241
-		* @return boolean whether the page content if available or not
242
-		*/
243
-		public function renderFinalPageFromCache(&$cache){
244
-			$logger = self::getLogger();
245
-			//the current page cache key for identification
246
-			$pageCacheKey = $this->_currentUrlCacheKey;
237
+        /**
238
+         * Send the final page output to user if is cached
239
+         * @param object $cache the cache instance
240
+         *
241
+         * @return boolean whether the page content if available or not
242
+         */
243
+        public function renderFinalPageFromCache(&$cache){
244
+            $logger = self::getLogger();
245
+            //the current page cache key for identification
246
+            $pageCacheKey = $this->_currentUrlCacheKey;
247 247
 			
248
-			$logger->debug('Checking if the page content for the URL [' . $this->_currentUrl . '] is cached ...');
249
-			//get the cache information to prepare header to send to browser
250
-			$cacheInfo = $cache->getInfo($pageCacheKey);
251
-			if($cacheInfo){
252
-				$status = $this->sendCacheNotYetExpireInfoToBrowser($cacheInfo);
253
-				if($status === false){
254
-					return $this->sendCachePageContentToBrowser($cache);
255
-				}
256
-				return true;
257
-			}
258
-			return false;
259
-		}
248
+            $logger->debug('Checking if the page content for the URL [' . $this->_currentUrl . '] is cached ...');
249
+            //get the cache information to prepare header to send to browser
250
+            $cacheInfo = $cache->getInfo($pageCacheKey);
251
+            if($cacheInfo){
252
+                $status = $this->sendCacheNotYetExpireInfoToBrowser($cacheInfo);
253
+                if($status === false){
254
+                    return $this->sendCachePageContentToBrowser($cache);
255
+                }
256
+                return true;
257
+            }
258
+            return false;
259
+        }
260 260
 	
261 261
 		
262
-		/**
263
-		* Get the final page to be rendered
264
-		* @return string
265
-		*/
266
-		public function getFinalPageRendered(){
267
-			return $this->_pageRender;
268
-		}
262
+        /**
263
+         * Get the final page to be rendered
264
+         * @return string
265
+         */
266
+        public function getFinalPageRendered(){
267
+            return $this->_pageRender;
268
+        }
269 269
 
270
-		/**
271
-		 * Send the HTTP 404 error if can not found the 
272
-		 * routing information for the current request
273
-		 */
274
-		public static function send404(){
275
-			/********* for logs **************/
276
-			//can't use $obj = & get_instance()  here because the global super object will be available until
277
-			//the main controller is loaded even for Loader::library('xxxx');
278
-			$logger = self::getLogger();
279
-			$request =& class_loader('Request', 'classes');
280
-			$userAgent =& class_loader('Browser');
281
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
270
+        /**
271
+         * Send the HTTP 404 error if can not found the 
272
+         * routing information for the current request
273
+         */
274
+        public static function send404(){
275
+            /********* for logs **************/
276
+            //can't use $obj = & get_instance()  here because the global super object will be available until
277
+            //the main controller is loaded even for Loader::library('xxxx');
278
+            $logger = self::getLogger();
279
+            $request =& class_loader('Request', 'classes');
280
+            $userAgent =& class_loader('Browser');
281
+            $browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
282 282
 			
283
-			//here can't use Loader::functions just include the helper manually
284
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
283
+            //here can't use Loader::functions just include the helper manually
284
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
285 285
 
286
-			$str = '[404 page not found] : ';
287
-			$str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
288
-			$logger->error($str);
289
-			/***********************************/
290
-			$path = CORE_VIEWS_PATH . '404.php';
291
-			if(file_exists($path)){
292
-				//compress the output if is available
293
-				$type = null;
294
-				if (self::$_canCompressOutput){
295
-					$type = 'ob_gzhandler';
296
-				}
297
-				ob_start($type);
298
-				require_once $path;
299
-				$output = ob_get_clean();
300
-				self::sendHeaders(404);
301
-				echo $output;
302
-			}
303
-			else{
304
-				show_error('The 404 view [' .$path. '] does not exist');
305
-			}
306
-		}
286
+            $str = '[404 page not found] : ';
287
+            $str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
288
+            $logger->error($str);
289
+            /***********************************/
290
+            $path = CORE_VIEWS_PATH . '404.php';
291
+            if(file_exists($path)){
292
+                //compress the output if is available
293
+                $type = null;
294
+                if (self::$_canCompressOutput){
295
+                    $type = 'ob_gzhandler';
296
+                }
297
+                ob_start($type);
298
+                require_once $path;
299
+                $output = ob_get_clean();
300
+                self::sendHeaders(404);
301
+                echo $output;
302
+            }
303
+            else{
304
+                show_error('The 404 view [' .$path. '] does not exist');
305
+            }
306
+        }
307 307
 
308
-		/**
309
-		 * Display the error to user
310
-		 * @param  array  $data the error information
311
-		 */
312
-		public static function sendError(array $data = array()){
313
-			$path = CORE_VIEWS_PATH . 'errors.php';
314
-			if(file_exists($path)){
315
-				//compress the output if is available
316
-				$type = null;
317
-				if (self::$_canCompressOutput){
318
-					$type = 'ob_gzhandler';
319
-				}
320
-				ob_start($type);
321
-				extract($data);
322
-				require_once $path;
323
-				$output = ob_get_clean();
324
-				self::sendHeaders(503);
325
-				echo $output;
326
-			}
327
-			else{
328
-				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
329
-				set_http_status_header(503);
330
-				echo 'The error view [' . $path . '] does not exist';
331
-			}
332
-		}
308
+        /**
309
+         * Display the error to user
310
+         * @param  array  $data the error information
311
+         */
312
+        public static function sendError(array $data = array()){
313
+            $path = CORE_VIEWS_PATH . 'errors.php';
314
+            if(file_exists($path)){
315
+                //compress the output if is available
316
+                $type = null;
317
+                if (self::$_canCompressOutput){
318
+                    $type = 'ob_gzhandler';
319
+                }
320
+                ob_start($type);
321
+                extract($data);
322
+                require_once $path;
323
+                $output = ob_get_clean();
324
+                self::sendHeaders(503);
325
+                echo $output;
326
+            }
327
+            else{
328
+                //can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
329
+                set_http_status_header(503);
330
+                echo 'The error view [' . $path . '] does not exist';
331
+            }
332
+        }
333 333
 
334
-		/**
335
-		 * Send the cache not yet expire to browser
336
-		 * @param  array $cacheInfo the cache information
337
-		 * @return boolean            true if the information is sent otherwise false
338
-		 */
339
-		protected function sendCacheNotYetExpireInfoToBrowser($cacheInfo){
340
-			if(! empty($cacheInfo)){
341
-				$logger = self::getLogger();
342
-				$lastModified = $cacheInfo['mtime'];
343
-				$expire = $cacheInfo['expire'];
344
-				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
345
-				self::setHeader('Pragma', 'public');
346
-				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
347
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
348
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
349
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
350
-					$logger->info('The cache page content is not yet expire for the URL [' . $this->_currentUrl . '] send 304 header to browser');
351
-					self::sendHeaders(304);
352
-					return true;
353
-				}
354
-			}
355
-			return false;
356
-		}
334
+        /**
335
+         * Send the cache not yet expire to browser
336
+         * @param  array $cacheInfo the cache information
337
+         * @return boolean            true if the information is sent otherwise false
338
+         */
339
+        protected function sendCacheNotYetExpireInfoToBrowser($cacheInfo){
340
+            if(! empty($cacheInfo)){
341
+                $logger = self::getLogger();
342
+                $lastModified = $cacheInfo['mtime'];
343
+                $expire = $cacheInfo['expire'];
344
+                $maxAge = $expire - $_SERVER['REQUEST_TIME'];
345
+                self::setHeader('Pragma', 'public');
346
+                self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
347
+                self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
348
+                self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
349
+                if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
350
+                    $logger->info('The cache page content is not yet expire for the URL [' . $this->_currentUrl . '] send 304 header to browser');
351
+                    self::sendHeaders(304);
352
+                    return true;
353
+                }
354
+            }
355
+            return false;
356
+        }
357 357
 
358
-		/**
359
-		 * Set the value of '{elapsed_time}' and '{memory_usage}'
360
-		 * @param  string $content the page content
361
-		 * @return string          the page content after replace 
362
-		 * '{elapsed_time}', '{memory_usage}'
363
-		 */
364
-		protected function replaceElapseTimeAndMemoryUsage($content){
365
-			//load benchmark class
366
-			$benchmark = & class_loader('Benchmark');
358
+        /**
359
+         * Set the value of '{elapsed_time}' and '{memory_usage}'
360
+         * @param  string $content the page content
361
+         * @return string          the page content after replace 
362
+         * '{elapsed_time}', '{memory_usage}'
363
+         */
364
+        protected function replaceElapseTimeAndMemoryUsage($content){
365
+            //load benchmark class
366
+            $benchmark = & class_loader('Benchmark');
367 367
 			
368
-			// Parse out the elapsed time and memory usage,
369
-			// then swap the pseudo-variables with the data
370
-			$elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
371
-			$memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
372
-			return str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);	
373
-		}
368
+            // Parse out the elapsed time and memory usage,
369
+            // then swap the pseudo-variables with the data
370
+            $elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
371
+            $memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
372
+            return str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);	
373
+        }
374 374
 
375
-		/**
376
-		 * Send the page content from cache to browser
377
-		 * @param object $cache the cache instance
378
-		 * @return boolean     the status of the operation
379
-		 */
380
-		protected function sendCachePageContentToBrowser(&$cache){
381
-			$logger = self::getLogger();
382
-			$logger->info('The cache page content is expired or the browser does not send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $this->_currentUrl . '] send cache headers to tell the browser');
383
-			self::sendHeaders(200);
384
-			//current page cache key
385
-			$pageCacheKey = $this->_currentUrlCacheKey;
386
-			//get the cache content
387
-			$content = $cache->get($pageCacheKey);
388
-			if($content){
389
-				$logger->info('The page content for the URL [' . $this->_currentUrl . '] already cached just display it');
390
-				$content = $this->replaceElapseTimeAndMemoryUsage($content);
391
-				///display the final output
392
-				//compress the output if is available
393
-				$type = null;
394
-				if (self::$_canCompressOutput){
395
-					$type = 'ob_gzhandler';
396
-				}
397
-				ob_start($type);
398
-				echo $content;
399
-				ob_end_flush();
400
-				return true;
401
-			}
402
-			$logger->info('The page cache content for the URL [' . $this->_currentUrl . '] is not valid may be already expired');
403
-			$cache->delete($pageCacheKey);
404
-			return false;
405
-		}
375
+        /**
376
+         * Send the page content from cache to browser
377
+         * @param object $cache the cache instance
378
+         * @return boolean     the status of the operation
379
+         */
380
+        protected function sendCachePageContentToBrowser(&$cache){
381
+            $logger = self::getLogger();
382
+            $logger->info('The cache page content is expired or the browser does not send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $this->_currentUrl . '] send cache headers to tell the browser');
383
+            self::sendHeaders(200);
384
+            //current page cache key
385
+            $pageCacheKey = $this->_currentUrlCacheKey;
386
+            //get the cache content
387
+            $content = $cache->get($pageCacheKey);
388
+            if($content){
389
+                $logger->info('The page content for the URL [' . $this->_currentUrl . '] already cached just display it');
390
+                $content = $this->replaceElapseTimeAndMemoryUsage($content);
391
+                ///display the final output
392
+                //compress the output if is available
393
+                $type = null;
394
+                if (self::$_canCompressOutput){
395
+                    $type = 'ob_gzhandler';
396
+                }
397
+                ob_start($type);
398
+                echo $content;
399
+                ob_end_flush();
400
+                return true;
401
+            }
402
+            $logger->info('The page cache content for the URL [' . $this->_currentUrl . '] is not valid may be already expired');
403
+            $cache->delete($pageCacheKey);
404
+            return false;
405
+        }
406 406
 
407
-		/**
408
-		 * Save the content of page into cache
409
-		 * @param  string $content the page content to be saved
410
-		 * @return void
411
-		 */
412
-		protected function savePageContentIntoCache($content){
413
-			$obj = & get_instance();
414
-			$logger = self::getLogger();
407
+        /**
408
+         * Save the content of page into cache
409
+         * @param  string $content the page content to be saved
410
+         * @return void
411
+         */
412
+        protected function savePageContentIntoCache($content){
413
+            $obj = & get_instance();
414
+            $logger = self::getLogger();
415 415
 
416
-			//current page URL
417
-			$url = $this->_currentUrl;
418
-			//Cache view Time to live in second
419
-			$viewCacheTtl = get_config('cache_ttl');
420
-			if (!empty($obj->view_cache_ttl)){
421
-				$viewCacheTtl = $obj->view_cache_ttl;
422
-			}
423
-			//the cache handler instance
424
-			$cacheInstance = $obj->cache;
425
-			//the current page cache key for identification
426
-			$cacheKey = $this->_currentUrlCacheKey;
427
-			$logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
428
-			$cacheInstance->set($cacheKey, $content, $viewCacheTtl);
416
+            //current page URL
417
+            $url = $this->_currentUrl;
418
+            //Cache view Time to live in second
419
+            $viewCacheTtl = get_config('cache_ttl');
420
+            if (!empty($obj->view_cache_ttl)){
421
+                $viewCacheTtl = $obj->view_cache_ttl;
422
+            }
423
+            //the cache handler instance
424
+            $cacheInstance = $obj->cache;
425
+            //the current page cache key for identification
426
+            $cacheKey = $this->_currentUrlCacheKey;
427
+            $logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
428
+            $cacheInstance->set($cacheKey, $content, $viewCacheTtl);
429 429
 			
430
-			//get the cache information to prepare header to send to browser
431
-			$cacheInfo = $cacheInstance->getInfo($cacheKey);
432
-			if($cacheInfo){
433
-				$lastModified = $cacheInfo['mtime'];
434
-				$expire = $cacheInfo['expire'];
435
-				$maxAge = $expire - time();
436
-				self::setHeader('Pragma', 'public');
437
-				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
438
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
439
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
440
-			}
441
-		}
430
+            //get the cache information to prepare header to send to browser
431
+            $cacheInfo = $cacheInstance->getInfo($cacheKey);
432
+            if($cacheInfo){
433
+                $lastModified = $cacheInfo['mtime'];
434
+                $expire = $cacheInfo['expire'];
435
+                $maxAge = $expire - time();
436
+                self::setHeader('Pragma', 'public');
437
+                self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
438
+                self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
439
+                self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
440
+            }
441
+        }
442 442
 		
443 443
 
444
-		/**
445
-		 * Get the module information for the view to load
446
-		 * @param  string $view the view name like moduleName/viewName, viewName
447
-		 * 
448
-		 * @return array        the module information
449
-		 * array(
450
-		 * 	'module'=> 'module_name'
451
-		 * 	'view' => 'view_name'
452
-		 * 	'viewFile' => 'view_file'
453
-		 * )
454
-		 */
455
-		protected  function getModuleInfoForView($view){
456
-			$module = null;
457
-			$viewFile = null;
458
-			$obj = & get_instance();
459
-			//check if the request class contains module name
460
-			if(strpos($view, '/') !== false){
461
-				$viewPath = explode('/', $view);
462
-				if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
463
-					$module = $viewPath[0];
464
-					array_shift($viewPath);
465
-					$view = implode('/', $viewPath);
466
-					$viewFile = $view . '.php';
467
-				}
468
-			}
469
-			if(! $module && !empty($obj->moduleName)){
470
-				$module = $obj->moduleName;
471
-			}
472
-			return array(
473
-						'view' => $view,
474
-						'module' => $module,
475
-						'viewFile' => $viewFile
476
-					);
477
-		}
444
+        /**
445
+         * Get the module information for the view to load
446
+         * @param  string $view the view name like moduleName/viewName, viewName
447
+         * 
448
+         * @return array        the module information
449
+         * array(
450
+         * 	'module'=> 'module_name'
451
+         * 	'view' => 'view_name'
452
+         * 	'viewFile' => 'view_file'
453
+         * )
454
+         */
455
+        protected  function getModuleInfoForView($view){
456
+            $module = null;
457
+            $viewFile = null;
458
+            $obj = & get_instance();
459
+            //check if the request class contains module name
460
+            if(strpos($view, '/') !== false){
461
+                $viewPath = explode('/', $view);
462
+                if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
463
+                    $module = $viewPath[0];
464
+                    array_shift($viewPath);
465
+                    $view = implode('/', $viewPath);
466
+                    $viewFile = $view . '.php';
467
+                }
468
+            }
469
+            if(! $module && !empty($obj->moduleName)){
470
+                $module = $obj->moduleName;
471
+            }
472
+            return array(
473
+                        'view' => $view,
474
+                        'module' => $module,
475
+                        'viewFile' => $viewFile
476
+                    );
477
+        }
478 478
 
479
-		/**
480
-		 * Render the view page
481
-		 * @see  Response::render
482
-		 * @return void|string
483
-		 */
484
-		protected  function loadView($path, array $data = array(), $return = false){
485
-			$found = false;
486
-			if(file_exists($path)){
487
-				//super instance
488
-				$obj = & get_instance();
489
-				foreach(get_object_vars($obj) as $key => $value){
490
-					if(! isset($this->{$key})){
491
-						$this->{$key} = & $obj->{$key};
492
-					}
493
-				}
494
-				ob_start();
495
-				extract($data);
496
-				//need use require() instead of require_once because can load this view many time
497
-				require $path;
498
-				$content = ob_get_clean();
499
-				if($return){
500
-					//remove unused html space 
501
-					return preg_replace('~>\s*\n\s*<~', '><', $content);
502
-				}
503
-				$this->_pageRender .= $content;
504
-				$found = true;
505
-			}
506
-			if(! $found){
507
-				show_error('Unable to find view [' .$path . ']');
508
-			}
509
-		}
479
+        /**
480
+         * Render the view page
481
+         * @see  Response::render
482
+         * @return void|string
483
+         */
484
+        protected  function loadView($path, array $data = array(), $return = false){
485
+            $found = false;
486
+            if(file_exists($path)){
487
+                //super instance
488
+                $obj = & get_instance();
489
+                foreach(get_object_vars($obj) as $key => $value){
490
+                    if(! isset($this->{$key})){
491
+                        $this->{$key} = & $obj->{$key};
492
+                    }
493
+                }
494
+                ob_start();
495
+                extract($data);
496
+                //need use require() instead of require_once because can load this view many time
497
+                require $path;
498
+                $content = ob_get_clean();
499
+                if($return){
500
+                    //remove unused html space 
501
+                    return preg_replace('~>\s*\n\s*<~', '><', $content);
502
+                }
503
+                $this->_pageRender .= $content;
504
+                $found = true;
505
+            }
506
+            if(! $found){
507
+                show_error('Unable to find view [' .$path . ']');
508
+            }
509
+        }
510 510
 
511
-	}
511
+    }
Please login to merge, or discard this patch.
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 extends BaseStaticClass{
27
+	class Response extends BaseStaticClass {
28 28
 
29 29
 		/**
30 30
 		 * The list of request header to send with response
@@ -59,15 +59,15 @@  discard block
 block discarded – undo
59 59
 		/**
60 60
 		 * Construct new response instance
61 61
 		 */
62
-		public function __construct(){
62
+		public function __construct() {
63 63
 			$currentUrl = '';
64
-			if (! empty($_SERVER['REQUEST_URI'])){
64
+			if (!empty($_SERVER['REQUEST_URI'])) {
65 65
 				$currentUrl = $_SERVER['REQUEST_URI'];
66 66
 			}
67
-			if (! empty($_SERVER['QUERY_STRING'])){
67
+			if (!empty($_SERVER['QUERY_STRING'])) {
68 68
 				$currentUrl .= '?' . $_SERVER['QUERY_STRING'];
69 69
 			}
70
-			$this->_currentUrl =  $currentUrl;
70
+			$this->_currentUrl = $currentUrl;
71 71
 					
72 72
 			$this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
@@ -84,12 +84,12 @@  discard block
 block discarded – undo
84 84
 		 * @param  integer $httpCode the HTTP status code
85 85
 		 * @param  array   $headers   the additional headers to add to the existing headers list
86 86
 		 */
87
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
87
+		public static function sendHeaders($httpCode = 200, array $headers = array()) {
88 88
 			set_http_status_header($httpCode);
89 89
 			self::setHeaders($headers);
90
-			if(! headers_sent()){
91
-				foreach(self::getHeaders() as $key => $value){
92
-					header($key .': '.$value);
90
+			if (!headers_sent()) {
91
+				foreach (self::getHeaders() as $key => $value) {
92
+					header($key . ': ' . $value);
93 93
 				}
94 94
 			}
95 95
 		}
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 		 * Get the list of the headers
99 99
 		 * @return array the headers list
100 100
 		 */
101
-		public static function getHeaders(){
101
+		public static function getHeaders() {
102 102
 			return self::$headers;
103 103
 		}
104 104
 
@@ -107,8 +107,8 @@  discard block
 block discarded – undo
107 107
 		 * @param  string $name the header name
108 108
 		 * @return string|null       the header value
109 109
 		 */
110
-		public static function getHeader($name){
111
-			if(array_key_exists($name, self::$headers)){
110
+		public static function getHeader($name) {
111
+			if (array_key_exists($name, self::$headers)) {
112 112
 				return self::$headers[$name];
113 113
 			}
114 114
 			return null;
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 		 * @param string $name  the header name
121 121
 		 * @param string $value the header value to be set
122 122
 		 */
123
-		public static function setHeader($name, $value){
123
+		public static function setHeader($name, $value) {
124 124
 			self::$headers[$name] = $value;
125 125
 		}
126 126
 
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 		 * @param array $headers the list of the headers to set. 
130 130
 		 * Note: this will merge with the existing headers
131 131
 		 */
132
-		public static function setHeaders(array $headers){
132
+		public static function setHeaders(array $headers) {
133 133
 			self::$headers = array_merge(self::getHeaders(), $headers);
134 134
 		}
135 135
 		
@@ -137,16 +137,16 @@  discard block
 block discarded – undo
137 137
 		 * Redirect user to the specified page
138 138
 		 * @param  string $path the URL or URI to be redirect to
139 139
 		 */
140
-		public static function redirect($path = ''){
140
+		public static function redirect($path = '') {
141 141
 			$logger = self::getLogger();
142 142
 			$url = Url::site_url($path);
143
-			$logger->info('Redirect to URL [' .$url. ']');
144
-			if(! headers_sent()){
145
-				header('Location: '.$url);
143
+			$logger->info('Redirect to URL [' . $url . ']');
144
+			if (!headers_sent()) {
145
+				header('Location: ' . $url);
146 146
 				exit;
147 147
 			}
148 148
 			echo '<script>
149
-					location.href = "'.$url.'";
149
+					location.href = "'.$url . '";
150 150
 				</script>';
151 151
 		}
152 152
 
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 		 * @return void|string          if $return is true will return the view content otherwise
159 159
 		 * will display the view content.
160 160
 		 */
161
-		public function render($view, $data = null, $return = false){
161
+		public function render($view, $data = null, $return = false) {
162 162
 			$logger = self::getLogger();
163 163
 			//convert data to an array
164 164
 			$data = (array) $data;
@@ -170,22 +170,22 @@  discard block
 block discarded – undo
170 170
 			//check in module first
171 171
 			$logger->debug('Checking the view [' . $view . '] from module list ...');
172 172
 			$moduleInfo = $this->getModuleInfoForView($view);
173
-			$module    = $moduleInfo['module'];
174
-			$view  = $moduleInfo['view'];
173
+			$module = $moduleInfo['module'];
174
+			$view = $moduleInfo['view'];
175 175
 			
176 176
 			$moduleViewPath = Module::findViewFullPath($view, $module);
177
-			if($moduleViewPath){
177
+			if ($moduleViewPath) {
178 178
 				$path = $moduleViewPath;
179
-				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$moduleViewPath. '] we will used it');
179
+				$logger->info('Found view [' . $view . '] in module [' . $module . '], the file path is [' . $moduleViewPath . '] we will used it');
180 180
 			}
181
-			else{
182
-				$logger->info('Cannot find view [' . $view . '] in module [' .$module. '] using the default location');
181
+			else {
182
+				$logger->info('Cannot find view [' . $view . '] in module [' . $module . '] using the default location');
183 183
 			}
184 184
 			
185 185
 			$logger->info('The view file path to be loaded is [' . $path . ']');
186 186
 			
187 187
 			/////////
188
-			if($return){
188
+			if ($return) {
189 189
 				return $this->loadView($path, $data, true);
190 190
 			}
191 191
 			$this->loadView($path, $data, false);
@@ -195,36 +195,36 @@  discard block
 block discarded – undo
195 195
 		/**
196 196
 		* Send the final page output to user
197 197
 		*/
198
-		public function renderFinalPage(){
198
+		public function renderFinalPage() {
199 199
 			$logger = self::getLogger();
200 200
 			$obj = & get_instance();
201 201
 			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
202 202
 			$dispatcher = $obj->eventdispatcher;
203 203
 			$content = $this->_pageRender;
204
-			if(! $content){
204
+			if (!$content) {
205 205
 				$logger->warning('The final view content is empty.');
206 206
 				return;
207 207
 			}
208 208
 			//dispatch
209 209
 			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
210 210
 			$content = null;
211
-			if(! empty($event->payload)){
211
+			if (!empty($event->payload)) {
212 212
 				$content = $event->payload;
213 213
 			}
214
-			if(empty($content)){
214
+			if (empty($content)) {
215 215
 				$logger->warning('The view content is empty after dispatch to event listeners.');
216 216
 			}
217 217
 			//remove unsed space in the content
218 218
 			$content = preg_replace('~>\s*\n\s*<~', '><', $content);
219 219
 			//check whether need save the page into cache.
220
-			if($cachePageStatus){
220
+			if ($cachePageStatus) {
221 221
 				$this->savePageContentIntoCache($content);
222 222
 			}
223 223
 			$content = $this->replaceElapseTimeAndMemoryUsage($content);
224 224
 
225 225
 			//compress the output if is available
226 226
 			$type = null;
227
-			if (self::$_canCompressOutput){
227
+			if (self::$_canCompressOutput) {
228 228
 				$type = 'ob_gzhandler';
229 229
 			}
230 230
 			ob_start($type);
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 		*
241 241
 		* @return boolean whether the page content if available or not
242 242
 		*/
243
-		public function renderFinalPageFromCache(&$cache){
243
+		public function renderFinalPageFromCache(&$cache) {
244 244
 			$logger = self::getLogger();
245 245
 			//the current page cache key for identification
246 246
 			$pageCacheKey = $this->_currentUrlCacheKey;
@@ -248,9 +248,9 @@  discard block
 block discarded – undo
248 248
 			$logger->debug('Checking if the page content for the URL [' . $this->_currentUrl . '] is cached ...');
249 249
 			//get the cache information to prepare header to send to browser
250 250
 			$cacheInfo = $cache->getInfo($pageCacheKey);
251
-			if($cacheInfo){
251
+			if ($cacheInfo) {
252 252
 				$status = $this->sendCacheNotYetExpireInfoToBrowser($cacheInfo);
253
-				if($status === false){
253
+				if ($status === false) {
254 254
 					return $this->sendCachePageContentToBrowser($cache);
255 255
 				}
256 256
 				return true;
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 		* Get the final page to be rendered
264 264
 		* @return string
265 265
 		*/
266
-		public function getFinalPageRendered(){
266
+		public function getFinalPageRendered() {
267 267
 			return $this->_pageRender;
268 268
 		}
269 269
 
@@ -271,14 +271,14 @@  discard block
 block discarded – undo
271 271
 		 * Send the HTTP 404 error if can not found the 
272 272
 		 * routing information for the current request
273 273
 		 */
274
-		public static function send404(){
274
+		public static function send404() {
275 275
 			/********* for logs **************/
276 276
 			//can't use $obj = & get_instance()  here because the global super object will be available until
277 277
 			//the main controller is loaded even for Loader::library('xxxx');
278 278
 			$logger = self::getLogger();
279
-			$request =& class_loader('Request', 'classes');
280
-			$userAgent =& class_loader('Browser');
281
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
279
+			$request = & class_loader('Request', 'classes');
280
+			$userAgent = & class_loader('Browser');
281
+			$browser = $userAgent->getPlatform() . ', ' . $userAgent->getBrowser() . ' ' . $userAgent->getVersion();
282 282
 			
283 283
 			//here can't use Loader::functions just include the helper manually
284 284
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
@@ -288,10 +288,10 @@  discard block
 block discarded – undo
288 288
 			$logger->error($str);
289 289
 			/***********************************/
290 290
 			$path = CORE_VIEWS_PATH . '404.php';
291
-			if(file_exists($path)){
291
+			if (file_exists($path)) {
292 292
 				//compress the output if is available
293 293
 				$type = null;
294
-				if (self::$_canCompressOutput){
294
+				if (self::$_canCompressOutput) {
295 295
 					$type = 'ob_gzhandler';
296 296
 				}
297 297
 				ob_start($type);
@@ -300,8 +300,8 @@  discard block
 block discarded – undo
300 300
 				self::sendHeaders(404);
301 301
 				echo $output;
302 302
 			}
303
-			else{
304
-				show_error('The 404 view [' .$path. '] does not exist');
303
+			else {
304
+				show_error('The 404 view [' . $path . '] does not exist');
305 305
 			}
306 306
 		}
307 307
 
@@ -309,12 +309,12 @@  discard block
 block discarded – undo
309 309
 		 * Display the error to user
310 310
 		 * @param  array  $data the error information
311 311
 		 */
312
-		public static function sendError(array $data = array()){
312
+		public static function sendError(array $data = array()) {
313 313
 			$path = CORE_VIEWS_PATH . 'errors.php';
314
-			if(file_exists($path)){
314
+			if (file_exists($path)) {
315 315
 				//compress the output if is available
316 316
 				$type = null;
317
-				if (self::$_canCompressOutput){
317
+				if (self::$_canCompressOutput) {
318 318
 					$type = 'ob_gzhandler';
319 319
 				}
320 320
 				ob_start($type);
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 				self::sendHeaders(503);
325 325
 				echo $output;
326 326
 			}
327
-			else{
327
+			else {
328 328
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
329 329
 				set_http_status_header(503);
330 330
 				echo 'The error view [' . $path . '] does not exist';
@@ -336,17 +336,17 @@  discard block
 block discarded – undo
336 336
 		 * @param  array $cacheInfo the cache information
337 337
 		 * @return boolean            true if the information is sent otherwise false
338 338
 		 */
339
-		protected function sendCacheNotYetExpireInfoToBrowser($cacheInfo){
340
-			if(! empty($cacheInfo)){
339
+		protected function sendCacheNotYetExpireInfoToBrowser($cacheInfo) {
340
+			if (!empty($cacheInfo)) {
341 341
 				$logger = self::getLogger();
342 342
 				$lastModified = $cacheInfo['mtime'];
343 343
 				$expire = $cacheInfo['expire'];
344 344
 				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
345 345
 				self::setHeader('Pragma', 'public');
346 346
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
347
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
348
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
349
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
347
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
348
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
349
+				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
350 350
 					$logger->info('The cache page content is not yet expire for the URL [' . $this->_currentUrl . '] send 304 header to browser');
351 351
 					self::sendHeaders(304);
352 352
 					return true;
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 		 * @return string          the page content after replace 
362 362
 		 * '{elapsed_time}', '{memory_usage}'
363 363
 		 */
364
-		protected function replaceElapseTimeAndMemoryUsage($content){
364
+		protected function replaceElapseTimeAndMemoryUsage($content) {
365 365
 			//load benchmark class
366 366
 			$benchmark = & class_loader('Benchmark');
367 367
 			
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 		 * @param object $cache the cache instance
378 378
 		 * @return boolean     the status of the operation
379 379
 		 */
380
-		protected function sendCachePageContentToBrowser(&$cache){
380
+		protected function sendCachePageContentToBrowser(&$cache) {
381 381
 			$logger = self::getLogger();
382 382
 			$logger->info('The cache page content is expired or the browser does not send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $this->_currentUrl . '] send cache headers to tell the browser');
383 383
 			self::sendHeaders(200);
@@ -385,13 +385,13 @@  discard block
 block discarded – undo
385 385
 			$pageCacheKey = $this->_currentUrlCacheKey;
386 386
 			//get the cache content
387 387
 			$content = $cache->get($pageCacheKey);
388
-			if($content){
388
+			if ($content) {
389 389
 				$logger->info('The page content for the URL [' . $this->_currentUrl . '] already cached just display it');
390 390
 				$content = $this->replaceElapseTimeAndMemoryUsage($content);
391 391
 				///display the final output
392 392
 				//compress the output if is available
393 393
 				$type = null;
394
-				if (self::$_canCompressOutput){
394
+				if (self::$_canCompressOutput) {
395 395
 					$type = 'ob_gzhandler';
396 396
 				}
397 397
 				ob_start($type);
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 		 * @param  string $content the page content to be saved
410 410
 		 * @return void
411 411
 		 */
412
-		protected function savePageContentIntoCache($content){
412
+		protected function savePageContentIntoCache($content) {
413 413
 			$obj = & get_instance();
414 414
 			$logger = self::getLogger();
415 415
 
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
 			$url = $this->_currentUrl;
418 418
 			//Cache view Time to live in second
419 419
 			$viewCacheTtl = get_config('cache_ttl');
420
-			if (!empty($obj->view_cache_ttl)){
420
+			if (!empty($obj->view_cache_ttl)) {
421 421
 				$viewCacheTtl = $obj->view_cache_ttl;
422 422
 			}
423 423
 			//the cache handler instance
@@ -429,14 +429,14 @@  discard block
 block discarded – undo
429 429
 			
430 430
 			//get the cache information to prepare header to send to browser
431 431
 			$cacheInfo = $cacheInstance->getInfo($cacheKey);
432
-			if($cacheInfo){
432
+			if ($cacheInfo) {
433 433
 				$lastModified = $cacheInfo['mtime'];
434 434
 				$expire = $cacheInfo['expire'];
435 435
 				$maxAge = $expire - time();
436 436
 				self::setHeader('Pragma', 'public');
437 437
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
438
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
439
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
438
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
439
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');	
440 440
 			}
441 441
 		}
442 442
 		
@@ -452,21 +452,21 @@  discard block
 block discarded – undo
452 452
 		 * 	'viewFile' => 'view_file'
453 453
 		 * )
454 454
 		 */
455
-		protected  function getModuleInfoForView($view){
455
+		protected  function getModuleInfoForView($view) {
456 456
 			$module = null;
457 457
 			$viewFile = null;
458 458
 			$obj = & get_instance();
459 459
 			//check if the request class contains module name
460
-			if(strpos($view, '/') !== false){
460
+			if (strpos($view, '/') !== false) {
461 461
 				$viewPath = explode('/', $view);
462
-				if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
462
+				if (isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())) {
463 463
 					$module = $viewPath[0];
464 464
 					array_shift($viewPath);
465 465
 					$view = implode('/', $viewPath);
466 466
 					$viewFile = $view . '.php';
467 467
 				}
468 468
 			}
469
-			if(! $module && !empty($obj->moduleName)){
469
+			if (!$module && !empty($obj->moduleName)) {
470 470
 				$module = $obj->moduleName;
471 471
 			}
472 472
 			return array(
@@ -481,13 +481,13 @@  discard block
 block discarded – undo
481 481
 		 * @see  Response::render
482 482
 		 * @return void|string
483 483
 		 */
484
-		protected  function loadView($path, array $data = array(), $return = false){
484
+		protected  function loadView($path, array $data = array(), $return = false) {
485 485
 			$found = false;
486
-			if(file_exists($path)){
486
+			if (file_exists($path)) {
487 487
 				//super instance
488 488
 				$obj = & get_instance();
489
-				foreach(get_object_vars($obj) as $key => $value){
490
-					if(! isset($this->{$key})){
489
+				foreach (get_object_vars($obj) as $key => $value) {
490
+					if (!isset($this->{$key})) {
491 491
 						$this->{$key} = & $obj->{$key};
492 492
 					}
493 493
 				}
@@ -496,15 +496,15 @@  discard block
 block discarded – undo
496 496
 				//need use require() instead of require_once because can load this view many time
497 497
 				require $path;
498 498
 				$content = ob_get_clean();
499
-				if($return){
499
+				if ($return) {
500 500
 					//remove unused html space 
501 501
 					return preg_replace('~>\s*\n\s*<~', '><', $content);
502 502
 				}
503 503
 				$this->_pageRender .= $content;
504 504
 				$found = true;
505 505
 			}
506
-			if(! $found){
507
-				show_error('Unable to find view [' .$path . ']');
506
+			if (!$found) {
507
+				show_error('Unable to find view [' . $path . ']');
508 508
 			}
509 509
 		}
510 510
 
Please login to merge, or discard this patch.
core/libraries/Html.php 2 patches
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -1,343 +1,343 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Html{
27
+    class Html{
28 28
 
29
-		/**
30
-		 * Generate the html anchor link
31
-		 * @param  string $link       the href attribute value
32
-		 * @param  string $anchor     the displayed anchor
33
-		 * @param  array  $attributes the additional attributes to be added
34
-		 * @param boolean $return whether need return the generated html or just display it directly
35
-		 *
36
-		 * @return string|void             the anchor link generated html if $return is true or display it if not
37
-		 */
38
-		public static function a($link = '', $anchor = null, array $attributes = array(), $return = true){
39
-			$link = Url::site_url($link);
40
-			if(! $anchor){
41
-				$anchor = $link;
42
-			}
43
-			$str = null;
44
-			$str .= '<a href = "'.$link.'"';
45
-			$str .= attributes_to_string($attributes);
46
-			$str .= '>';
47
-			$str .= $anchor;
48
-			$str .= '</a>';
29
+        /**
30
+         * Generate the html anchor link
31
+         * @param  string $link       the href attribute value
32
+         * @param  string $anchor     the displayed anchor
33
+         * @param  array  $attributes the additional attributes to be added
34
+         * @param boolean $return whether need return the generated html or just display it directly
35
+         *
36
+         * @return string|void             the anchor link generated html if $return is true or display it if not
37
+         */
38
+        public static function a($link = '', $anchor = null, array $attributes = array(), $return = true){
39
+            $link = Url::site_url($link);
40
+            if(! $anchor){
41
+                $anchor = $link;
42
+            }
43
+            $str = null;
44
+            $str .= '<a href = "'.$link.'"';
45
+            $str .= attributes_to_string($attributes);
46
+            $str .= '>';
47
+            $str .= $anchor;
48
+            $str .= '</a>';
49 49
 
50
-			if($return){
51
-				return $str;
52
-			}
53
-			echo $str;
54
-		}
50
+            if($return){
51
+                return $str;
52
+            }
53
+            echo $str;
54
+        }
55 55
 		
56
-		/**
57
-		 * Generate an mailto anchor link
58
-		 * @param  string $link       the email address 
59
-		 * @param  string $anchor     the displayed value of the link
60
-		 * @param  array  $attributes the additional attributes to be added
61
-		 * @param boolean $return whether need return the generated html or just display it directly
62
-		 *
63
-		 * @return string|void             the generated html for mailto link if $return is true or display it if not
64
-		 */
65
-		public static function mailto($link, $anchor = null, array $attributes = array(), $return = true){
66
-			if(! $anchor){
67
-				$anchor = $link;
68
-			}
69
-			$str = null;
70
-			$str .= '<a href = "mailto:'.$link.'"';
71
-			$str .= attributes_to_string($attributes);
72
-			$str .= '>';
73
-			$str .= $anchor;
74
-			$str .= '</a>';
56
+        /**
57
+         * Generate an mailto anchor link
58
+         * @param  string $link       the email address 
59
+         * @param  string $anchor     the displayed value of the link
60
+         * @param  array  $attributes the additional attributes to be added
61
+         * @param boolean $return whether need return the generated html or just display it directly
62
+         *
63
+         * @return string|void             the generated html for mailto link if $return is true or display it if not
64
+         */
65
+        public static function mailto($link, $anchor = null, array $attributes = array(), $return = true){
66
+            if(! $anchor){
67
+                $anchor = $link;
68
+            }
69
+            $str = null;
70
+            $str .= '<a href = "mailto:'.$link.'"';
71
+            $str .= attributes_to_string($attributes);
72
+            $str .= '>';
73
+            $str .= $anchor;
74
+            $str .= '</a>';
75 75
 
76
-			if($return){
77
-				return $str;
78
-			}
79
-			echo $str;
80
-		}
76
+            if($return){
77
+                return $str;
78
+            }
79
+            echo $str;
80
+        }
81 81
 
82
-		/**
83
-		 * Generate the html "br" tag  
84
-		 * @param  integer $nb the number of generated "<br />" tag
85
-		 * @param boolean $return whether need return the generated html or just display it directly
86
-		 *
87
-		 * @return string|void      the generated "br" html if $return is true or display it if not
88
-		 */
89
-		public static function br($nb = 1, $return = true){
90
-			$nb = (int) $nb;
91
-			$str = null;
92
-			for ($i = 1; $i <= $nb; $i++) {
93
-				$str .= '<br />';
94
-			}
82
+        /**
83
+         * Generate the html "br" tag  
84
+         * @param  integer $nb the number of generated "<br />" tag
85
+         * @param boolean $return whether need return the generated html or just display it directly
86
+         *
87
+         * @return string|void      the generated "br" html if $return is true or display it if not
88
+         */
89
+        public static function br($nb = 1, $return = true){
90
+            $nb = (int) $nb;
91
+            $str = null;
92
+            for ($i = 1; $i <= $nb; $i++) {
93
+                $str .= '<br />';
94
+            }
95 95
 
96
-			if($return){
97
-				return $str;
98
-			}
99
-			echo $str;
100
-		}
96
+            if($return){
97
+                return $str;
98
+            }
99
+            echo $str;
100
+        }
101 101
 
102
-		/**
103
-		 * Generate the html content for tag "hr"
104
-		 * @param integer $nb the number of generated "<hr />" tag
105
-		 * @param  array   $attributes the tag attributes
106
-		 * @param  boolean $return    whether need return the generated html or just display it directly
107
-		 *
108
-		 * @return string|void the generated "hr" html if $return is true or display it if not.
109
-		 */
110
-		public static function hr($nb = 1, array $attributes = array(), $return = true){
111
-			$nb = (int) $nb;
112
-			$str = null;
113
-			for ($i = 1; $i <= $nb; $i++) {
114
-				$str .= '<hr' .attributes_to_string($attributes). ' />';
115
-			}
116
-			if($return){
117
-				return $str;
118
-			}
119
-			echo $str;
120
-		}
102
+        /**
103
+         * Generate the html content for tag "hr"
104
+         * @param integer $nb the number of generated "<hr />" tag
105
+         * @param  array   $attributes the tag attributes
106
+         * @param  boolean $return    whether need return the generated html or just display it directly
107
+         *
108
+         * @return string|void the generated "hr" html if $return is true or display it if not.
109
+         */
110
+        public static function hr($nb = 1, array $attributes = array(), $return = true){
111
+            $nb = (int) $nb;
112
+            $str = null;
113
+            for ($i = 1; $i <= $nb; $i++) {
114
+                $str .= '<hr' .attributes_to_string($attributes). ' />';
115
+            }
116
+            if($return){
117
+                return $str;
118
+            }
119
+            echo $str;
120
+        }
121 121
 
122
-		/**
123
-		 * Generate the html content for tag like h1, h2, h3, h4, h5 and h6
124
-		 * @param  integer $type       the tag type 1 mean h1, 2 h2, etc,
125
-		 * @param  string  $text       the display text
126
-		 * @param integer $nb the number of generated "<h{1,2,3,4,5,6}>"
127
-		 * @param  array   $attributes the tag attributes
128
-		 * @param  boolean $return    whether need return the generated html or just display it directly
129
-		 *
130
-		 * @return string|void the generated header html if $return is true or display it if not.
131
-		 */
132
-		public static function head($type = 1, $text = null, $nb = 1, array $attributes = array(), $return = true){
133
-			$nb = (int) $nb;
134
-			$type = (int) $type;
135
-			$str = null;
136
-			for ($i = 1; $i <= $nb; $i++) {
137
-				$str .= '<h' . $type . attributes_to_string($attributes). '>' .$text. '</h' . $type . '>';
138
-			}
139
-			if($return){
140
-				return $str;
141
-			}
142
-			echo $str;
143
-		}
122
+        /**
123
+         * Generate the html content for tag like h1, h2, h3, h4, h5 and h6
124
+         * @param  integer $type       the tag type 1 mean h1, 2 h2, etc,
125
+         * @param  string  $text       the display text
126
+         * @param integer $nb the number of generated "<h{1,2,3,4,5,6}>"
127
+         * @param  array   $attributes the tag attributes
128
+         * @param  boolean $return    whether need return the generated html or just display it directly
129
+         *
130
+         * @return string|void the generated header html if $return is true or display it if not.
131
+         */
132
+        public static function head($type = 1, $text = null, $nb = 1, array $attributes = array(), $return = true){
133
+            $nb = (int) $nb;
134
+            $type = (int) $type;
135
+            $str = null;
136
+            for ($i = 1; $i <= $nb; $i++) {
137
+                $str .= '<h' . $type . attributes_to_string($attributes). '>' .$text. '</h' . $type . '>';
138
+            }
139
+            if($return){
140
+                return $str;
141
+            }
142
+            echo $str;
143
+        }
144 144
 
145
-		/**
146
-		 * Generate the html "ul" tag
147
-		 * @param  array   $data the data to use for each "li" tag
148
-		 * @param  array   $attributes   the "ul" properties attribute use the array index below for each tag:
149
-		 *  for ul "ul", for li "li".
150
-		 * @param  boolean $return whether need return the generated html or just display it directly
151
-		 *
152
-		 * @return string|void the generated "ul" html  if $return is true or display it if not.
153
-		 */
154
-		public static function ul($data = array(), $attributes = array(), $return = true){
155
-			if($return){
156
-				return self::buildUlOl($data, $attributes, true, 'ul');
157
-			}
158
-			self::buildUlOl($data, $attributes, false, 'ul');
159
-		}
145
+        /**
146
+         * Generate the html "ul" tag
147
+         * @param  array   $data the data to use for each "li" tag
148
+         * @param  array   $attributes   the "ul" properties attribute use the array index below for each tag:
149
+         *  for ul "ul", for li "li".
150
+         * @param  boolean $return whether need return the generated html or just display it directly
151
+         *
152
+         * @return string|void the generated "ul" html  if $return is true or display it if not.
153
+         */
154
+        public static function ul($data = array(), $attributes = array(), $return = true){
155
+            if($return){
156
+                return self::buildUlOl($data, $attributes, true, 'ul');
157
+            }
158
+            self::buildUlOl($data, $attributes, false, 'ul');
159
+        }
160 160
 
161
-		/**
162
-		 * Generate the html "ol" tag
163
-		 * @param  array   $data the data to use for each "li" tag
164
-		 * @param  array   $attributes   the "ol" properties attribute use the array index below for each tag:
165
-		 *  for ol "ol", for li "li".
166
-		 * @param  boolean $return whether need return the generated html or just display it directly
167
-		 * @return string|void the generated "ol" html  if $return is true or display it if not.
168
-		 */
169
-		public static function ol($data = array(), $attributes = array(), $return = true){
170
-			if($return){
171
-				return self::buildUlOl($data, $attributes, true, 'ol');
172
-			}
173
-			self::buildUlOl($data, $attributes, false, 'ol');
174
-		}
161
+        /**
162
+         * Generate the html "ol" tag
163
+         * @param  array   $data the data to use for each "li" tag
164
+         * @param  array   $attributes   the "ol" properties attribute use the array index below for each tag:
165
+         *  for ol "ol", for li "li".
166
+         * @param  boolean $return whether need return the generated html or just display it directly
167
+         * @return string|void the generated "ol" html  if $return is true or display it if not.
168
+         */
169
+        public static function ol($data = array(), $attributes = array(), $return = true){
170
+            if($return){
171
+                return self::buildUlOl($data, $attributes, true, 'ol');
172
+            }
173
+            self::buildUlOl($data, $attributes, false, 'ol');
174
+        }
175 175
 
176 176
 
177
-		/**
178
-		 * Generate the html "table" tag
179
-		 * @param  array   $headers            the table headers to use between (<thead>)
180
-		 * @param  array   $body the table body values between (<tbody>)
181
-		 * @param  array   $attributes   the table properties attribute use the array index below for each tag:
182
-		 *  for table "table", for thead "thead", for thead tr "thead_tr",
183
-		 *  for thead th "thead_th", for tbody "tbody", for tbody tr "tbody_tr", for tbody td "tbody_td", for tfoot "tfoot",
184
-		 *  for tfoot tr "tfoot_tr", for tfoot th "tfoot_th".
185
-		 * @param boolean $use_footer whether need to generate table footer (<tfoot>) use the $headers values
186
-		 * @param  boolean $return whether need return the generated html or just display it directly
187
-		 * @return string|void the generated "table" html  if $return is true or display it if not.
188
-		 */
189
-		public static function table($headers = array(), $body = array(), $attributes = array(), $use_footer = false, $return = true){
190
-			$headers = (array) $headers;
191
-			$body = (array) $body;
192
-			$str = null;
193
-			$tableAttributes = '';
194
-			if(! empty($attributes['table'])){
195
-				$tableAttributes = ' ' . attributes_to_string($attributes['table']);
196
-			}
197
-			$str .= '<table' . $tableAttributes . '>';
198
-			$str .= self::buildTableHeader($headers, $attributes);
199
-			$str .= self::buildTableBody($body, $attributes);
177
+        /**
178
+         * Generate the html "table" tag
179
+         * @param  array   $headers            the table headers to use between (<thead>)
180
+         * @param  array   $body the table body values between (<tbody>)
181
+         * @param  array   $attributes   the table properties attribute use the array index below for each tag:
182
+         *  for table "table", for thead "thead", for thead tr "thead_tr",
183
+         *  for thead th "thead_th", for tbody "tbody", for tbody tr "tbody_tr", for tbody td "tbody_td", for tfoot "tfoot",
184
+         *  for tfoot tr "tfoot_tr", for tfoot th "tfoot_th".
185
+         * @param boolean $use_footer whether need to generate table footer (<tfoot>) use the $headers values
186
+         * @param  boolean $return whether need return the generated html or just display it directly
187
+         * @return string|void the generated "table" html  if $return is true or display it if not.
188
+         */
189
+        public static function table($headers = array(), $body = array(), $attributes = array(), $use_footer = false, $return = true){
190
+            $headers = (array) $headers;
191
+            $body = (array) $body;
192
+            $str = null;
193
+            $tableAttributes = '';
194
+            if(! empty($attributes['table'])){
195
+                $tableAttributes = ' ' . attributes_to_string($attributes['table']);
196
+            }
197
+            $str .= '<table' . $tableAttributes . '>';
198
+            $str .= self::buildTableHeader($headers, $attributes);
199
+            $str .= self::buildTableBody($body, $attributes);
200 200
 
201
-			if($use_footer){
202
-				$str .= self::buildTableFooter($headers, $attributes);
203
-			}
204
-			$str .= '</table>';
205
-			if($return){
206
-				return $str;
207
-			}
208
-			echo $str;
209
-		}
201
+            if($use_footer){
202
+                $str .= self::buildTableFooter($headers, $attributes);
203
+            }
204
+            $str .= '</table>';
205
+            if($return){
206
+                return $str;
207
+            }
208
+            echo $str;
209
+        }
210 210
 
211
-		/**
212
-		 * This method is used to build the header of the html table
213
-		 * @see  Html::table 
214
-		 * @return string|null
215
-		 */
216
-		protected static function buildTableHeader(array $headers, $attributes = array()){
217
-			$str = null;
218
-			$theadAttributes = '';
219
-			if(! empty($attributes['thead'])){
220
-				$theadAttributes = ' ' . attributes_to_string($attributes['thead']);
221
-			}
222
-			$theadtrAttributes = '';
223
-			if(! empty($attributes['thead_tr'])){
224
-				$theadtrAttributes = ' ' . attributes_to_string($attributes['thead_tr']);
225
-			}
226
-			$thAttributes = '';
227
-			if(! empty($attributes['thead_th'])){
228
-				$thAttributes = ' ' . attributes_to_string($attributes['thead_th']);
229
-			}
230
-			$str .= '<thead' . $theadAttributes .'>';
231
-			$str .= '<tr' . $theadtrAttributes .'>';
232
-			foreach ($headers as $value) {
233
-				$str .= '<th' . $thAttributes .'>' .$value. '</th>';
234
-			}
235
-			$str .= '</tr>';
236
-			$str .= '</thead>';
237
-			return $str;
238
-		}
211
+        /**
212
+         * This method is used to build the header of the html table
213
+         * @see  Html::table 
214
+         * @return string|null
215
+         */
216
+        protected static function buildTableHeader(array $headers, $attributes = array()){
217
+            $str = null;
218
+            $theadAttributes = '';
219
+            if(! empty($attributes['thead'])){
220
+                $theadAttributes = ' ' . attributes_to_string($attributes['thead']);
221
+            }
222
+            $theadtrAttributes = '';
223
+            if(! empty($attributes['thead_tr'])){
224
+                $theadtrAttributes = ' ' . attributes_to_string($attributes['thead_tr']);
225
+            }
226
+            $thAttributes = '';
227
+            if(! empty($attributes['thead_th'])){
228
+                $thAttributes = ' ' . attributes_to_string($attributes['thead_th']);
229
+            }
230
+            $str .= '<thead' . $theadAttributes .'>';
231
+            $str .= '<tr' . $theadtrAttributes .'>';
232
+            foreach ($headers as $value) {
233
+                $str .= '<th' . $thAttributes .'>' .$value. '</th>';
234
+            }
235
+            $str .= '</tr>';
236
+            $str .= '</thead>';
237
+            return $str;
238
+        }
239 239
 
240
-		/**
241
-		 * This method is used to build the body of the html table
242
-		 * @see  Html::table 
243
-		 * @return string|null
244
-		 */
245
-		protected static function buildTableBody(array $body, $attributes = array()){
246
-			$str = null;
247
-			$tbodyAttributes = '';
248
-			if(! empty($attributes['tbody'])){
249
-				$tbodyAttributes = ' ' . attributes_to_string($attributes['tbody']);
250
-			}
251
-			$tbodytrAttributes = '';
252
-			if(! empty($attributes['tbody_tr'])){
253
-				$tbodytrAttributes = ' ' . attributes_to_string($attributes['tbody_tr']);
254
-			}
255
-			$tbodytdAttributes = '';
256
-			if(! empty($attributes['tbody_td'])){
257
-				$tbodytdAttributes = ' ' . attributes_to_string($attributes['tbody_td']);
258
-			}
259
-			$str .= '<tbody' . $tbodyAttributes .'>';
260
-			$str .= self::buildTableBodyContent($body, $tbodytrAttributes, $tbodytdAttributes);
261
-			$str .= '</tbody>';
262
-			return $str;
263
-		}
240
+        /**
241
+         * This method is used to build the body of the html table
242
+         * @see  Html::table 
243
+         * @return string|null
244
+         */
245
+        protected static function buildTableBody(array $body, $attributes = array()){
246
+            $str = null;
247
+            $tbodyAttributes = '';
248
+            if(! empty($attributes['tbody'])){
249
+                $tbodyAttributes = ' ' . attributes_to_string($attributes['tbody']);
250
+            }
251
+            $tbodytrAttributes = '';
252
+            if(! empty($attributes['tbody_tr'])){
253
+                $tbodytrAttributes = ' ' . attributes_to_string($attributes['tbody_tr']);
254
+            }
255
+            $tbodytdAttributes = '';
256
+            if(! empty($attributes['tbody_td'])){
257
+                $tbodytdAttributes = ' ' . attributes_to_string($attributes['tbody_td']);
258
+            }
259
+            $str .= '<tbody' . $tbodyAttributes .'>';
260
+            $str .= self::buildTableBodyContent($body, $tbodytrAttributes, $tbodytdAttributes);
261
+            $str .= '</tbody>';
262
+            return $str;
263
+        }
264 264
 
265
-		/**
266
-		 * This method is used to build the body content of the html table
267
-		 * @param  array  $body              the table body data
268
-		 * @param  string $tbodytrAttributes the html attributes for each tr in tbody
269
-		 * @param  string $tbodytdAttributes the html attributes for each td in tbody
270
-		 * @return string                    
271
-		 */
272
-		protected static function buildTableBodyContent(array $body, $tbodytrAttributes, $tbodytdAttributes){
273
-			$str = null;
274
-			foreach ($body as $row) {
275
-				if(is_array($row)){
276
-					$str .= '<tr' . $tbodytrAttributes .'>';
277
-					foreach ($row as $value) {
278
-						$str .= '<td' . $tbodytdAttributes .'>' .$value. '</td>';	
279
-					}
280
-					$str .= '</tr>';
281
-				}
282
-			}
283
-			return $str;
284
-		}
265
+        /**
266
+         * This method is used to build the body content of the html table
267
+         * @param  array  $body              the table body data
268
+         * @param  string $tbodytrAttributes the html attributes for each tr in tbody
269
+         * @param  string $tbodytdAttributes the html attributes for each td in tbody
270
+         * @return string                    
271
+         */
272
+        protected static function buildTableBodyContent(array $body, $tbodytrAttributes, $tbodytdAttributes){
273
+            $str = null;
274
+            foreach ($body as $row) {
275
+                if(is_array($row)){
276
+                    $str .= '<tr' . $tbodytrAttributes .'>';
277
+                    foreach ($row as $value) {
278
+                        $str .= '<td' . $tbodytdAttributes .'>' .$value. '</td>';	
279
+                    }
280
+                    $str .= '</tr>';
281
+                }
282
+            }
283
+            return $str;
284
+        }
285 285
 
286
-		/**
287
-		 * This method is used to build the footer of the html table
288
-		 * @see  Html::table 
289
-		 * @return string|null
290
-		 */
291
-		protected static function buildTableFooter(array $footers, $attributes = array()){
292
-			$str = null;
293
-			$tfootAttributes = '';
294
-			if(! empty($attributes['tfoot'])){
295
-				$tfootAttributes = ' ' . attributes_to_string($attributes['tfoot']);
296
-			}
297
-			$tfoottrAttributes = '';
298
-			if(! empty($attributes['tfoot_tr'])){
299
-				$tfoottrAttributes = ' ' . attributes_to_string($attributes['tfoot_tr']);
300
-			}
301
-			$thAttributes = '';
302
-			if(! empty($attributes['tfoot_th'])){
303
-				$thAttributes = ' ' . attributes_to_string($attributes['tfoot_th']);
304
-			}
305
-			$str .= '<tfoot' . $tfootAttributes .'>';
306
-				$str .= '<tr' . $tfoottrAttributes .'>';
307
-				foreach ($footers as $value) {
308
-					$str .= '<th' . $thAttributes .'>' .$value. '</th>';
309
-				}
310
-				$str .= '</tr>';
311
-				$str .= '</tfoot>';
312
-			return $str;
313
-		}
286
+        /**
287
+         * This method is used to build the footer of the html table
288
+         * @see  Html::table 
289
+         * @return string|null
290
+         */
291
+        protected static function buildTableFooter(array $footers, $attributes = array()){
292
+            $str = null;
293
+            $tfootAttributes = '';
294
+            if(! empty($attributes['tfoot'])){
295
+                $tfootAttributes = ' ' . attributes_to_string($attributes['tfoot']);
296
+            }
297
+            $tfoottrAttributes = '';
298
+            if(! empty($attributes['tfoot_tr'])){
299
+                $tfoottrAttributes = ' ' . attributes_to_string($attributes['tfoot_tr']);
300
+            }
301
+            $thAttributes = '';
302
+            if(! empty($attributes['tfoot_th'])){
303
+                $thAttributes = ' ' . attributes_to_string($attributes['tfoot_th']);
304
+            }
305
+            $str .= '<tfoot' . $tfootAttributes .'>';
306
+                $str .= '<tr' . $tfoottrAttributes .'>';
307
+                foreach ($footers as $value) {
308
+                    $str .= '<th' . $thAttributes .'>' .$value. '</th>';
309
+                }
310
+                $str .= '</tr>';
311
+                $str .= '</tfoot>';
312
+            return $str;
313
+        }
314 314
 
315
-		/**
316
-		 * Return the HTML content for ol or ul tags
317
-		 * @see  Html::ol
318
-		 * @see  Html::ul
319
-		 * @param  string  $olul   the type 'ol' or 'ul'
320
-		 * @return void|string
321
-		 */
322
-		protected static function buildUlOl($data = array(), $attributes = array(), $return = true, $olul = 'ul'){
323
-			$data = (array) $data;
324
-			$str = null;
325
-			$olulAttributes = '';
326
-			if(! empty($attributes[$olul])){
327
-				$olulAttributes = ' ' . attributes_to_string($attributes[$olul]);
328
-			}
329
-			$liAttributes = '';
330
-			if(! empty($attributes['li'])){
331
-				$liAttributes = ' ' . attributes_to_string($attributes['li']);
332
-			}
333
-			$str .= '<' . $olul . $olulAttributes . '>';
334
-			foreach ($data as $row) {
335
-				$str .= '<li' . $liAttributes .'>' .$row. '</li>';
336
-			}
337
-			$str .= '</' . $olul . '>';
338
-			if($return){
339
-				return $str;
340
-			}
341
-			echo $str;
342
-		}
343
-	}
315
+        /**
316
+         * Return the HTML content for ol or ul tags
317
+         * @see  Html::ol
318
+         * @see  Html::ul
319
+         * @param  string  $olul   the type 'ol' or 'ul'
320
+         * @return void|string
321
+         */
322
+        protected static function buildUlOl($data = array(), $attributes = array(), $return = true, $olul = 'ul'){
323
+            $data = (array) $data;
324
+            $str = null;
325
+            $olulAttributes = '';
326
+            if(! empty($attributes[$olul])){
327
+                $olulAttributes = ' ' . attributes_to_string($attributes[$olul]);
328
+            }
329
+            $liAttributes = '';
330
+            if(! empty($attributes['li'])){
331
+                $liAttributes = ' ' . attributes_to_string($attributes['li']);
332
+            }
333
+            $str .= '<' . $olul . $olulAttributes . '>';
334
+            foreach ($data as $row) {
335
+                $str .= '<li' . $liAttributes .'>' .$row. '</li>';
336
+            }
337
+            $str .= '</' . $olul . '>';
338
+            if($return){
339
+                return $str;
340
+            }
341
+            echo $str;
342
+        }
343
+    }
Please login to merge, or discard this patch.
Spacing   +53 added lines, -53 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 Html{
27
+	class Html {
28 28
 
29 29
 		/**
30 30
 		 * Generate the html anchor link
@@ -35,19 +35,19 @@  discard block
 block discarded – undo
35 35
 		 *
36 36
 		 * @return string|void             the anchor link generated html if $return is true or display it if not
37 37
 		 */
38
-		public static function a($link = '', $anchor = null, array $attributes = array(), $return = true){
38
+		public static function a($link = '', $anchor = null, array $attributes = array(), $return = true) {
39 39
 			$link = Url::site_url($link);
40
-			if(! $anchor){
40
+			if (!$anchor) {
41 41
 				$anchor = $link;
42 42
 			}
43 43
 			$str = null;
44
-			$str .= '<a href = "'.$link.'"';
44
+			$str .= '<a href = "' . $link . '"';
45 45
 			$str .= attributes_to_string($attributes);
46 46
 			$str .= '>';
47 47
 			$str .= $anchor;
48 48
 			$str .= '</a>';
49 49
 
50
-			if($return){
50
+			if ($return) {
51 51
 				return $str;
52 52
 			}
53 53
 			echo $str;
@@ -62,18 +62,18 @@  discard block
 block discarded – undo
62 62
 		 *
63 63
 		 * @return string|void             the generated html for mailto link if $return is true or display it if not
64 64
 		 */
65
-		public static function mailto($link, $anchor = null, array $attributes = array(), $return = true){
66
-			if(! $anchor){
65
+		public static function mailto($link, $anchor = null, array $attributes = array(), $return = true) {
66
+			if (!$anchor) {
67 67
 				$anchor = $link;
68 68
 			}
69 69
 			$str = null;
70
-			$str .= '<a href = "mailto:'.$link.'"';
70
+			$str .= '<a href = "mailto:' . $link . '"';
71 71
 			$str .= attributes_to_string($attributes);
72 72
 			$str .= '>';
73 73
 			$str .= $anchor;
74 74
 			$str .= '</a>';
75 75
 
76
-			if($return){
76
+			if ($return) {
77 77
 				return $str;
78 78
 			}
79 79
 			echo $str;
@@ -86,14 +86,14 @@  discard block
 block discarded – undo
86 86
 		 *
87 87
 		 * @return string|void      the generated "br" html if $return is true or display it if not
88 88
 		 */
89
-		public static function br($nb = 1, $return = true){
89
+		public static function br($nb = 1, $return = true) {
90 90
 			$nb = (int) $nb;
91 91
 			$str = null;
92 92
 			for ($i = 1; $i <= $nb; $i++) {
93 93
 				$str .= '<br />';
94 94
 			}
95 95
 
96
-			if($return){
96
+			if ($return) {
97 97
 				return $str;
98 98
 			}
99 99
 			echo $str;
@@ -107,13 +107,13 @@  discard block
 block discarded – undo
107 107
 		 *
108 108
 		 * @return string|void the generated "hr" html if $return is true or display it if not.
109 109
 		 */
110
-		public static function hr($nb = 1, array $attributes = array(), $return = true){
110
+		public static function hr($nb = 1, array $attributes = array(), $return = true) {
111 111
 			$nb = (int) $nb;
112 112
 			$str = null;
113 113
 			for ($i = 1; $i <= $nb; $i++) {
114
-				$str .= '<hr' .attributes_to_string($attributes). ' />';
114
+				$str .= '<hr' . attributes_to_string($attributes) . ' />';
115 115
 			}
116
-			if($return){
116
+			if ($return) {
117 117
 				return $str;
118 118
 			}
119 119
 			echo $str;
@@ -129,14 +129,14 @@  discard block
 block discarded – undo
129 129
 		 *
130 130
 		 * @return string|void the generated header html if $return is true or display it if not.
131 131
 		 */
132
-		public static function head($type = 1, $text = null, $nb = 1, array $attributes = array(), $return = true){
132
+		public static function head($type = 1, $text = null, $nb = 1, array $attributes = array(), $return = true) {
133 133
 			$nb = (int) $nb;
134 134
 			$type = (int) $type;
135 135
 			$str = null;
136 136
 			for ($i = 1; $i <= $nb; $i++) {
137
-				$str .= '<h' . $type . attributes_to_string($attributes). '>' .$text. '</h' . $type . '>';
137
+				$str .= '<h' . $type . attributes_to_string($attributes) . '>' . $text . '</h' . $type . '>';
138 138
 			}
139
-			if($return){
139
+			if ($return) {
140 140
 				return $str;
141 141
 			}
142 142
 			echo $str;
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
 		 *
152 152
 		 * @return string|void the generated "ul" html  if $return is true or display it if not.
153 153
 		 */
154
-		public static function ul($data = array(), $attributes = array(), $return = true){
155
-			if($return){
154
+		public static function ul($data = array(), $attributes = array(), $return = true) {
155
+			if ($return) {
156 156
 				return self::buildUlOl($data, $attributes, true, 'ul');
157 157
 			}
158 158
 			self::buildUlOl($data, $attributes, false, 'ul');
@@ -166,8 +166,8 @@  discard block
 block discarded – undo
166 166
 		 * @param  boolean $return whether need return the generated html or just display it directly
167 167
 		 * @return string|void the generated "ol" html  if $return is true or display it if not.
168 168
 		 */
169
-		public static function ol($data = array(), $attributes = array(), $return = true){
170
-			if($return){
169
+		public static function ol($data = array(), $attributes = array(), $return = true) {
170
+			if ($return) {
171 171
 				return self::buildUlOl($data, $attributes, true, 'ol');
172 172
 			}
173 173
 			self::buildUlOl($data, $attributes, false, 'ol');
@@ -186,23 +186,23 @@  discard block
 block discarded – undo
186 186
 		 * @param  boolean $return whether need return the generated html or just display it directly
187 187
 		 * @return string|void the generated "table" html  if $return is true or display it if not.
188 188
 		 */
189
-		public static function table($headers = array(), $body = array(), $attributes = array(), $use_footer = false, $return = true){
189
+		public static function table($headers = array(), $body = array(), $attributes = array(), $use_footer = false, $return = true) {
190 190
 			$headers = (array) $headers;
191 191
 			$body = (array) $body;
192 192
 			$str = null;
193 193
 			$tableAttributes = '';
194
-			if(! empty($attributes['table'])){
194
+			if (!empty($attributes['table'])) {
195 195
 				$tableAttributes = ' ' . attributes_to_string($attributes['table']);
196 196
 			}
197 197
 			$str .= '<table' . $tableAttributes . '>';
198 198
 			$str .= self::buildTableHeader($headers, $attributes);
199 199
 			$str .= self::buildTableBody($body, $attributes);
200 200
 
201
-			if($use_footer){
201
+			if ($use_footer) {
202 202
 				$str .= self::buildTableFooter($headers, $attributes);
203 203
 			}
204 204
 			$str .= '</table>';
205
-			if($return){
205
+			if ($return) {
206 206
 				return $str;
207 207
 			}
208 208
 			echo $str;
@@ -213,24 +213,24 @@  discard block
 block discarded – undo
213 213
 		 * @see  Html::table 
214 214
 		 * @return string|null
215 215
 		 */
216
-		protected static function buildTableHeader(array $headers, $attributes = array()){
216
+		protected static function buildTableHeader(array $headers, $attributes = array()) {
217 217
 			$str = null;
218 218
 			$theadAttributes = '';
219
-			if(! empty($attributes['thead'])){
219
+			if (!empty($attributes['thead'])) {
220 220
 				$theadAttributes = ' ' . attributes_to_string($attributes['thead']);
221 221
 			}
222 222
 			$theadtrAttributes = '';
223
-			if(! empty($attributes['thead_tr'])){
223
+			if (!empty($attributes['thead_tr'])) {
224 224
 				$theadtrAttributes = ' ' . attributes_to_string($attributes['thead_tr']);
225 225
 			}
226 226
 			$thAttributes = '';
227
-			if(! empty($attributes['thead_th'])){
227
+			if (!empty($attributes['thead_th'])) {
228 228
 				$thAttributes = ' ' . attributes_to_string($attributes['thead_th']);
229 229
 			}
230
-			$str .= '<thead' . $theadAttributes .'>';
231
-			$str .= '<tr' . $theadtrAttributes .'>';
230
+			$str .= '<thead' . $theadAttributes . '>';
231
+			$str .= '<tr' . $theadtrAttributes . '>';
232 232
 			foreach ($headers as $value) {
233
-				$str .= '<th' . $thAttributes .'>' .$value. '</th>';
233
+				$str .= '<th' . $thAttributes . '>' . $value . '</th>';
234 234
 			}
235 235
 			$str .= '</tr>';
236 236
 			$str .= '</thead>';
@@ -242,21 +242,21 @@  discard block
 block discarded – undo
242 242
 		 * @see  Html::table 
243 243
 		 * @return string|null
244 244
 		 */
245
-		protected static function buildTableBody(array $body, $attributes = array()){
245
+		protected static function buildTableBody(array $body, $attributes = array()) {
246 246
 			$str = null;
247 247
 			$tbodyAttributes = '';
248
-			if(! empty($attributes['tbody'])){
248
+			if (!empty($attributes['tbody'])) {
249 249
 				$tbodyAttributes = ' ' . attributes_to_string($attributes['tbody']);
250 250
 			}
251 251
 			$tbodytrAttributes = '';
252
-			if(! empty($attributes['tbody_tr'])){
252
+			if (!empty($attributes['tbody_tr'])) {
253 253
 				$tbodytrAttributes = ' ' . attributes_to_string($attributes['tbody_tr']);
254 254
 			}
255 255
 			$tbodytdAttributes = '';
256
-			if(! empty($attributes['tbody_td'])){
256
+			if (!empty($attributes['tbody_td'])) {
257 257
 				$tbodytdAttributes = ' ' . attributes_to_string($attributes['tbody_td']);
258 258
 			}
259
-			$str .= '<tbody' . $tbodyAttributes .'>';
259
+			$str .= '<tbody' . $tbodyAttributes . '>';
260 260
 			$str .= self::buildTableBodyContent($body, $tbodytrAttributes, $tbodytdAttributes);
261 261
 			$str .= '</tbody>';
262 262
 			return $str;
@@ -269,13 +269,13 @@  discard block
 block discarded – undo
269 269
 		 * @param  string $tbodytdAttributes the html attributes for each td in tbody
270 270
 		 * @return string                    
271 271
 		 */
272
-		protected static function buildTableBodyContent(array $body, $tbodytrAttributes, $tbodytdAttributes){
272
+		protected static function buildTableBodyContent(array $body, $tbodytrAttributes, $tbodytdAttributes) {
273 273
 			$str = null;
274 274
 			foreach ($body as $row) {
275
-				if(is_array($row)){
276
-					$str .= '<tr' . $tbodytrAttributes .'>';
275
+				if (is_array($row)) {
276
+					$str .= '<tr' . $tbodytrAttributes . '>';
277 277
 					foreach ($row as $value) {
278
-						$str .= '<td' . $tbodytdAttributes .'>' .$value. '</td>';	
278
+						$str .= '<td' . $tbodytdAttributes . '>' . $value . '</td>';	
279 279
 					}
280 280
 					$str .= '</tr>';
281 281
 				}
@@ -288,24 +288,24 @@  discard block
 block discarded – undo
288 288
 		 * @see  Html::table 
289 289
 		 * @return string|null
290 290
 		 */
291
-		protected static function buildTableFooter(array $footers, $attributes = array()){
291
+		protected static function buildTableFooter(array $footers, $attributes = array()) {
292 292
 			$str = null;
293 293
 			$tfootAttributes = '';
294
-			if(! empty($attributes['tfoot'])){
294
+			if (!empty($attributes['tfoot'])) {
295 295
 				$tfootAttributes = ' ' . attributes_to_string($attributes['tfoot']);
296 296
 			}
297 297
 			$tfoottrAttributes = '';
298
-			if(! empty($attributes['tfoot_tr'])){
298
+			if (!empty($attributes['tfoot_tr'])) {
299 299
 				$tfoottrAttributes = ' ' . attributes_to_string($attributes['tfoot_tr']);
300 300
 			}
301 301
 			$thAttributes = '';
302
-			if(! empty($attributes['tfoot_th'])){
302
+			if (!empty($attributes['tfoot_th'])) {
303 303
 				$thAttributes = ' ' . attributes_to_string($attributes['tfoot_th']);
304 304
 			}
305
-			$str .= '<tfoot' . $tfootAttributes .'>';
306
-				$str .= '<tr' . $tfoottrAttributes .'>';
305
+			$str .= '<tfoot' . $tfootAttributes . '>';
306
+				$str .= '<tr' . $tfoottrAttributes . '>';
307 307
 				foreach ($footers as $value) {
308
-					$str .= '<th' . $thAttributes .'>' .$value. '</th>';
308
+					$str .= '<th' . $thAttributes . '>' . $value . '</th>';
309 309
 				}
310 310
 				$str .= '</tr>';
311 311
 				$str .= '</tfoot>';
@@ -319,23 +319,23 @@  discard block
 block discarded – undo
319 319
 		 * @param  string  $olul   the type 'ol' or 'ul'
320 320
 		 * @return void|string
321 321
 		 */
322
-		protected static function buildUlOl($data = array(), $attributes = array(), $return = true, $olul = 'ul'){
322
+		protected static function buildUlOl($data = array(), $attributes = array(), $return = true, $olul = 'ul') {
323 323
 			$data = (array) $data;
324 324
 			$str = null;
325 325
 			$olulAttributes = '';
326
-			if(! empty($attributes[$olul])){
326
+			if (!empty($attributes[$olul])) {
327 327
 				$olulAttributes = ' ' . attributes_to_string($attributes[$olul]);
328 328
 			}
329 329
 			$liAttributes = '';
330
-			if(! empty($attributes['li'])){
330
+			if (!empty($attributes['li'])) {
331 331
 				$liAttributes = ' ' . attributes_to_string($attributes['li']);
332 332
 			}
333 333
 			$str .= '<' . $olul . $olulAttributes . '>';
334 334
 			foreach ($data as $row) {
335
-				$str .= '<li' . $liAttributes .'>' .$row. '</li>';
335
+				$str .= '<li' . $liAttributes . '>' . $row . '</li>';
336 336
 			}
337 337
 			$str .= '</' . $olul . '>';
338
-			if($return){
338
+			if ($return) {
339 339
 				return $str;
340 340
 			}
341 341
 			echo $str;
Please login to merge, or discard this patch.
core/classes/model/Model.php 3 patches
Indentation   +126 added lines, -126 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
             }
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
         {
371 371
             $data = $this->trigger('before_update', $data);
372 372
             $this->getQueryBuilder()->from($this->_table);
373
-			$result = $this->_database->update($data, $escape);
373
+            $result = $this->_database->update($data, $escape);
374 374
             $this->trigger('after_update', array($data, $result));
375 375
             return $result;
376 376
         }
@@ -382,16 +382,16 @@  discard block
 block discarded – undo
382 382
         {
383 383
             $this->trigger('before_delete', $id);
384 384
             $this->getQueryBuilder()->where($this->primary_key, $id);
385
-			$result = false;
385
+            $result = false;
386 386
             if ($this->soft_delete)
387 387
             {
388 388
                 $this->getQueryBuilder()->from($this->_table);	
389
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
389
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
390 390
             }
391 391
             else
392 392
             {
393 393
                 $this->getQueryBuilder()->from($this->_table); 
394
-				$result = $this->_database->delete();
394
+                $result = $this->_database->delete();
395 395
             }
396 396
 
397 397
             $this->trigger('after_delete', $result);
@@ -404,18 +404,18 @@  discard block
 block discarded – undo
404 404
         public function delete_by()
405 405
         {
406 406
             $where = func_get_args();
407
-    	    $where = $this->trigger('before_delete', $where);
407
+            $where = $this->trigger('before_delete', $where);
408 408
             $this->_set_where($where);
409
-			$result = false;
409
+            $result = false;
410 410
             if ($this->soft_delete)
411 411
             {
412 412
                 $this->getQueryBuilder()->from($this->_table);	
413
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
413
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
414 414
             }
415 415
             else
416 416
             {
417 417
                 $this->getQueryBuilder()->from($this->_table); 
418
-				$result = $this->_database->delete();
418
+                $result = $this->_database->delete();
419 419
             }
420 420
             $this->trigger('after_delete', $result);
421 421
             return $result;
@@ -428,16 +428,16 @@  discard block
 block discarded – undo
428 428
         {
429 429
             $primary_values = $this->trigger('before_delete', $primary_values);
430 430
             $this->getQueryBuilder()->in($this->primary_key, $primary_values);
431
-			$result = false;
431
+            $result = false;
432 432
             if ($this->soft_delete)
433 433
             {
434 434
                 $this->getQueryBuilder()->from($this->_table);	
435
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
435
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
436 436
             }
437 437
             else
438 438
             {
439 439
                 $this->getQueryBuilder()->from($this->_table); 
440
-				$result = $this->_database->delete();
440
+                $result = $this->_database->delete();
441 441
             }
442 442
             $this->trigger('after_delete', $result);
443 443
             return $result;
@@ -449,8 +449,8 @@  discard block
 block discarded – undo
449 449
          */
450 450
         public function truncate()
451 451
         {
452
-			$this->getQueryBuilder()->from($this->_table); 
453
-			$result = $this->_database->delete();
452
+            $this->getQueryBuilder()->from($this->_table); 
453
+            $result = $this->_database->delete();
454 454
             return $result;
455 455
         }
456 456
 
@@ -468,14 +468,14 @@  discard block
 block discarded – undo
468 468
             return $this;
469 469
         }
470 470
 		
471
-		/**
472
-		* Relationship
473
-		*/
471
+        /**
472
+         * Relationship
473
+         */
474 474
         public function relate($row)
475 475
         {
476
-    		if (empty($row))
476
+            if (empty($row))
477 477
             {
478
-    		    return $row;
478
+                return $row;
479 479
             }
480 480
 
481 481
             $row = $this->relateBelongsTo($row);
@@ -508,9 +508,9 @@  discard block
 block discarded – undo
508 508
                 $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
509 509
             }
510 510
             $this->getQueryBuilder()
511
-									 ->select(array($key, $value))
512
-									 ->from($this->_table);
513
-			$result = $this->_database->getAll();
511
+                                        ->select(array($key, $value))
512
+                                        ->from($this->_table);
513
+            $result = $this->_database->getAll();
514 514
             $options = array();
515 515
             foreach ($result as $row)
516 516
             {
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
             $where = func_get_args();
533 533
             $this->_set_where($where);
534 534
             $this->getQueryBuilder()->from($this->_table);
535
-			$this->_database->getAll();
535
+            $this->_database->getAll();
536 536
             return $this->_database->numRows();
537 537
         }
538 538
 
@@ -545,20 +545,20 @@  discard block
 block discarded – undo
545 545
             {
546 546
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
547 547
             }
548
-			$this->getQueryBuilder()->from($this->_table);
549
-			$this->_database->getAll();
548
+            $this->getQueryBuilder()->from($this->_table);
549
+            $this->_database->getAll();
550 550
             return $this->_database->numRows();
551 551
         }
552 552
 		
553
-		/**
554
-		* Enabled cache temporary
555
-		*/
556
-		public function cached($ttl = 0){
557
-		  if ($ttl > 0){
558
-			$this->_database = $this->_database->cached($ttl);
559
-		  }
560
-		  return $this;
561
-		}
553
+        /**
554
+         * Enabled cache temporary
555
+         */
556
+        public function cached($ttl = 0){
557
+            if ($ttl > 0){
558
+            $this->_database = $this->_database->cached($ttl);
559
+            }
560
+            return $this;
561
+        }
562 562
 
563 563
         /**
564 564
          * Tell the class to skip the insert validation
@@ -582,10 +582,10 @@  discard block
 block discarded – undo
582 582
          */
583 583
         public function get_next_id()
584 584
         {
585
-			$this->getQueryBuilder()->select('AUTO_INCREMENT')
586
-									->from('information_schema.TABLES')
587
-									->where('TABLE_NAME', $this->_table)
588
-									->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
585
+            $this->getQueryBuilder()->select('AUTO_INCREMENT')
586
+                                    ->from('information_schema.TABLES')
587
+                                    ->where('TABLE_NAME', $this->_table)
588
+                                    ->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
589 589
             return (int) $this->_database->get()->AUTO_INCREMENT;
590 590
         }
591 591
 
@@ -708,24 +708,24 @@  discard block
 block discarded – undo
708 708
             {
709 709
                 if (is_object($row))
710 710
                 {
711
-					if (isset($row->$attr)){
712
-						unset($row->$attr);
713
-					}
711
+                    if (isset($row->$attr)){
712
+                        unset($row->$attr);
713
+                    }
714 714
                 }
715 715
                 else
716 716
                 {
717
-					if (isset($row[$attr])){
718
-						unset($row[$attr]);
719
-					}
717
+                    if (isset($row[$attr])){
718
+                        unset($row[$attr]);
719
+                    }
720 720
                 }
721 721
             }
722 722
             return $row;
723 723
         }
724 724
 		
725
-		 /**
726
-         * Return the database instance
727
-         * @return Database the database instance
728
-         */
725
+            /**
726
+             * Return the database instance
727
+             * @return Database the database instance
728
+             */
729 729
         public function getDatabaseInstance(){
730 730
             return $this->_database;
731 731
         }
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
          * set the Database instance for future use
735 735
          * @param Database $db the database object
736 736
          */
737
-         public function setDatabaseInstance($db){
737
+            public function setDatabaseInstance($db){
738 738
             $this->_database = $db;
739 739
             if ($this->dbCacheTime > 0){
740 740
                 $this->_database->setCache($this->dbCacheTime);
@@ -753,14 +753,14 @@  discard block
 block discarded – undo
753 753
         /**
754 754
          * Set the loader instance for future use
755 755
          * @param Loader $loader the loader object
756
-		 * @return object
756
+         * @return object
757 757
          */
758
-         public function setLoader($loader){
758
+            public function setLoader($loader){
759 759
             $this->loaderInstance = $loader;
760 760
             return $this;
761 761
         }
762 762
 
763
-		/**
763
+        /**
764 764
          * Return the queryBuilder instance this is the shortcut to database queryBuilder
765 765
          * @return object the DatabaseQueryBuilder instance
766 766
          */
@@ -771,9 +771,9 @@  discard block
 block discarded – undo
771 771
         /**
772 772
          * Set the DatabaseQueryBuilder instance for future use
773 773
          * @param object $queryBuilder the DatabaseQueryBuilder object
774
-		 * @return object
774
+         * @return object
775 775
          */
776
-         public function setQueryBuilder($queryBuilder){
776
+            public function setQueryBuilder($queryBuilder){
777 777
             $this->_database->setQueryBuilder($queryBuilder);
778 778
             return $this;
779 779
         }
@@ -790,9 +790,9 @@  discard block
 block discarded – undo
790 790
         /**
791 791
          * Set the form validation instance for future use
792 792
          * @param FormValidation $fv the form validation object
793
-		 * @return object
793
+         * @return object
794 794
          */
795
-         public function setFormValidation($fv){
795
+            public function setFormValidation($fv){
796 796
             $this->formValidationInstance = $fv;
797 797
             return $this;
798 798
         }
@@ -833,12 +833,12 @@  discard block
 block discarded – undo
833 833
          * INTERNAL METHODS
834 834
          * ------------------------------------------------------------ */
835 835
 
836
-		/**
837
-		* relate for the relation "belongs_to"
838
-		* @return mixed
839
-		*/
840
-		protected function relateBelongsTo($row){
841
-			foreach ($this->belongs_to as $key => $value)
836
+        /**
837
+         * relate for the relation "belongs_to"
838
+         * @return mixed
839
+         */
840
+        protected function relateBelongsTo($row){
841
+            foreach ($this->belongs_to as $key => $value)
842 842
             {
843 843
                 if (is_string($value))
844 844
                 {
@@ -869,15 +869,15 @@  discard block
 block discarded – undo
869 869
                     }
870 870
                 }
871 871
             }
872
-			return $row;
873
-		}
874
-
875
-		/**
876
-		* relate for the relation "has_many"
877
-		* @return mixed
878
-		*/
879
-		protected function relateHasMany($row){
880
-			foreach ($this->has_many as $key => $value)
872
+            return $row;
873
+        }
874
+
875
+        /**
876
+         * relate for the relation "has_many"
877
+         * @return mixed
878
+         */
879
+        protected function relateHasMany($row){
880
+            foreach ($this->has_many as $key => $value)
881 881
             {
882 882
                 if (is_string($value))
883 883
                 {
@@ -908,8 +908,8 @@  discard block
 block discarded – undo
908 908
                     }
909 909
                 }
910 910
             }
911
-			return $row;
912
-		}
911
+            return $row;
912
+        }
913 913
 		
914 914
         /**
915 915
          * Trigger an event and call its observers. Pass through the event name
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
             }
946 946
             $fv = $this->formValidationInstance;
947 947
             if (! is_object($fv)){
948
-                 Loader::library('FormValidation');
948
+                    Loader::library('FormValidation');
949 949
                 $fv = $this->formvalidation;
950 950
                 $this->setFormValidation($fv);  
951 951
             }
@@ -960,30 +960,30 @@  discard block
 block discarded – undo
960 960
         }
961 961
 		
962 962
 		
963
-		/**
964
-		* Set WHERE parameters, when is array
965
-		* @param array $params
966
-		*/
967
-		protected function _set_where_array(array $params){
968
-			foreach ($params as $field => $filter)
969
-			{
970
-				if (is_array($filter))
971
-				{
972
-					$this->getQueryBuilder()->in($field, $filter);
973
-				}
974
-				else
975
-				{
976
-					if (is_int($field))
977
-					{
978
-						$this->getQueryBuilder()->where($filter);
979
-					}
980
-					else
981
-					{
982
-						$this->getQueryBuilder()->where($field, $filter);
983
-					}
984
-				}
985
-			}
986
-		}
963
+        /**
964
+         * Set WHERE parameters, when is array
965
+         * @param array $params
966
+         */
967
+        protected function _set_where_array(array $params){
968
+            foreach ($params as $field => $filter)
969
+            {
970
+                if (is_array($filter))
971
+                {
972
+                    $this->getQueryBuilder()->in($field, $filter);
973
+                }
974
+                else
975
+                {
976
+                    if (is_int($field))
977
+                    {
978
+                        $this->getQueryBuilder()->where($filter);
979
+                    }
980
+                    else
981
+                    {
982
+                        $this->getQueryBuilder()->where($field, $filter);
983
+                    }
984
+                }
985
+            }
986
+        }
987 987
 
988 988
 
989 989
         /**
@@ -999,8 +999,8 @@  discard block
 block discarded – undo
999 999
             {
1000 1000
                 $this->getQueryBuilder()->where($params[0]);
1001 1001
             }
1002
-        	else if (count($params) == 2)
1003
-    		{
1002
+            else if (count($params) == 2)
1003
+            {
1004 1004
                 if (is_array($params[1]))
1005 1005
                 {
1006 1006
                     $this->getQueryBuilder()->in($params[0], $params[1]);
@@ -1009,11 +1009,11 @@  discard block
 block discarded – undo
1009 1009
                 {
1010 1010
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1011 1011
                 }
1012
-    		}
1013
-    		else if (count($params) == 3)
1014
-    		{
1015
-    			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1016
-    		}
1012
+            }
1013
+            else if (count($params) == 3)
1014
+            {
1015
+                $this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1016
+            }
1017 1017
             else
1018 1018
             {
1019 1019
                 if (is_array($params[1]))
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
 
1030 1030
         /**
1031 1031
             Shortcut to controller
1032
-        */
1032
+         */
1033 1033
         public function __get($key){
1034 1034
             return get_instance()->{$key};
1035 1035
         }
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 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
@@ -145,13 +145,13 @@  discard block
 block discarded – undo
145 145
          * Initialise the model, tie into the CodeIgniter superobject and
146 146
          * try our best to guess the table name.
147 147
          */
148
-        public function __construct(Database $db = null){
149
-            if (is_object($db)){
148
+        public function __construct(Database $db = null) {
149
+            if (is_object($db)) {
150 150
                 $this->setDatabaseInstance($db);
151 151
             }
152
-            else{
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 156
                     * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157 157
                     * to prevent duplication
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 
188 188
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
189 189
             {
190
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
190
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
191 191
             }
192 192
     		$this->_set_where($where);
193 193
 
@@ -229,9 +229,9 @@  discard block
 block discarded – undo
229 229
             $this->trigger('before_get');
230 230
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
231 231
             {
232
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
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 236
 			$result = $this->_database->getAll($type);
237 237
             $this->_temporary_return_type = $this->return_type;
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
                 $insert_id = $this->_database->insertId();
265 265
                 $this->trigger('after_create', $insert_id);
266 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;
267
+				return !$insert_id ? true : $insert_id;
268 268
             }
269 269
             else
270 270
             {
@@ -341,13 +341,13 @@  discard block
 block discarded – undo
341 341
         {
342 342
             $args = func_get_args();
343 343
             $data = array();
344
-            if (count($args) == 2){
345
-                if (is_array($args[1])){
344
+            if (count($args) == 2) {
345
+                if (is_array($args[1])) {
346 346
                     $data = array_pop($args);
347 347
                 }
348 348
             }
349
-            else if (count($args) == 3){
350
-                if (is_array($args[2])){
349
+            else if (count($args) == 3) {
350
+                if (is_array($args[2])) {
351 351
                     $data = array_pop($args);
352 352
                 }
353 353
             }
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
             if ($this->soft_delete)
387 387
             {
388 388
                 $this->getQueryBuilder()->from($this->_table);	
389
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
389
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
390 390
             }
391 391
             else
392 392
             {
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
             if ($this->soft_delete)
411 411
             {
412 412
                 $this->getQueryBuilder()->from($this->_table);	
413
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
413
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
414 414
             }
415 415
             else
416 416
             {
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
             if ($this->soft_delete)
433 433
             {
434 434
                 $this->getQueryBuilder()->from($this->_table);	
435
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
435
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
436 436
             }
437 437
             else
438 438
             {
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
                 $key = $this->primary_key;
503 503
                 $value = $args[0];
504 504
             }
505
-            $this->trigger('before_dropdown', array( $key, $value ));
505
+            $this->trigger('before_dropdown', array($key, $value));
506 506
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
507 507
             {
508 508
                 $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
         {
528 528
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
529 529
             {
530
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
530
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
531 531
             }
532 532
             $where = func_get_args();
533 533
             $this->_set_where($where);
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
         {
544 544
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
545 545
             {
546
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
546
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
547 547
             }
548 548
 			$this->getQueryBuilder()->from($this->_table);
549 549
 			$this->_database->getAll();
@@ -553,8 +553,8 @@  discard block
 block discarded – undo
553 553
 		/**
554 554
 		* Enabled cache temporary
555 555
 		*/
556
-		public function cached($ttl = 0){
557
-		  if ($ttl > 0){
556
+		public function cached($ttl = 0) {
557
+		  if ($ttl > 0) {
558 558
 			$this->_database = $this->_database->cached($ttl);
559 559
 		  }
560 560
 		  return $this;
@@ -708,13 +708,13 @@  discard block
 block discarded – undo
708 708
             {
709 709
                 if (is_object($row))
710 710
                 {
711
-					if (isset($row->$attr)){
711
+					if (isset($row->$attr)) {
712 712
 						unset($row->$attr);
713 713
 					}
714 714
                 }
715 715
                 else
716 716
                 {
717
-					if (isset($row[$attr])){
717
+					if (isset($row[$attr])) {
718 718
 						unset($row[$attr]);
719 719
 					}
720 720
                 }
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
          * Return the database instance
727 727
          * @return Database the database instance
728 728
          */
729
-        public function getDatabaseInstance(){
729
+        public function getDatabaseInstance() {
730 730
             return $this->_database;
731 731
         }
732 732
 
@@ -734,9 +734,9 @@  discard block
 block discarded – undo
734 734
          * set the Database instance for future use
735 735
          * @param Database $db the database object
736 736
          */
737
-         public function setDatabaseInstance($db){
737
+         public function setDatabaseInstance($db) {
738 738
             $this->_database = $db;
739
-            if ($this->dbCacheTime > 0){
739
+            if ($this->dbCacheTime > 0) {
740 740
                 $this->_database->setCache($this->dbCacheTime);
741 741
             }
742 742
             return $this;
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
          * Return the loader instance
747 747
          * @return Loader the loader instance
748 748
          */
749
-        public function getLoader(){
749
+        public function getLoader() {
750 750
             return $this->loaderInstance;
751 751
         }
752 752
 
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
          * @param Loader $loader the loader object
756 756
 		 * @return object
757 757
          */
758
-         public function setLoader($loader){
758
+         public function setLoader($loader) {
759 759
             $this->loaderInstance = $loader;
760 760
             return $this;
761 761
         }
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
          * Return the queryBuilder instance this is the shortcut to database queryBuilder
765 765
          * @return object the DatabaseQueryBuilder instance
766 766
          */
767
-        public function getQueryBuilder(){
767
+        public function getQueryBuilder() {
768 768
             return $this->_database->getQueryBuilder();
769 769
         }
770 770
 
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
          * @param object $queryBuilder the DatabaseQueryBuilder object
774 774
 		 * @return object
775 775
          */
776
-         public function setQueryBuilder($queryBuilder){
776
+         public function setQueryBuilder($queryBuilder) {
777 777
             $this->_database->setQueryBuilder($queryBuilder);
778 778
             return $this;
779 779
         }
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
          * Return the FormValidation instance
784 784
          * @return FormValidation the form validation instance
785 785
          */
786
-        public function getFormValidation(){
786
+        public function getFormValidation() {
787 787
             return $this->formValidationInstance;
788 788
         }
789 789
 
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
          * @param FormValidation $fv the form validation object
793 793
 		 * @return object
794 794
          */
795
-         public function setFormValidation($fv){
795
+         public function setFormValidation($fv) {
796 796
             $this->formValidationInstance = $fv;
797 797
             return $this;
798 798
         }
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
          */
807 807
         public function order_by($criteria, $order = 'ASC')
808 808
         {
809
-            if ( is_array($criteria) )
809
+            if (is_array($criteria))
810 810
             {
811 811
                 foreach ($criteria as $key => $value)
812 812
                 {
@@ -837,13 +837,13 @@  discard block
 block discarded – undo
837 837
 		* relate for the relation "belongs_to"
838 838
 		* @return mixed
839 839
 		*/
840
-		protected function relateBelongsTo($row){
840
+		protected function relateBelongsTo($row) {
841 841
 			foreach ($this->belongs_to as $key => $value)
842 842
             {
843 843
                 if (is_string($value))
844 844
                 {
845 845
                     $relationship = $value;
846
-                    $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
846
+                    $options = array('primary_key' => $value . '_id', 'model' => $value . '_model');
847 847
                 }
848 848
                 else
849 849
                 {
@@ -853,10 +853,10 @@  discard block
 block discarded – undo
853 853
 
854 854
                 if (in_array($relationship, $this->_with))
855 855
                 {
856
-                    if (is_object($this->loaderInstance)){
856
+                    if (is_object($this->loaderInstance)) {
857 857
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
858 858
                     }
859
-                    else{
859
+                    else {
860 860
                         Loader::model($options['model'], $relationship . '_model');    
861 861
                     }
862 862
                     if (is_object($row))
@@ -876,13 +876,13 @@  discard block
 block discarded – undo
876 876
 		* relate for the relation "has_many"
877 877
 		* @return mixed
878 878
 		*/
879
-		protected function relateHasMany($row){
879
+		protected function relateHasMany($row) {
880 880
 			foreach ($this->has_many as $key => $value)
881 881
             {
882 882
                 if (is_string($value))
883 883
                 {
884 884
                     $relationship = $value;
885
-                    $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
885
+                    $options = array('primary_key' => $this->_table . '_id', 'model' => $value . '_model');
886 886
                 }
887 887
                 else
888 888
                 {
@@ -892,10 +892,10 @@  discard block
 block discarded – undo
892 892
 
893 893
                 if (in_array($relationship, $this->_with))
894 894
                 {
895
-                    if (is_object($this->loaderInstance)){
895
+                    if (is_object($this->loaderInstance)) {
896 896
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
897 897
                     }
898
-                    else{
898
+                    else {
899 899
                         Loader::model($options['model'], $relationship . '_model');    
900 900
                     }
901 901
                     if (is_object($row))
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
                 return $data;
945 945
             }
946 946
             $fv = $this->formValidationInstance;
947
-            if (! is_object($fv)){
947
+            if (!is_object($fv)) {
948 948
                  Loader::library('FormValidation');
949 949
                 $fv = $this->formvalidation;
950 950
                 $this->setFormValidation($fv);  
@@ -964,7 +964,7 @@  discard block
 block discarded – undo
964 964
 		* Set WHERE parameters, when is array
965 965
 		* @param array $params
966 966
 		*/
967
-		protected function _set_where_array(array $params){
967
+		protected function _set_where_array(array $params) {
968 968
 			foreach ($params as $field => $filter)
969 969
 			{
970 970
 				if (is_array($filter))
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
         /**
1031 1031
             Shortcut to controller
1032 1032
         */
1033
-        public function __get($key){
1033
+        public function __get($key) {
1034 1034
             return get_instance()->{$key};
1035 1035
         }
1036 1036
 
Please login to merge, or discard this patch.
Braces   +28 added lines, -56 removed lines patch added patch discarded remove patch
@@ -148,8 +148,7 @@  discard block
 block discarded – undo
148 148
         public function __construct(Database $db = null){
149 149
             if (is_object($db)){
150 150
                 $this->setDatabaseInstance($db);
151
-            }
152
-            else{
151
+            } else{
153 152
                 $obj = & get_instance();
154 153
         		if (isset($obj->database) && is_object($obj->database)){
155 154
                     /**
@@ -265,8 +264,7 @@  discard block
 block discarded – undo
265 264
                 $this->trigger('after_create', $insert_id);
266 265
 				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
267 266
 				return ! $insert_id ? true : $insert_id;
268
-            }
269
-            else
267
+            } else
270 268
             {
271 269
                 return FALSE;
272 270
             }
@@ -303,8 +301,7 @@  discard block
 block discarded – undo
303 301
                 $result = $this->_database->update($data, $escape);
304 302
                 $this->trigger('after_update', array($data, $result));
305 303
                 return $result;
306
-            }
307
-            else
304
+            } else
308 305
             {
309 306
                 return FALSE;
310 307
             }
@@ -327,8 +324,7 @@  discard block
 block discarded – undo
327 324
 				$result = $this->_database->update($data, $escape);
328 325
                 $this->trigger('after_update', array($data, $result));
329 326
                 return $result;
330
-            }
331
-            else
327
+            } else
332 328
             {
333 329
                 return FALSE;
334 330
             }
@@ -345,8 +341,7 @@  discard block
 block discarded – undo
345 341
                 if (is_array($args[1])){
346 342
                     $data = array_pop($args);
347 343
                 }
348
-            }
349
-            else if (count($args) == 3){
344
+            } else if (count($args) == 3){
350 345
                 if (is_array($args[2])){
351 346
                     $data = array_pop($args);
352 347
                 }
@@ -387,8 +382,7 @@  discard block
 block discarded – undo
387 382
             {
388 383
                 $this->getQueryBuilder()->from($this->_table);	
389 384
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
390
-            }
391
-            else
385
+            } else
392 386
             {
393 387
                 $this->getQueryBuilder()->from($this->_table); 
394 388
 				$result = $this->_database->delete();
@@ -411,8 +405,7 @@  discard block
 block discarded – undo
411 405
             {
412 406
                 $this->getQueryBuilder()->from($this->_table);	
413 407
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
414
-            }
415
-            else
408
+            } else
416 409
             {
417 410
                 $this->getQueryBuilder()->from($this->_table); 
418 411
 				$result = $this->_database->delete();
@@ -433,8 +426,7 @@  discard block
 block discarded – undo
433 426
             {
434 427
                 $this->getQueryBuilder()->from($this->_table);	
435 428
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
436
-            }
437
-            else
429
+            } else
438 430
             {
439 431
                 $this->getQueryBuilder()->from($this->_table); 
440 432
 				$result = $this->_database->delete();
@@ -496,8 +488,7 @@  discard block
 block discarded – undo
496 488
             if (count($args) == 2)
497 489
             {
498 490
                 list($key, $value) = $args;
499
-            }
500
-            else
491
+            } else
501 492
             {
502 493
                 $key = $this->primary_key;
503 494
                 $value = $args[0];
@@ -649,8 +640,7 @@  discard block
 block discarded – undo
649 640
             if (is_object($row))
650 641
             {
651 642
                 $row->created_at = date('Y-m-d H:i:s');
652
-            }
653
-            else
643
+            } else
654 644
             {
655 645
                 $row['created_at'] = date('Y-m-d H:i:s');
656 646
             }
@@ -662,8 +652,7 @@  discard block
 block discarded – undo
662 652
             if (is_object($row))
663 653
             {
664 654
                 $row->updated_at = date('Y-m-d H:i:s');
665
-            }
666
-            else
655
+            } else
667 656
             {
668 657
                 $row['updated_at'] = date('Y-m-d H:i:s');
669 658
             }
@@ -690,8 +679,7 @@  discard block
 block discarded – undo
690 679
                 if (is_array($row))
691 680
                 {
692 681
                     $row[$column] = unserialize($row[$column]);
693
-                }
694
-                else
682
+                } else
695 683
                 {
696 684
                     $row->$column = unserialize($row->$column);
697 685
                 }
@@ -711,8 +699,7 @@  discard block
 block discarded – undo
711 699
 					if (isset($row->$attr)){
712 700
 						unset($row->$attr);
713 701
 					}
714
-                }
715
-                else
702
+                } else
716 703
                 {
717 704
 					if (isset($row[$attr])){
718 705
 						unset($row[$attr]);
@@ -812,8 +799,7 @@  discard block
 block discarded – undo
812 799
                 {
813 800
                     $this->getQueryBuilder()->orderBy($key, $value);
814 801
                 }
815
-            }
816
-            else
802
+            } else
817 803
             {
818 804
                 $this->getQueryBuilder()->orderBy($criteria, $order);
819 805
             }
@@ -844,8 +830,7 @@  discard block
 block discarded – undo
844 830
                 {
845 831
                     $relationship = $value;
846 832
                     $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
847
-                }
848
-                else
833
+                } else
849 834
                 {
850 835
                     $relationship = $key;
851 836
                     $options = $value;
@@ -855,15 +840,13 @@  discard block
 block discarded – undo
855 840
                 {
856 841
                     if (is_object($this->loaderInstance)){
857 842
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
858
-                    }
859
-                    else{
843
+                    } else{
860 844
                         Loader::model($options['model'], $relationship . '_model');    
861 845
                     }
862 846
                     if (is_object($row))
863 847
                     {
864 848
                         $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
865
-                    }
866
-                    else
849
+                    } else
867 850
                     {
868 851
                         $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
869 852
                     }
@@ -883,8 +866,7 @@  discard block
 block discarded – undo
883 866
                 {
884 867
                     $relationship = $value;
885 868
                     $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
886
-                }
887
-                else
869
+                } else
888 870
                 {
889 871
                     $relationship = $key;
890 872
                     $options = $value;
@@ -894,15 +876,13 @@  discard block
 block discarded – undo
894 876
                 {
895 877
                     if (is_object($this->loaderInstance)){
896 878
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
897
-                    }
898
-                    else{
879
+                    } else{
899 880
                         Loader::model($options['model'], $relationship . '_model');    
900 881
                     }
901 882
                     if (is_object($row))
902 883
                     {
903 884
                         $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
904
-                    }
905
-                    else
885
+                    } else
906 886
                     {
907 887
                         $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
908 888
                     }
@@ -970,14 +950,12 @@  discard block
 block discarded – undo
970 950
 				if (is_array($filter))
971 951
 				{
972 952
 					$this->getQueryBuilder()->in($field, $filter);
973
-				}
974
-				else
953
+				} else
975 954
 				{
976 955
 					if (is_int($field))
977 956
 					{
978 957
 						$this->getQueryBuilder()->where($filter);
979
-					}
980
-					else
958
+					} else
981 959
 					{
982 960
 						$this->getQueryBuilder()->where($field, $filter);
983 961
 					}
@@ -994,33 +972,27 @@  discard block
 block discarded – undo
994 972
             if (count($params) == 1 && is_array($params[0]))
995 973
             {
996 974
                 $this->_set_where_array($params[0]);
997
-            }
998
-            else if (count($params) == 1)
975
+            } else if (count($params) == 1)
999 976
             {
1000 977
                 $this->getQueryBuilder()->where($params[0]);
1001
-            }
1002
-        	else if (count($params) == 2)
978
+            } else if (count($params) == 2)
1003 979
     		{
1004 980
                 if (is_array($params[1]))
1005 981
                 {
1006 982
                     $this->getQueryBuilder()->in($params[0], $params[1]);
1007
-                }
1008
-                else
983
+                } else
1009 984
                 {
1010 985
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1011 986
                 }
1012
-    		}
1013
-    		else if (count($params) == 3)
987
+    		} else if (count($params) == 3)
1014 988
     		{
1015 989
     			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1016
-    		}
1017
-            else
990
+    		} else
1018 991
             {
1019 992
                 if (is_array($params[1]))
1020 993
                 {
1021 994
                     $this->getQueryBuilder()->in($params[0], $params[1]);
1022
-                }
1023
-                else
995
+                } else
1024 996
                 {
1025 997
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1026 998
                 }
Please login to merge, or discard this patch.
core/common.php 3 patches
Indentation   +533 added lines, -533 removed lines patch added patch discarded remove patch
@@ -1,578 +1,578 @@
 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',
183
-								200 => 'OK',
184
-								201 => 'Created',
185
-								202 => 'Accepted',
186
-								203 => 'Non-Authoritative Information',
187
-								204 => 'No Content',
188
-								205 => 'Reset Content',
189
-								206 => 'Partial Content',
190
-								300 => 'Multiple Choices',
191
-								301 => 'Moved Permanently',
192
-								302 => 'Found',
193
-								303 => 'See Other',
194
-								304 => 'Not Modified',
195
-								305 => 'Use Proxy',
196
-								307 => 'Temporary Redirect',
197
-								400 => 'Bad Request',
198
-								401 => 'Unauthorized',
199
-								402 => 'Payment Required',
200
-								403 => 'Forbidden',
201
-								404 => 'Not Found',
202
-								405 => 'Method Not Allowed',
203
-								406 => 'Not Acceptable',
204
-								407 => 'Proxy Authentication Required',
205
-								408 => 'Request Timeout',
206
-								409 => 'Conflict',
207
-								410 => 'Gone',
208
-								411 => 'Length Required',
209
-								412 => 'Precondition Failed',
210
-								413 => 'Request Entity Too Large',
211
-								414 => 'Request-URI Too Long',
212
-								415 => 'Unsupported Media Type',
213
-								416 => 'Requested Range Not Satisfiable',
214
-								417 => 'Expectation Failed',
215
-								418 => 'I\'m a teapot',
216
-								500 => 'Internal Server Error',
217
-								501 => 'Not Implemented',
218
-								502 => 'Bad Gateway',
219
-								503 => 'Service Unavailable',
220
-								504 => 'Gateway Timeout',
221
-								505 => 'HTTP Version Not Supported',
222
-							);
223
-			if (isset($http_status[$code])){
224
-				$text = $http_status[$code];
225
-			}
226
-			else{
227
-				show_error('No HTTP status text found for your code please check it.');
228
-			}
229
-		}
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
+                                200 => 'OK',
184
+                                201 => 'Created',
185
+                                202 => 'Accepted',
186
+                                203 => 'Non-Authoritative Information',
187
+                                204 => 'No Content',
188
+                                205 => 'Reset Content',
189
+                                206 => 'Partial Content',
190
+                                300 => 'Multiple Choices',
191
+                                301 => 'Moved Permanently',
192
+                                302 => 'Found',
193
+                                303 => 'See Other',
194
+                                304 => 'Not Modified',
195
+                                305 => 'Use Proxy',
196
+                                307 => 'Temporary Redirect',
197
+                                400 => 'Bad Request',
198
+                                401 => 'Unauthorized',
199
+                                402 => 'Payment Required',
200
+                                403 => 'Forbidden',
201
+                                404 => 'Not Found',
202
+                                405 => 'Method Not Allowed',
203
+                                406 => 'Not Acceptable',
204
+                                407 => 'Proxy Authentication Required',
205
+                                408 => 'Request Timeout',
206
+                                409 => 'Conflict',
207
+                                410 => 'Gone',
208
+                                411 => 'Length Required',
209
+                                412 => 'Precondition Failed',
210
+                                413 => 'Request Entity Too Large',
211
+                                414 => 'Request-URI Too Long',
212
+                                415 => 'Unsupported Media Type',
213
+                                416 => 'Requested Range Not Satisfiable',
214
+                                417 => 'Expectation Failed',
215
+                                418 => 'I\'m a teapot',
216
+                                500 => 'Internal Server Error',
217
+                                501 => 'Not Implemented',
218
+                                502 => 'Bad Gateway',
219
+                                503 => 'Service Unavailable',
220
+                                504 => 'Gateway Timeout',
221
+                                505 => 'HTTP Version Not Supported',
222
+                            );
223
+            if (isset($http_status[$code])){
224
+                $text = $http_status[$code];
225
+            }
226
+            else{
227
+                show_error('No HTTP status text found for your code please check it.');
228
+            }
229
+        }
230 230
 		
231
-		if (strpos(php_sapi_name(), 'cgi') === 0){
232
-			header('Status: ' . $code . ' ' . $text, TRUE);
233
-		}
234
-		else{
235
-			$proto = 'HTTP/1.1';
236
-			if(isset($_SERVER['SERVER_PROTOCOL'])){
237
-				$proto = $_SERVER['SERVER_PROTOCOL'];
238
-			}
239
-			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
240
-		}
241
-	}
231
+        if (strpos(php_sapi_name(), 'cgi') === 0){
232
+            header('Status: ' . $code . ' ' . $text, TRUE);
233
+        }
234
+        else{
235
+            $proto = 'HTTP/1.1';
236
+            if(isset($_SERVER['SERVER_PROTOCOL'])){
237
+                $proto = $_SERVER['SERVER_PROTOCOL'];
238
+            }
239
+            header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
240
+        }
241
+    }
242 242
 
243
-	/**
244
-	 *  This function displays an error message to the user and ends the execution of the script.
245
-	 *  
246
-	 *  @param string $msg the message to display
247
-	 *  @param string $title the message title: "error", "info", "warning", etc.
248
-	 *  @param boolean $logging either to save error in log
249
-	 *  
250
-	 *  @codeCoverageIgnore
251
-	 */
252
-	function show_error($msg, $title = 'error', $logging = true){
253
-		$title = strtoupper($title);
254
-		$data = array();
255
-		$data['error'] = $msg;
256
-		$data['title'] = $title;
257
-		if ($logging){
258
-			save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
259
-		}
260
-		$response = & class_loader('Response', 'classes');
261
-		$response->sendError($data);
262
-		die();
263
-	}
243
+    /**
244
+     *  This function displays an error message to the user and ends the execution of the script.
245
+     *  
246
+     *  @param string $msg the message to display
247
+     *  @param string $title the message title: "error", "info", "warning", etc.
248
+     *  @param boolean $logging either to save error in log
249
+     *  
250
+     *  @codeCoverageIgnore
251
+     */
252
+    function show_error($msg, $title = 'error', $logging = true){
253
+        $title = strtoupper($title);
254
+        $data = array();
255
+        $data['error'] = $msg;
256
+        $data['title'] = $title;
257
+        if ($logging){
258
+            save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
259
+        }
260
+        $response = & class_loader('Response', 'classes');
261
+        $response->sendError($data);
262
+        die();
263
+    }
264 264
 
265
-	/**
266
-	 *  Check whether the protocol used is "https" or not
267
-	 *  That is, the web server is configured to use a secure connection.
268
-	 *  @codeCoverageIgnore
269
-	 *  
270
-	 *  @return boolean true if the web server uses the https protocol, false if not.
271
-	 */
272
-	function is_https(){
273
-		/*
265
+    /**
266
+     *  Check whether the protocol used is "https" or not
267
+     *  That is, the web server is configured to use a secure connection.
268
+     *  @codeCoverageIgnore
269
+     *  
270
+     *  @return boolean true if the web server uses the https protocol, false if not.
271
+     */
272
+    function is_https(){
273
+        /*
274 274
 		* some servers pass the "HTTPS" parameter in the server variable,
275 275
 		* if is the case, check if the value is "on", "true", "1".
276 276
 		*/
277
-		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
278
-			return true;
279
-		}
280
-		if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
281
-			return true;
282
-		}
283
-		if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
284
-			return true;
285
-		}
286
-		return false;
287
-	}
277
+        if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
278
+            return true;
279
+        }
280
+        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
281
+            return true;
282
+        }
283
+        if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
284
+            return true;
285
+        }
286
+        return false;
287
+    }
288 288
 	
289
-	/**
290
-	 *  This function is used to check the URL format of the given string argument. 
291
-	 *  The address is valid if the protocol is http, https, ftp, etc.
292
-	 *
293
-	 *  @param string $url the URL address to check
294
-	 *  @test
295
-	 *  
296
-	 *  @return boolean true if is a valid URL address or false.
297
-	 */
298
-	function is_url($url){
299
-		return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
300
-	}
289
+    /**
290
+     *  This function is used to check the URL format of the given string argument. 
291
+     *  The address is valid if the protocol is http, https, ftp, etc.
292
+     *
293
+     *  @param string $url the URL address to check
294
+     *  @test
295
+     *  
296
+     *  @return boolean true if is a valid URL address or false.
297
+     */
298
+    function is_url($url){
299
+        return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
300
+    }
301 301
 	
302
-	/**
303
-	 *  Function defined to load controller
304
-	 *  
305
-	 *  @param string $controllerClass the controller class name to be loaded
306
-	 *  @codeCoverageIgnore
307
-	 */
308
-	function autoload_controller($controllerClass){
309
-		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
310
-			require_once $path;
311
-		}
312
-	}
302
+    /**
303
+     *  Function defined to load controller
304
+     *  
305
+     *  @param string $controllerClass the controller class name to be loaded
306
+     *  @codeCoverageIgnore
307
+     */
308
+    function autoload_controller($controllerClass){
309
+        if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
310
+            require_once $path;
311
+        }
312
+    }
313 313
 	
314
-	/**
315
-	 *  Function defined for handling PHP exception error message, 
316
-	 *  it displays an error message using the function "show_error"
317
-	 *  
318
-	 *  @param object $ex instance of the "Exception" class or a derived class
319
-	 *  @codeCoverageIgnore
320
-	 *  
321
-	 *  @return boolean
322
-	 */
323
-	function php_exception_handler($ex){
324
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
325
-			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
326
-		}
327
-		else{
328
-			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
329
-		}
330
-		return true;
331
-	}
314
+    /**
315
+     *  Function defined for handling PHP exception error message, 
316
+     *  it displays an error message using the function "show_error"
317
+     *  
318
+     *  @param object $ex instance of the "Exception" class or a derived class
319
+     *  @codeCoverageIgnore
320
+     *  
321
+     *  @return boolean
322
+     */
323
+    function php_exception_handler($ex){
324
+        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
325
+            show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
326
+        }
327
+        else{
328
+            save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
329
+        }
330
+        return true;
331
+    }
332 332
 	
333
-	/**
334
-	 *  Function defined for PHP error message handling
335
-	 *  			
336
-	 *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
337
-	 *  @param string $errstr the error message
338
-	 *  @param string $errfile the file where the error occurred
339
-	 *  @param int $errline the line number where the error occurred
340
-	 *  @codeCoverageIgnore
341
-	 *  
342
-	 *  @return boolean	
343
-	 */
344
-	function php_error_handler($errno , $errstr, $errfile , $errline){
345
-		$isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
346
-		if ($isError){
347
-			set_http_status_header(500);
348
-		}
349
-		if (! (error_reporting() & $errno)) {
350
-			save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
351
-			return;
352
-		}
353
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
354
-			$errorType = 'error';
355
-			switch ($errno) {
356
-				case E_USER_WARNING:
357
-					$errorType = 'warning';
358
-					break;
359
-				case E_USER_NOTICE:
360
-					$errorType = 'notice';
361
-					break;
362
-			}
363
-			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
364
-		}
365
-		if ($isError){
366
-			die();
367
-		}
368
-		return true;
369
-	}
333
+    /**
334
+     *  Function defined for PHP error message handling
335
+     *  			
336
+     *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
337
+     *  @param string $errstr the error message
338
+     *  @param string $errfile the file where the error occurred
339
+     *  @param int $errline the line number where the error occurred
340
+     *  @codeCoverageIgnore
341
+     *  
342
+     *  @return boolean	
343
+     */
344
+    function php_error_handler($errno , $errstr, $errfile , $errline){
345
+        $isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
346
+        if ($isError){
347
+            set_http_status_header(500);
348
+        }
349
+        if (! (error_reporting() & $errno)) {
350
+            save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
351
+            return;
352
+        }
353
+        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
354
+            $errorType = 'error';
355
+            switch ($errno) {
356
+                case E_USER_WARNING:
357
+                    $errorType = 'warning';
358
+                    break;
359
+                case E_USER_NOTICE:
360
+                    $errorType = 'notice';
361
+                    break;
362
+            }
363
+            show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
364
+        }
365
+        if ($isError){
366
+            die();
367
+        }
368
+        return true;
369
+    }
370 370
 
371
-	/**
372
-	 * This function is used to run in shutdown situation of the script
373
-	 * @codeCoverageIgnore
374
-	 */
375
-	function php_shudown_handler(){
376
-		$lastError = error_get_last();
377
-		if (isset($lastError) &&
378
-			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
379
-			php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
380
-		}
381
-	}
371
+    /**
372
+     * This function is used to run in shutdown situation of the script
373
+     * @codeCoverageIgnore
374
+     */
375
+    function php_shudown_handler(){
376
+        $lastError = error_get_last();
377
+        if (isset($lastError) &&
378
+            ($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
379
+            php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
380
+        }
381
+    }
382 382
 
383 383
 
384
-	/**
385
-	 *  Convert array attributes to string
386
-	 *
387
-	 *  This function converts an associative array into HTML attributes.
388
-	 *  For example :
389
-	 *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
390
-	 *  name = "Foo" type = "text"
391
-	 *
392
-	 *  @param array $attributes associative array to convert to a string attribute.
393
-	 *   
394
-	 *  @return string string of the HTML attribute.
395
-	 */
396
-	function attributes_to_string(array $attributes){
397
-		$str = ' ';
398
-		//we check that the array passed as an argument is not empty.
399
-		if (! empty($attributes)){
400
-			foreach($attributes as $key => $value){
401
-				$key = trim(htmlspecialchars($key));
402
-				$value = trim(htmlspecialchars($value));
403
-				/*
384
+    /**
385
+     *  Convert array attributes to string
386
+     *
387
+     *  This function converts an associative array into HTML attributes.
388
+     *  For example :
389
+     *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
390
+     *  name = "Foo" type = "text"
391
+     *
392
+     *  @param array $attributes associative array to convert to a string attribute.
393
+     *   
394
+     *  @return string string of the HTML attribute.
395
+     */
396
+    function attributes_to_string(array $attributes){
397
+        $str = ' ';
398
+        //we check that the array passed as an argument is not empty.
399
+        if (! empty($attributes)){
400
+            foreach($attributes as $key => $value){
401
+                $key = trim(htmlspecialchars($key));
402
+                $value = trim(htmlspecialchars($value));
403
+                /*
404 404
 				* To predict the case where the string to convert contains the character "
405 405
 				* we check if this is the case we add a slash to solve this problem.
406 406
 				* For example:
407 407
 				* 	$attr = array('placeholder' => 'I am a "puple"')
408 408
 				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
409 409
 				 */
410
-				if ($value && strpos('"', $value) !== false){
411
-					$value = addslashes($value);
412
-				}
413
-				$str .= $key.' = "'.$value.'" ';
414
-			}
415
-		}
416
-		//remove the space after using rtrim()
417
-		return rtrim($str);
418
-	}
410
+                if ($value && strpos('"', $value) !== false){
411
+                    $value = addslashes($value);
412
+                }
413
+                $str .= $key.' = "'.$value.'" ';
414
+            }
415
+        }
416
+        //remove the space after using rtrim()
417
+        return rtrim($str);
418
+    }
419 419
 
420 420
 
421
-	/**
422
-	* Function to stringfy PHP variable, useful in debug situation
423
-	*
424
-	* @param mixed $var the variable to stringfy
425
-	* @codeCoverageIgnore
426
-	*
427
-	* @return string the stringfy value
428
-	*/
429
-	function stringfy_vars($var){
430
-		return print_r($var, true);
431
-	}
421
+    /**
422
+     * Function to stringfy PHP variable, useful in debug situation
423
+     *
424
+     * @param mixed $var the variable to stringfy
425
+     * @codeCoverageIgnore
426
+     *
427
+     * @return string the stringfy value
428
+     */
429
+    function stringfy_vars($var){
430
+        return print_r($var, true);
431
+    }
432 432
 
433
-	/**
434
-	 * Clean the user input
435
-	 * @param  mixed $str the value to clean
436
-	 * @test
437
-	 * 
438
-	 * @return mixed   the sanitize value
439
-	 */
440
-	function clean_input($str){
441
-		if (is_array($str)){
442
-			$str = array_map('clean_input', $str);
443
-		}
444
-		else if (is_object($str)){
445
-			$obj = $str;
446
-			foreach ($str as $var => $value) {
447
-				$obj->$var = clean_input($value);
448
-			}
449
-			$str = $obj;
450
-		}
451
-		else{
452
-			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
453
-		}
454
-		return $str;
455
-	}
433
+    /**
434
+     * Clean the user input
435
+     * @param  mixed $str the value to clean
436
+     * @test
437
+     * 
438
+     * @return mixed   the sanitize value
439
+     */
440
+    function clean_input($str){
441
+        if (is_array($str)){
442
+            $str = array_map('clean_input', $str);
443
+        }
444
+        else if (is_object($str)){
445
+            $obj = $str;
446
+            foreach ($str as $var => $value) {
447
+                $obj->$var = clean_input($value);
448
+            }
449
+            $str = $obj;
450
+        }
451
+        else{
452
+            $str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
453
+        }
454
+        return $str;
455
+    }
456 456
 	
457
-	/**
458
-	 * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
459
-	 * Information like credit card number, password, etc.
460
-	 *
461
-	 * @param  string $str the string you want to hide some part
462
-	 * @param  int $startCount the length of non hidden for the beginning char
463
-	 * @param  int $endCount the length of non hidden for the ending char
464
-	 * @param  string $hiddenChar the char used to hide the given string
465
-	 * @test
466
-	 * 
467
-	 * @return string the string with the hidden part.
468
-	 */
469
-	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
470
-		//get the string length
471
-		$len = strlen($str);
472
-		//if str is empty
473
-		if ($len <= 0){
474
-			return str_repeat($hiddenChar, 6);
475
-		}
476
-		//if the length is less than startCount and endCount
477
-		//or the startCount and endCount length is 0
478
-		//or startCount is negative or endCount is negative
479
-		//return the full string hidden
457
+    /**
458
+     * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
459
+     * Information like credit card number, password, etc.
460
+     *
461
+     * @param  string $str the string you want to hide some part
462
+     * @param  int $startCount the length of non hidden for the beginning char
463
+     * @param  int $endCount the length of non hidden for the ending char
464
+     * @param  string $hiddenChar the char used to hide the given string
465
+     * @test
466
+     * 
467
+     * @return string the string with the hidden part.
468
+     */
469
+    function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
470
+        //get the string length
471
+        $len = strlen($str);
472
+        //if str is empty
473
+        if ($len <= 0){
474
+            return str_repeat($hiddenChar, 6);
475
+        }
476
+        //if the length is less than startCount and endCount
477
+        //or the startCount and endCount length is 0
478
+        //or startCount is negative or endCount is negative
479
+        //return the full string hidden
480 480
 		
481
-		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
482
-			return str_repeat($hiddenChar, $len);
483
-		}
484
-		//the start non hidden string
485
-		$startNonHiddenStr = substr($str, 0, $startCount);
486
-		//the end non hidden string
487
-		$endNonHiddenStr = null;
488
-		if ($endCount > 0){
489
-			$endNonHiddenStr = substr($str, - $endCount);
490
-		}
491
-		//the hidden string
492
-		$hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
481
+        if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
482
+            return str_repeat($hiddenChar, $len);
483
+        }
484
+        //the start non hidden string
485
+        $startNonHiddenStr = substr($str, 0, $startCount);
486
+        //the end non hidden string
487
+        $endNonHiddenStr = null;
488
+        if ($endCount > 0){
489
+            $endNonHiddenStr = substr($str, - $endCount);
490
+        }
491
+        //the hidden string
492
+        $hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
493 493
 		
494
-		return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
495
-	}
494
+        return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
495
+    }
496 496
 	
497
-	/**
498
-	 * This function is used to set the initial session config regarding the configuration
499
-	 * @codeCoverageIgnore
500
-	 */
501
-	function set_session_config(){
502
-		//$_SESSION is not available on cli mode 
503
-		if (! IS_CLI){
504
-			$logger =& class_loader('Log', 'classes');
505
-			$logger->setLogger('PHPSession');
506
-			//set session params
507
-			$sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
508
-			$sessionName = get_config('session_name');
509
-			if ($sessionName){
510
-				session_name($sessionName);
511
-			}
512
-			$logger->info('Session handler: ' . $sessionHandler);
513
-			$logger->info('Session name: ' . $sessionName);
497
+    /**
498
+     * This function is used to set the initial session config regarding the configuration
499
+     * @codeCoverageIgnore
500
+     */
501
+    function set_session_config(){
502
+        //$_SESSION is not available on cli mode 
503
+        if (! IS_CLI){
504
+            $logger =& class_loader('Log', 'classes');
505
+            $logger->setLogger('PHPSession');
506
+            //set session params
507
+            $sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
508
+            $sessionName = get_config('session_name');
509
+            if ($sessionName){
510
+                session_name($sessionName);
511
+            }
512
+            $logger->info('Session handler: ' . $sessionHandler);
513
+            $logger->info('Session name: ' . $sessionName);
514 514
 
515
-			if ($sessionHandler == 'files'){
516
-				$sessionSavePath = get_config('session_save_path');
517
-				if ($sessionSavePath){
518
-					if (! is_dir($sessionSavePath)){
519
-						mkdir($sessionSavePath, 1773);
520
-					}
521
-					session_save_path($sessionSavePath);
522
-					$logger->info('Session save path: ' . $sessionSavePath);
523
-				}
524
-			}
525
-			else if ($sessionHandler == 'database'){
526
-				//load database session handle library
527
-				//Database Session handler Model
528
-				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
515
+            if ($sessionHandler == 'files'){
516
+                $sessionSavePath = get_config('session_save_path');
517
+                if ($sessionSavePath){
518
+                    if (! is_dir($sessionSavePath)){
519
+                        mkdir($sessionSavePath, 1773);
520
+                    }
521
+                    session_save_path($sessionSavePath);
522
+                    $logger->info('Session save path: ' . $sessionSavePath);
523
+                }
524
+            }
525
+            else if ($sessionHandler == 'database'){
526
+                //load database session handle library
527
+                //Database Session handler Model
528
+                require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
529 529
 
530
-				$DBS =& class_loader('DBSessionHandler', 'classes');
531
-				session_set_save_handler($DBS, true);
532
-				$logger->info('session save path: ' . get_config('session_save_path'));
533
-			}
534
-			else{
535
-				show_error('Invalid session handler configuration');
536
-			}
537
-			$lifetime = get_config('session_cookie_lifetime', 0);
538
-			$path = get_config('session_cookie_path', '/');
539
-			$domain = get_config('session_cookie_domain', '');
540
-			$secure = get_config('session_cookie_secure', false);
541
-			session_set_cookie_params(
542
-				$lifetime,
543
-				$path,
544
-				$domain,
545
-				$secure,
546
-				$httponly = true /*for security for access to cookie via javascript or XSS attack*/
547
-			);
548
-			//to prevent attack of Session Fixation 
549
-			//thank to https://www.phparch.com/2018/01/php-sessions-in-depth/
550
-			ini_set('session.use_strict_mode ', 1);
551
-			ini_set('session.use_only_cookies', 1);
552
-			ini_set('session.use_trans_sid ', 0);
530
+                $DBS =& class_loader('DBSessionHandler', 'classes');
531
+                session_set_save_handler($DBS, true);
532
+                $logger->info('session save path: ' . get_config('session_save_path'));
533
+            }
534
+            else{
535
+                show_error('Invalid session handler configuration');
536
+            }
537
+            $lifetime = get_config('session_cookie_lifetime', 0);
538
+            $path = get_config('session_cookie_path', '/');
539
+            $domain = get_config('session_cookie_domain', '');
540
+            $secure = get_config('session_cookie_secure', false);
541
+            session_set_cookie_params(
542
+                $lifetime,
543
+                $path,
544
+                $domain,
545
+                $secure,
546
+                $httponly = true /*for security for access to cookie via javascript or XSS attack*/
547
+            );
548
+            //to prevent attack of Session Fixation 
549
+            //thank to https://www.phparch.com/2018/01/php-sessions-in-depth/
550
+            ini_set('session.use_strict_mode ', 1);
551
+            ini_set('session.use_only_cookies', 1);
552
+            ini_set('session.use_trans_sid ', 0);
553 553
 			
554
-			$logger->info('Session lifetime: ' . $lifetime);
555
-			$logger->info('Session cookie path: ' . $path);
556
-			$logger->info('Session domain: ' . $domain);
557
-			$logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
554
+            $logger->info('Session lifetime: ' . $lifetime);
555
+            $logger->info('Session cookie path: ' . $path);
556
+            $logger->info('Session domain: ' . $domain);
557
+            $logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
558 558
 			
559
-			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
560
-				$logger->info('Session not yet start, start it now');
561
-				session_start();
562
-			}
563
-		}
564
-	}
559
+            if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
560
+                $logger->info('Session not yet start, start it now');
561
+                session_start();
562
+            }
563
+        }
564
+    }
565 565
 	
566
-	/**
567
-	* This function is very useful, it allows to recover the instance of the global controller.
568
-	* Note this function always returns the address of the super instance.
569
-	* For example :
570
-	* $obj = & get_instance();
571
-	* 
572
-	* @codeCoverageIgnore
573
-	*  
574
-	* @return object the instance of the "Controller" class
575
-	*/
576
-	function & get_instance(){
577
-		return Controller::get_instance();
578
-	}
566
+    /**
567
+     * This function is very useful, it allows to recover the instance of the global controller.
568
+     * Note this function always returns the address of the super instance.
569
+     * For example :
570
+     * $obj = & get_instance();
571
+     * 
572
+     * @codeCoverageIgnore
573
+     *  
574
+     * @return object the instance of the "Controller" class
575
+     */
576
+    function & get_instance(){
577
+        return Controller::get_instance();
578
+    }
Please login to merge, or discard this patch.
Spacing   +69 added lines, -69 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',
@@ -220,20 +220,20 @@  discard block
 block discarded – undo
220 220
 								504 => 'Gateway Timeout',
221 221
 								505 => 'HTTP Version Not Supported',
222 222
 							);
223
-			if (isset($http_status[$code])){
223
+			if (isset($http_status[$code])) {
224 224
 				$text = $http_status[$code];
225 225
 			}
226
-			else{
226
+			else {
227 227
 				show_error('No HTTP status text found for your code please check it.');
228 228
 			}
229 229
 		}
230 230
 		
231
-		if (strpos(php_sapi_name(), 'cgi') === 0){
231
+		if (strpos(php_sapi_name(), 'cgi') === 0) {
232 232
 			header('Status: ' . $code . ' ' . $text, TRUE);
233 233
 		}
234
-		else{
234
+		else {
235 235
 			$proto = 'HTTP/1.1';
236
-			if(isset($_SERVER['SERVER_PROTOCOL'])){
236
+			if (isset($_SERVER['SERVER_PROTOCOL'])) {
237 237
 				$proto = $_SERVER['SERVER_PROTOCOL'];
238 238
 			}
239 239
 			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
@@ -249,13 +249,13 @@  discard block
 block discarded – undo
249 249
 	 *  
250 250
 	 *  @codeCoverageIgnore
251 251
 	 */
252
-	function show_error($msg, $title = 'error', $logging = true){
252
+	function show_error($msg, $title = 'error', $logging = true) {
253 253
 		$title = strtoupper($title);
254 254
 		$data = array();
255 255
 		$data['error'] = $msg;
256 256
 		$data['title'] = $title;
257
-		if ($logging){
258
-			save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
257
+		if ($logging) {
258
+			save_to_log('error', '[' . $title . '] ' . strip_tags($msg), 'GLOBAL::ERROR');
259 259
 		}
260 260
 		$response = & class_loader('Response', 'classes');
261 261
 		$response->sendError($data);
@@ -269,18 +269,18 @@  discard block
 block discarded – undo
269 269
 	 *  
270 270
 	 *  @return boolean true if the web server uses the https protocol, false if not.
271 271
 	 */
272
-	function is_https(){
272
+	function is_https() {
273 273
 		/*
274 274
 		* some servers pass the "HTTPS" parameter in the server variable,
275 275
 		* if is the case, check if the value is "on", "true", "1".
276 276
 		*/
277
-		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
277
+		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
278 278
 			return true;
279 279
 		}
280
-		if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
280
+		if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
281 281
 			return true;
282 282
 		}
283
-		if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
283
+		if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
284 284
 			return true;
285 285
 		}
286 286
 		return false;
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
 	 *  
296 296
 	 *  @return boolean true if is a valid URL address or false.
297 297
 	 */
298
-	function is_url($url){
298
+	function is_url($url) {
299 299
 		return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
300 300
 	}
301 301
 	
@@ -305,8 +305,8 @@  discard block
 block discarded – undo
305 305
 	 *  @param string $controllerClass the controller class name to be loaded
306 306
 	 *  @codeCoverageIgnore
307 307
 	 */
308
-	function autoload_controller($controllerClass){
309
-		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
308
+	function autoload_controller($controllerClass) {
309
+		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')) {
310 310
 			require_once $path;
311 311
 		}
312 312
 	}
@@ -320,11 +320,11 @@  discard block
 block discarded – undo
320 320
 	 *  
321 321
 	 *  @return boolean
322 322
 	 */
323
-	function php_exception_handler($ex){
324
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
325
-			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
323
+	function php_exception_handler($ex) {
324
+		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
325
+			show_error('An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
326 326
 		}
327
-		else{
327
+		else {
328 328
 			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
329 329
 		}
330 330
 		return true;
@@ -341,16 +341,16 @@  discard block
 block discarded – undo
341 341
 	 *  
342 342
 	 *  @return boolean	
343 343
 	 */
344
-	function php_error_handler($errno , $errstr, $errfile , $errline){
344
+	function php_error_handler($errno, $errstr, $errfile, $errline) {
345 345
 		$isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
346
-		if ($isError){
346
+		if ($isError) {
347 347
 			set_http_status_header(500);
348 348
 		}
349
-		if (! (error_reporting() & $errno)) {
349
+		if (!(error_reporting() & $errno)) {
350 350
 			save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
351 351
 			return;
352 352
 		}
353
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
353
+		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
354 354
 			$errorType = 'error';
355 355
 			switch ($errno) {
356 356
 				case E_USER_WARNING:
@@ -360,9 +360,9 @@  discard block
 block discarded – undo
360 360
 					$errorType = 'notice';
361 361
 					break;
362 362
 			}
363
-			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
363
+			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline . '</b> raison : ' . $errstr, 'PHP ' . $errorType);
364 364
 		}
365
-		if ($isError){
365
+		if ($isError) {
366 366
 			die();
367 367
 		}
368 368
 		return true;
@@ -372,10 +372,10 @@  discard block
 block discarded – undo
372 372
 	 * This function is used to run in shutdown situation of the script
373 373
 	 * @codeCoverageIgnore
374 374
 	 */
375
-	function php_shudown_handler(){
375
+	function php_shudown_handler() {
376 376
 		$lastError = error_get_last();
377 377
 		if (isset($lastError) &&
378
-			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
378
+			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))) {
379 379
 			php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
380 380
 		}
381 381
 	}
@@ -393,11 +393,11 @@  discard block
 block discarded – undo
393 393
 	 *   
394 394
 	 *  @return string string of the HTML attribute.
395 395
 	 */
396
-	function attributes_to_string(array $attributes){
396
+	function attributes_to_string(array $attributes) {
397 397
 		$str = ' ';
398 398
 		//we check that the array passed as an argument is not empty.
399
-		if (! empty($attributes)){
400
-			foreach($attributes as $key => $value){
399
+		if (!empty($attributes)) {
400
+			foreach ($attributes as $key => $value) {
401 401
 				$key = trim(htmlspecialchars($key));
402 402
 				$value = trim(htmlspecialchars($value));
403 403
 				/*
@@ -407,10 +407,10 @@  discard block
 block discarded – undo
407 407
 				* 	$attr = array('placeholder' => 'I am a "puple"')
408 408
 				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
409 409
 				 */
410
-				if ($value && strpos('"', $value) !== false){
410
+				if ($value && strpos('"', $value) !== false) {
411 411
 					$value = addslashes($value);
412 412
 				}
413
-				$str .= $key.' = "'.$value.'" ';
413
+				$str .= $key . ' = "' . $value . '" ';
414 414
 			}
415 415
 		}
416 416
 		//remove the space after using rtrim()
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
 	*
427 427
 	* @return string the stringfy value
428 428
 	*/
429
-	function stringfy_vars($var){
429
+	function stringfy_vars($var) {
430 430
 		return print_r($var, true);
431 431
 	}
432 432
 
@@ -437,18 +437,18 @@  discard block
 block discarded – undo
437 437
 	 * 
438 438
 	 * @return mixed   the sanitize value
439 439
 	 */
440
-	function clean_input($str){
441
-		if (is_array($str)){
440
+	function clean_input($str) {
441
+		if (is_array($str)) {
442 442
 			$str = array_map('clean_input', $str);
443 443
 		}
444
-		else if (is_object($str)){
444
+		else if (is_object($str)) {
445 445
 			$obj = $str;
446 446
 			foreach ($str as $var => $value) {
447 447
 				$obj->$var = clean_input($value);
448 448
 			}
449 449
 			$str = $obj;
450 450
 		}
451
-		else{
451
+		else {
452 452
 			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
453 453
 		}
454 454
 		return $str;
@@ -466,11 +466,11 @@  discard block
 block discarded – undo
466 466
 	 * 
467 467
 	 * @return string the string with the hidden part.
468 468
 	 */
469
-	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
469
+	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*') {
470 470
 		//get the string length
471 471
 		$len = strlen($str);
472 472
 		//if str is empty
473
-		if ($len <= 0){
473
+		if ($len <= 0) {
474 474
 			return str_repeat($hiddenChar, 6);
475 475
 		}
476 476
 		//if the length is less than startCount and endCount
@@ -478,14 +478,14 @@  discard block
 block discarded – undo
478 478
 		//or startCount is negative or endCount is negative
479 479
 		//return the full string hidden
480 480
 		
481
-		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
481
+		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)) {
482 482
 			return str_repeat($hiddenChar, $len);
483 483
 		}
484 484
 		//the start non hidden string
485 485
 		$startNonHiddenStr = substr($str, 0, $startCount);
486 486
 		//the end non hidden string
487 487
 		$endNonHiddenStr = null;
488
-		if ($endCount > 0){
488
+		if ($endCount > 0) {
489 489
 			$endNonHiddenStr = substr($str, - $endCount);
490 490
 		}
491 491
 		//the hidden string
@@ -498,40 +498,40 @@  discard block
 block discarded – undo
498 498
 	 * This function is used to set the initial session config regarding the configuration
499 499
 	 * @codeCoverageIgnore
500 500
 	 */
501
-	function set_session_config(){
501
+	function set_session_config() {
502 502
 		//$_SESSION is not available on cli mode 
503
-		if (! IS_CLI){
504
-			$logger =& class_loader('Log', 'classes');
503
+		if (!IS_CLI) {
504
+			$logger = & class_loader('Log', 'classes');
505 505
 			$logger->setLogger('PHPSession');
506 506
 			//set session params
507 507
 			$sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
508 508
 			$sessionName = get_config('session_name');
509
-			if ($sessionName){
509
+			if ($sessionName) {
510 510
 				session_name($sessionName);
511 511
 			}
512 512
 			$logger->info('Session handler: ' . $sessionHandler);
513 513
 			$logger->info('Session name: ' . $sessionName);
514 514
 
515
-			if ($sessionHandler == 'files'){
515
+			if ($sessionHandler == 'files') {
516 516
 				$sessionSavePath = get_config('session_save_path');
517
-				if ($sessionSavePath){
518
-					if (! is_dir($sessionSavePath)){
517
+				if ($sessionSavePath) {
518
+					if (!is_dir($sessionSavePath)) {
519 519
 						mkdir($sessionSavePath, 1773);
520 520
 					}
521 521
 					session_save_path($sessionSavePath);
522 522
 					$logger->info('Session save path: ' . $sessionSavePath);
523 523
 				}
524 524
 			}
525
-			else if ($sessionHandler == 'database'){
525
+			else if ($sessionHandler == 'database') {
526 526
 				//load database session handle library
527 527
 				//Database Session handler Model
528 528
 				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
529 529
 
530
-				$DBS =& class_loader('DBSessionHandler', 'classes');
530
+				$DBS = & class_loader('DBSessionHandler', 'classes');
531 531
 				session_set_save_handler($DBS, true);
532 532
 				$logger->info('session save path: ' . get_config('session_save_path'));
533 533
 			}
534
-			else{
534
+			else {
535 535
 				show_error('Invalid session handler configuration');
536 536
 			}
537 537
 			$lifetime = get_config('session_cookie_lifetime', 0);
@@ -554,9 +554,9 @@  discard block
 block discarded – undo
554 554
 			$logger->info('Session lifetime: ' . $lifetime);
555 555
 			$logger->info('Session cookie path: ' . $path);
556 556
 			$logger->info('Session domain: ' . $domain);
557
-			$logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
557
+			$logger->info('Session is secure: ' . ($secure ? 'TRUE' : 'FALSE'));
558 558
 			
559
-			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
559
+			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
560 560
 				$logger->info('Session not yet start, start it now');
561 561
 				session_start();
562 562
 			}
Please login to merge, or discard this patch.
Braces   +7 added lines, -14 removed lines patch added patch discarded remove patch
@@ -222,16 +222,14 @@  discard block
 block discarded – undo
222 222
 							);
223 223
 			if (isset($http_status[$code])){
224 224
 				$text = $http_status[$code];
225
-			}
226
-			else{
225
+			} else{
227 226
 				show_error('No HTTP status text found for your code please check it.');
228 227
 			}
229 228
 		}
230 229
 		
231 230
 		if (strpos(php_sapi_name(), 'cgi') === 0){
232 231
 			header('Status: ' . $code . ' ' . $text, TRUE);
233
-		}
234
-		else{
232
+		} else{
235 233
 			$proto = 'HTTP/1.1';
236 234
 			if(isset($_SERVER['SERVER_PROTOCOL'])){
237 235
 				$proto = $_SERVER['SERVER_PROTOCOL'];
@@ -323,8 +321,7 @@  discard block
 block discarded – undo
323 321
 	function php_exception_handler($ex){
324 322
 		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
325 323
 			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
326
-		}
327
-		else{
324
+		} else{
328 325
 			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
329 326
 		}
330 327
 		return true;
@@ -440,15 +437,13 @@  discard block
 block discarded – undo
440 437
 	function clean_input($str){
441 438
 		if (is_array($str)){
442 439
 			$str = array_map('clean_input', $str);
443
-		}
444
-		else if (is_object($str)){
440
+		} else if (is_object($str)){
445 441
 			$obj = $str;
446 442
 			foreach ($str as $var => $value) {
447 443
 				$obj->$var = clean_input($value);
448 444
 			}
449 445
 			$str = $obj;
450
-		}
451
-		else{
446
+		} else{
452 447
 			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
453 448
 		}
454 449
 		return $str;
@@ -521,8 +516,7 @@  discard block
 block discarded – undo
521 516
 					session_save_path($sessionSavePath);
522 517
 					$logger->info('Session save path: ' . $sessionSavePath);
523 518
 				}
524
-			}
525
-			else if ($sessionHandler == 'database'){
519
+			} else if ($sessionHandler == 'database'){
526 520
 				//load database session handle library
527 521
 				//Database Session handler Model
528 522
 				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
@@ -530,8 +524,7 @@  discard block
 block discarded – undo
530 524
 				$DBS =& class_loader('DBSessionHandler', 'classes');
531 525
 				session_set_save_handler($DBS, true);
532 526
 				$logger->info('session save path: ' . get_config('session_save_path'));
533
-			}
534
-			else{
527
+			} else{
535 528
 				show_error('Invalid session handler configuration');
536 529
 			}
537 530
 			$lifetime = get_config('session_cookie_lifetime', 0);
Please login to merge, or discard this patch.
core/classes/Module.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -49,8 +49,7 @@
 block discarded – undo
49 49
 				while(($module = readdir($moduleDir)) !== false){
50 50
 					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
51 51
 						self::$list[] = $module;
52
-					}
53
-					else{
52
+					} else{
54 53
 						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
55 54
 					}
56 55
 				}
Please login to merge, or discard this patch.
Indentation   +228 added lines, -228 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,252 +22,252 @@  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 extends BaseStaticClass{
27
+    class Module extends BaseStaticClass{
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
-		 * Initialise the module list by scanning the directory MODULE_PATH
37
-		 */
38
-		public function init(){
39
-			$logger = self::getLogger();
40
-			$logger->debug('Check if the application contains the modules ...');
41
-			$moduleDir = opendir(MODULE_PATH);
42
-			if (is_resource($moduleDir)){
43
-				while(($module = readdir($moduleDir)) !== false){
44
-					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
45
-						self::$list[] = $module;
46
-					}
47
-					else{
48
-						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
49
-					}
50
-				}
51
-				closedir($moduleDir);
52
-			}
53
-			ksort(self::$list);
35
+        /**
36
+         * Initialise the module list by scanning the directory MODULE_PATH
37
+         */
38
+        public function init(){
39
+            $logger = self::getLogger();
40
+            $logger->debug('Check if the application contains the modules ...');
41
+            $moduleDir = opendir(MODULE_PATH);
42
+            if (is_resource($moduleDir)){
43
+                while(($module = readdir($moduleDir)) !== false){
44
+                    if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
45
+                        self::$list[] = $module;
46
+                    }
47
+                    else{
48
+                        $logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
49
+                    }
50
+                }
51
+                closedir($moduleDir);
52
+            }
53
+            ksort(self::$list);
54 54
 			
55
-			if (! empty(self::$list)){
56
-				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
57
-			}
58
-		}
55
+            if (! empty(self::$list)){
56
+                $logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
57
+            }
58
+        }
59 59
 		
60 60
 
61
-		/**
62
-		 * Add new module in the list
63
-		 * @param string $name the name of the module
64
-		 *
65
-		 * @return object the current instance
66
-		 */
67
-		public function add($name){
68
-			self::$list[] = $name;
69
-			return $this;
70
-		}
61
+        /**
62
+         * Add new module in the list
63
+         * @param string $name the name of the module
64
+         *
65
+         * @return object the current instance
66
+         */
67
+        public function add($name){
68
+            self::$list[] = $name;
69
+            return $this;
70
+        }
71 71
 		
72
-		/**
73
-		 * Get the list of the custom autoload configuration from module if exists
74
-		 * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
75
-		 */
76
-		public static function getModulesAutoloadConfig(){
77
-			$logger = self::getLogger();
78
-			if (empty(self::$list)){
79
-				$logger->info('No module was loaded skipping.');
80
-				return false;
81
-			}
82
-			$autoloads = array();
83
-			$autoloads['libraries'] = array();
84
-			$autoloads['config']    = array();
85
-			$autoloads['models']    = array();
86
-			$autoloads['functions'] = array();
87
-			$autoloads['languages'] = array();
72
+        /**
73
+         * Get the list of the custom autoload configuration from module if exists
74
+         * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
75
+         */
76
+        public static function getModulesAutoloadConfig(){
77
+            $logger = self::getLogger();
78
+            if (empty(self::$list)){
79
+                $logger->info('No module was loaded skipping.');
80
+                return false;
81
+            }
82
+            $autoloads = array();
83
+            $autoloads['libraries'] = array();
84
+            $autoloads['config']    = array();
85
+            $autoloads['models']    = array();
86
+            $autoloads['functions'] = array();
87
+            $autoloads['languages'] = array();
88 88
 			
89
-			foreach (self::$list as $module) {
90
-				$file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
91
-				if (file_exists($file)){
92
-					$autoload = array();
93
-					require_once $file;
94
-					if (! empty($autoload) && is_array($autoload)){
95
-						$autoloads = array_merge_recursive($autoloads, $autoload);
96
-						unset($autoload);
97
-					}
98
-				}
99
-			}
100
-			return $autoloads;
101
-		}
89
+            foreach (self::$list as $module) {
90
+                $file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
91
+                if (file_exists($file)){
92
+                    $autoload = array();
93
+                    require_once $file;
94
+                    if (! empty($autoload) && is_array($autoload)){
95
+                        $autoloads = array_merge_recursive($autoloads, $autoload);
96
+                        unset($autoload);
97
+                    }
98
+                }
99
+            }
100
+            return $autoloads;
101
+        }
102 102
 
103
-		/**
104
-		 * Get the list of the custom routes configuration from module if exists
105
-		 * @return array|boolean the routes list or false if no module contains the routes configuration
106
-		 */
107
-		public static function getModulesRoutesConfig(){
108
-			$logger = self::getLogger();
109
-			if (empty(self::$list)){
110
-				$logger->info('No module was loaded skipping.');
111
-				return false;
112
-			}
113
-			$routes = array();
114
-			foreach (self::$list as $module) {
115
-				$file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
116
-				if (file_exists($file)){
117
-					$route = array();
118
-					require_once $file;
119
-					if (! empty($route) && is_array($route)){
120
-						$routes = array_merge($routes, $route);
121
-						unset($route);
122
-					}
123
-				}
124
-			}
125
-			return $routes;
126
-		}
103
+        /**
104
+         * Get the list of the custom routes configuration from module if exists
105
+         * @return array|boolean the routes list or false if no module contains the routes configuration
106
+         */
107
+        public static function getModulesRoutesConfig(){
108
+            $logger = self::getLogger();
109
+            if (empty(self::$list)){
110
+                $logger->info('No module was loaded skipping.');
111
+                return false;
112
+            }
113
+            $routes = array();
114
+            foreach (self::$list as $module) {
115
+                $file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
116
+                if (file_exists($file)){
117
+                    $route = array();
118
+                    require_once $file;
119
+                    if (! empty($route) && is_array($route)){
120
+                        $routes = array_merge($routes, $route);
121
+                        unset($route);
122
+                    }
123
+                }
124
+            }
125
+            return $routes;
126
+        }
127 127
 
128 128
 
129
-		/**
130
-		 * Check if in module list can have this controller
131
-		 * @see Module::findClassInModuleFullFilePath
132
-		 * @return boolean|string  false or null if no module have this controller, path the full path of the controller
133
-		 */
134
-		public static function findControllerFullPath($class, $module = null){
135
-			return self::findClassInModuleFullFilePath($class, $module, 'controllers');
136
-		}
129
+        /**
130
+         * Check if in module list can have this controller
131
+         * @see Module::findClassInModuleFullFilePath
132
+         * @return boolean|string  false or null if no module have this controller, path the full path of the controller
133
+         */
134
+        public static function findControllerFullPath($class, $module = null){
135
+            return self::findClassInModuleFullFilePath($class, $module, 'controllers');
136
+        }
137 137
 
138
-		/**
139
-		 * Check if in module list can have this model
140
-		 * @see Module::findClassInModuleFullFilePath
141
-		 * @return boolean|string  false or null if no module have this model, return the full path of this model
142
-		 */
143
-		public static function findModelFullPath($class, $module = null){
144
-			return self::findClassInModuleFullFilePath($class, $module, 'models');
145
-		}
138
+        /**
139
+         * Check if in module list can have this model
140
+         * @see Module::findClassInModuleFullFilePath
141
+         * @return boolean|string  false or null if no module have this model, return the full path of this model
142
+         */
143
+        public static function findModelFullPath($class, $module = null){
144
+            return self::findClassInModuleFullFilePath($class, $module, 'models');
145
+        }
146 146
 
147
-		/**
148
-		 * Check if in module list can have this library
149
-		 * @see Module::findClassInModuleFullFilePath
150
-		 * @return boolean|string  false or null if no module have this library,  return the full path of this library
151
-		 */
152
-		public static function findLibraryFullPath($class, $module = null){
153
-			return self::findClassInModuleFullFilePath($class, $module, 'libraries');
154
-		}
147
+        /**
148
+         * Check if in module list can have this library
149
+         * @see Module::findClassInModuleFullFilePath
150
+         * @return boolean|string  false or null if no module have this library,  return the full path of this library
151
+         */
152
+        public static function findLibraryFullPath($class, $module = null){
153
+            return self::findClassInModuleFullFilePath($class, $module, 'libraries');
154
+        }
155 155
 
156 156
 		
157
-		/**
158
-		 * Check if in module list can have this config
159
-		 * @see  Module::findNonClassInModuleFullFilePath
160
-		 * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
161
-		 */
162
-		public static function findConfigFullPath($configuration, $module = null){
163
-			return self::findNonClassInModuleFullFilePath($configuration, $module, 'config');
164
-		}
157
+        /**
158
+         * Check if in module list can have this config
159
+         * @see  Module::findNonClassInModuleFullFilePath
160
+         * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
161
+         */
162
+        public static function findConfigFullPath($configuration, $module = null){
163
+            return self::findNonClassInModuleFullFilePath($configuration, $module, 'config');
164
+        }
165 165
 
166
-		/**
167
-		 * Check if in module list can have this helper
168
-		 * @see  Module::findNonClassInModuleFullFilePath
169
-		 * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
170
-		 */
171
-		public static function findFunctionFullPath($helper, $module = null){
172
-			return self::findNonClassInModuleFullFilePath($helper, $module, 'functions');
173
-		}
166
+        /**
167
+         * Check if in module list can have this helper
168
+         * @see  Module::findNonClassInModuleFullFilePath
169
+         * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
170
+         */
171
+        public static function findFunctionFullPath($helper, $module = null){
172
+            return self::findNonClassInModuleFullFilePath($helper, $module, 'functions');
173
+        }
174 174
 
175
-		/**
176
-		 * Check if in module list can have this view
177
-		 * @see  Module::findNonClassInModuleFullFilePath
178
-		 * @return boolean|string  false or null if no module have this view, path the full path of the view
179
-		 */
180
-		public static function findViewFullPath($view, $module = null){
181
-			return self::findNonClassInModuleFullFilePath($view, $module, 'views');
182
-		}
175
+        /**
176
+         * Check if in module list can have this view
177
+         * @see  Module::findNonClassInModuleFullFilePath
178
+         * @return boolean|string  false or null if no module have this view, path the full path of the view
179
+         */
180
+        public static function findViewFullPath($view, $module = null){
181
+            return self::findNonClassInModuleFullFilePath($view, $module, 'views');
182
+        }
183 183
 
184
-		/**
185
-		 * Check if in module list can have this language
186
-		 * @see  Module::findNonClassInModuleFullFilePath
187
-		 * @return boolean|string  false or null if no module have this language,  return the full path of this language
188
-		 */
189
-		public static function findLanguageFullPath($language, $appLang, $module = null){
190
-			return self::findNonClassInModuleFullFilePath($language, $module, 'lang', $appLang);
191
-		}
184
+        /**
185
+         * Check if in module list can have this language
186
+         * @see  Module::findNonClassInModuleFullFilePath
187
+         * @return boolean|string  false or null if no module have this language,  return the full path of this language
188
+         */
189
+        public static function findLanguageFullPath($language, $appLang, $module = null){
190
+            return self::findNonClassInModuleFullFilePath($language, $module, 'lang', $appLang);
191
+        }
192 192
 
193
-		/**
194
-		 * Get the list of module loaded
195
-		 * @return array the module list
196
-		 */
197
-		public static function getModuleList(){
198
-			return self::$list;
199
-		}
193
+        /**
194
+         * Get the list of module loaded
195
+         * @return array the module list
196
+         */
197
+        public static function getModuleList(){
198
+            return self::$list;
199
+        }
200 200
 
201
-		/**
202
-		 * Check if the application has an module
203
-		 * @return boolean
204
-		 */
205
-		public static function hasModule(){
206
-			return !empty(self::$list);
207
-		}
201
+        /**
202
+         * Check if the application has an module
203
+         * @return boolean
204
+         */
205
+        public static function hasModule(){
206
+            return !empty(self::$list);
207
+        }
208 208
 
209
-		/**
210
-		 * Check if in module list can have the model, controller, library
211
-		 * @param  string $class the class name of library, model, controller
212
-		 * @param string $module the module name
213
-		 * @param string $type the name of the type "controllers", "libraries", "models"
214
-		 * @return boolean|string  false or null if no module 
215
-		 * have this class, return the full path of the class
216
-		 */
217
-		protected static function findClassInModuleFullFilePath($class, $module, $type){
218
-			$logger = self::getLogger();
219
-		    $class = str_ireplace('.php', '', $class);
220
-		    $class = ucfirst($class);
221
-		    $classFile = $class.'.php';
222
-		    $logger->debug('Checking the class [' . $class . '] in module [' . $module . '] for [' . $type . '] ...');
223
-		    $filePath = MODULE_PATH . $module . DS . $type . DS . $classFile;
224
-		    if (file_exists($filePath)){
225
-		        $logger->info('Found class [' . $class . '] in module [' . $module . '] for [' . $type . '] the file path is [' .$filePath. ']');
226
-		        return $filePath;
227
-		    }
228
-		    $logger->info('Class [' . $class . '] does not exist in the module [' .$module. '] for [' . $type . ']');
229
-		    return false;
230
-		}
209
+        /**
210
+         * Check if in module list can have the model, controller, library
211
+         * @param  string $class the class name of library, model, controller
212
+         * @param string $module the module name
213
+         * @param string $type the name of the type "controllers", "libraries", "models"
214
+         * @return boolean|string  false or null if no module 
215
+         * have this class, return the full path of the class
216
+         */
217
+        protected static function findClassInModuleFullFilePath($class, $module, $type){
218
+            $logger = self::getLogger();
219
+            $class = str_ireplace('.php', '', $class);
220
+            $class = ucfirst($class);
221
+            $classFile = $class.'.php';
222
+            $logger->debug('Checking the class [' . $class . '] in module [' . $module . '] for [' . $type . '] ...');
223
+            $filePath = MODULE_PATH . $module . DS . $type . DS . $classFile;
224
+            if (file_exists($filePath)){
225
+                $logger->info('Found class [' . $class . '] in module [' . $module . '] for [' . $type . '] the file path is [' .$filePath. ']');
226
+                return $filePath;
227
+            }
228
+            $logger->info('Class [' . $class . '] does not exist in the module [' .$module. '] for [' . $type . ']');
229
+            return false;
230
+        }
231 231
 
232
-		/**
233
-		 * Check if in module list can have the config, view, helper, language
234
-		 * @param string $name the name of config, view, helper, language
235
-		 * @param string $module the module name
236
-		 * @param string $type the name of the type "config", "functions", "views", "lang"
237
-		 * @param string|null $appLang the application language. This is use only when $type = "lang"
238
-		 * @return boolean|string  false or null if no module 
239
-		 * have this resource, return the full path of the resource
240
-		 */
241
-		protected static function findNonClassInModuleFullFilePath($name, $module, $type, $appLang = null){
242
-		    $logger = self::getLogger();
243
-		    $name = str_ireplace('.php', '', $name);
244
-		    $file = $name.'.php';
245
-		    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
246
-		    switch($type){
247
-		        case 'functions':
248
-		            $name = str_ireplace('function_', '', $name);
249
-		            $file = 'function_'.$name.'.php';
250
-		            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
251
-		        break;
252
-		        case 'views':
253
-		            $name = trim($name, '/\\');
254
-		            $name = str_ireplace('/', DS, $name);
255
-		            $file = $name . '.php';
256
-		            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
257
-		        break;
258
-		        case 'lang':
259
-		            $name = str_ireplace('lang_', '', $name);
260
-		            $file = 'lang_'.$name.'.php';
261
-		            $filePath = MODULE_PATH . $module . DS . $type . DS . $appLang . DS . $file;
262
-		        break;
263
-		    }
264
-		    $logger->debug('Checking resource [' . $name . '] in module [' .$module. '] for [' . $type . '] ...');
265
-		    if (file_exists($filePath)){
266
-		        $logger->info('Found resource [' . $name . '] in module [' .$module. '] for [' . $type . '] the file path is [' .$filePath. ']');
267
-		        return $filePath;
268
-		    }
269
-		    $logger->info('Resource [' . $name . '] does not exist in the module [' .$module. '] for [' . $type . ']');
270
-		    return false;
271
-		}
232
+        /**
233
+         * Check if in module list can have the config, view, helper, language
234
+         * @param string $name the name of config, view, helper, language
235
+         * @param string $module the module name
236
+         * @param string $type the name of the type "config", "functions", "views", "lang"
237
+         * @param string|null $appLang the application language. This is use only when $type = "lang"
238
+         * @return boolean|string  false or null if no module 
239
+         * have this resource, return the full path of the resource
240
+         */
241
+        protected static function findNonClassInModuleFullFilePath($name, $module, $type, $appLang = null){
242
+            $logger = self::getLogger();
243
+            $name = str_ireplace('.php', '', $name);
244
+            $file = $name.'.php';
245
+            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
246
+            switch($type){
247
+                case 'functions':
248
+                    $name = str_ireplace('function_', '', $name);
249
+                    $file = 'function_'.$name.'.php';
250
+                    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
251
+                break;
252
+                case 'views':
253
+                    $name = trim($name, '/\\');
254
+                    $name = str_ireplace('/', DS, $name);
255
+                    $file = $name . '.php';
256
+                    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
257
+                break;
258
+                case 'lang':
259
+                    $name = str_ireplace('lang_', '', $name);
260
+                    $file = 'lang_'.$name.'.php';
261
+                    $filePath = MODULE_PATH . $module . DS . $type . DS . $appLang . DS . $file;
262
+                break;
263
+            }
264
+            $logger->debug('Checking resource [' . $name . '] in module [' .$module. '] for [' . $type . '] ...');
265
+            if (file_exists($filePath)){
266
+                $logger->info('Found resource [' . $name . '] in module [' .$module. '] for [' . $type . '] the file path is [' .$filePath. ']');
267
+                return $filePath;
268
+            }
269
+            $logger->info('Resource [' . $name . '] does not exist in the module [' .$module. '] for [' . $type . ']');
270
+            return false;
271
+        }
272 272
 
273
-	}
273
+    }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 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 extends BaseStaticClass{
27
+	class Module extends BaseStaticClass {
28 28
 		
29 29
 		/**
30 30
 		 * list of loaded module
@@ -35,24 +35,24 @@  discard block
 block discarded – undo
35 35
 		/**
36 36
 		 * Initialise the module list by scanning the directory MODULE_PATH
37 37
 		 */
38
-		public function init(){
38
+		public function init() {
39 39
 			$logger = self::getLogger();
40 40
 			$logger->debug('Check if the application contains the modules ...');
41 41
 			$moduleDir = opendir(MODULE_PATH);
42
-			if (is_resource($moduleDir)){
43
-				while(($module = readdir($moduleDir)) !== false){
44
-					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
42
+			if (is_resource($moduleDir)) {
43
+				while (($module = readdir($moduleDir)) !== false) {
44
+					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)) {
45 45
 						self::$list[] = $module;
46 46
 					}
47
-					else{
48
-						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
47
+					else {
48
+						$logger->info('Skipping [' . $module . '], may be this is not a directory or does not exists or is invalid name');
49 49
 					}
50 50
 				}
51 51
 				closedir($moduleDir);
52 52
 			}
53 53
 			ksort(self::$list);
54 54
 			
55
-			if (! empty(self::$list)){
55
+			if (!empty(self::$list)) {
56 56
 				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
57 57
 			}
58 58
 		}
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		 *
65 65
 		 * @return object the current instance
66 66
 		 */
67
-		public function add($name){
67
+		public function add($name) {
68 68
 			self::$list[] = $name;
69 69
 			return $this;
70 70
 		}
@@ -73,9 +73,9 @@  discard block
 block discarded – undo
73 73
 		 * Get the list of the custom autoload configuration from module if exists
74 74
 		 * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
75 75
 		 */
76
-		public static function getModulesAutoloadConfig(){
76
+		public static function getModulesAutoloadConfig() {
77 77
 			$logger = self::getLogger();
78
-			if (empty(self::$list)){
78
+			if (empty(self::$list)) {
79 79
 				$logger->info('No module was loaded skipping.');
80 80
 				return false;
81 81
 			}
@@ -88,10 +88,10 @@  discard block
 block discarded – undo
88 88
 			
89 89
 			foreach (self::$list as $module) {
90 90
 				$file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
91
-				if (file_exists($file)){
91
+				if (file_exists($file)) {
92 92
 					$autoload = array();
93 93
 					require_once $file;
94
-					if (! empty($autoload) && is_array($autoload)){
94
+					if (!empty($autoload) && is_array($autoload)) {
95 95
 						$autoloads = array_merge_recursive($autoloads, $autoload);
96 96
 						unset($autoload);
97 97
 					}
@@ -104,19 +104,19 @@  discard block
 block discarded – undo
104 104
 		 * Get the list of the custom routes configuration from module if exists
105 105
 		 * @return array|boolean the routes list or false if no module contains the routes configuration
106 106
 		 */
107
-		public static function getModulesRoutesConfig(){
107
+		public static function getModulesRoutesConfig() {
108 108
 			$logger = self::getLogger();
109
-			if (empty(self::$list)){
109
+			if (empty(self::$list)) {
110 110
 				$logger->info('No module was loaded skipping.');
111 111
 				return false;
112 112
 			}
113 113
 			$routes = array();
114 114
 			foreach (self::$list as $module) {
115 115
 				$file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
116
-				if (file_exists($file)){
116
+				if (file_exists($file)) {
117 117
 					$route = array();
118 118
 					require_once $file;
119
-					if (! empty($route) && is_array($route)){
119
+					if (!empty($route) && is_array($route)) {
120 120
 						$routes = array_merge($routes, $route);
121 121
 						unset($route);
122 122
 					}
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 		 * @see Module::findClassInModuleFullFilePath
132 132
 		 * @return boolean|string  false or null if no module have this controller, path the full path of the controller
133 133
 		 */
134
-		public static function findControllerFullPath($class, $module = null){
134
+		public static function findControllerFullPath($class, $module = null) {
135 135
 			return self::findClassInModuleFullFilePath($class, $module, 'controllers');
136 136
 		}
137 137
 
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 		 * @see Module::findClassInModuleFullFilePath
141 141
 		 * @return boolean|string  false or null if no module have this model, return the full path of this model
142 142
 		 */
143
-		public static function findModelFullPath($class, $module = null){
143
+		public static function findModelFullPath($class, $module = null) {
144 144
 			return self::findClassInModuleFullFilePath($class, $module, 'models');
145 145
 		}
146 146
 
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 		 * @see Module::findClassInModuleFullFilePath
150 150
 		 * @return boolean|string  false or null if no module have this library,  return the full path of this library
151 151
 		 */
152
-		public static function findLibraryFullPath($class, $module = null){
152
+		public static function findLibraryFullPath($class, $module = null) {
153 153
 			return self::findClassInModuleFullFilePath($class, $module, 'libraries');
154 154
 		}
155 155
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		 * @see  Module::findNonClassInModuleFullFilePath
160 160
 		 * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
161 161
 		 */
162
-		public static function findConfigFullPath($configuration, $module = null){
162
+		public static function findConfigFullPath($configuration, $module = null) {
163 163
 			return self::findNonClassInModuleFullFilePath($configuration, $module, 'config');
164 164
 		}
165 165
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 		 * @see  Module::findNonClassInModuleFullFilePath
169 169
 		 * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
170 170
 		 */
171
-		public static function findFunctionFullPath($helper, $module = null){
171
+		public static function findFunctionFullPath($helper, $module = null) {
172 172
 			return self::findNonClassInModuleFullFilePath($helper, $module, 'functions');
173 173
 		}
174 174
 
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		 * @see  Module::findNonClassInModuleFullFilePath
178 178
 		 * @return boolean|string  false or null if no module have this view, path the full path of the view
179 179
 		 */
180
-		public static function findViewFullPath($view, $module = null){
180
+		public static function findViewFullPath($view, $module = null) {
181 181
 			return self::findNonClassInModuleFullFilePath($view, $module, 'views');
182 182
 		}
183 183
 
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 		 * @see  Module::findNonClassInModuleFullFilePath
187 187
 		 * @return boolean|string  false or null if no module have this language,  return the full path of this language
188 188
 		 */
189
-		public static function findLanguageFullPath($language, $appLang, $module = null){
189
+		public static function findLanguageFullPath($language, $appLang, $module = null) {
190 190
 			return self::findNonClassInModuleFullFilePath($language, $module, 'lang', $appLang);
191 191
 		}
192 192
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 		 * Get the list of module loaded
195 195
 		 * @return array the module list
196 196
 		 */
197
-		public static function getModuleList(){
197
+		public static function getModuleList() {
198 198
 			return self::$list;
199 199
 		}
200 200
 
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		 * Check if the application has an module
203 203
 		 * @return boolean
204 204
 		 */
205
-		public static function hasModule(){
205
+		public static function hasModule() {
206 206
 			return !empty(self::$list);
207 207
 		}
208 208
 
@@ -214,18 +214,18 @@  discard block
 block discarded – undo
214 214
 		 * @return boolean|string  false or null if no module 
215 215
 		 * have this class, return the full path of the class
216 216
 		 */
217
-		protected static function findClassInModuleFullFilePath($class, $module, $type){
217
+		protected static function findClassInModuleFullFilePath($class, $module, $type) {
218 218
 			$logger = self::getLogger();
219 219
 		    $class = str_ireplace('.php', '', $class);
220 220
 		    $class = ucfirst($class);
221
-		    $classFile = $class.'.php';
221
+		    $classFile = $class . '.php';
222 222
 		    $logger->debug('Checking the class [' . $class . '] in module [' . $module . '] for [' . $type . '] ...');
223 223
 		    $filePath = MODULE_PATH . $module . DS . $type . DS . $classFile;
224
-		    if (file_exists($filePath)){
225
-		        $logger->info('Found class [' . $class . '] in module [' . $module . '] for [' . $type . '] the file path is [' .$filePath. ']');
224
+		    if (file_exists($filePath)) {
225
+		        $logger->info('Found class [' . $class . '] in module [' . $module . '] for [' . $type . '] the file path is [' . $filePath . ']');
226 226
 		        return $filePath;
227 227
 		    }
228
-		    $logger->info('Class [' . $class . '] does not exist in the module [' .$module. '] for [' . $type . ']');
228
+		    $logger->info('Class [' . $class . '] does not exist in the module [' . $module . '] for [' . $type . ']');
229 229
 		    return false;
230 230
 		}
231 231
 
@@ -238,15 +238,15 @@  discard block
 block discarded – undo
238 238
 		 * @return boolean|string  false or null if no module 
239 239
 		 * have this resource, return the full path of the resource
240 240
 		 */
241
-		protected static function findNonClassInModuleFullFilePath($name, $module, $type, $appLang = null){
241
+		protected static function findNonClassInModuleFullFilePath($name, $module, $type, $appLang = null) {
242 242
 		    $logger = self::getLogger();
243 243
 		    $name = str_ireplace('.php', '', $name);
244
-		    $file = $name.'.php';
244
+		    $file = $name . '.php';
245 245
 		    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
246
-		    switch($type){
246
+		    switch ($type) {
247 247
 		        case 'functions':
248 248
 		            $name = str_ireplace('function_', '', $name);
249
-		            $file = 'function_'.$name.'.php';
249
+		            $file = 'function_' . $name . '.php';
250 250
 		            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
251 251
 		        break;
252 252
 		        case 'views':
@@ -257,16 +257,16 @@  discard block
 block discarded – undo
257 257
 		        break;
258 258
 		        case 'lang':
259 259
 		            $name = str_ireplace('lang_', '', $name);
260
-		            $file = 'lang_'.$name.'.php';
260
+		            $file = 'lang_' . $name . '.php';
261 261
 		            $filePath = MODULE_PATH . $module . DS . $type . DS . $appLang . DS . $file;
262 262
 		        break;
263 263
 		    }
264
-		    $logger->debug('Checking resource [' . $name . '] in module [' .$module. '] for [' . $type . '] ...');
265
-		    if (file_exists($filePath)){
266
-		        $logger->info('Found resource [' . $name . '] in module [' .$module. '] for [' . $type . '] the file path is [' .$filePath. ']');
264
+		    $logger->debug('Checking resource [' . $name . '] in module [' . $module . '] for [' . $type . '] ...');
265
+		    if (file_exists($filePath)) {
266
+		        $logger->info('Found resource [' . $name . '] in module [' . $module . '] for [' . $type . '] the file path is [' . $filePath . ']');
267 267
 		        return $filePath;
268 268
 		    }
269
-		    $logger->info('Resource [' . $name . '] does not exist in the module [' .$module. '] for [' . $type . ']');
269
+		    $logger->info('Resource [' . $name . '] does not exist in the module [' . $module . '] for [' . $type . ']');
270 270
 		    return false;
271 271
 		}
272 272
 
Please login to merge, or discard this patch.
core/libraries/Form.php 2 patches
Indentation   +294 added lines, -294 removed lines patch added patch discarded remove patch
@@ -1,322 +1,322 @@
 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 27
 
28
-	class Form{
28
+    class Form{
29 29
 
30
-		/**
31
-		 * Generate the form opened tag
32
-		 * @param  string $path       the form action path
33
-		 * @param  array  $attributes the additional form attributes
34
-		 * @param  string $method     the form method like 'GET', 'POST'
35
-		 * @param  string $enctype    the form enctype like "multipart/form-data"
36
-		 * @return string             the generated form html
37
-		 */
38
-		public static function open($path = null, array $attributes = array(), $method = 'POST', $enctype = null){
39
-			if($path){
40
-				$path = Url::site_url($path);
41
-			}
42
-			$method = strtoupper($method);
43
-			$str = null;
44
-			$str .= '<form action = "'.$path.'" method = "'.$method.'"';
45
-			if(! empty($enctype)){
46
-				$str .= ' enctype = "'.$enctype.'" ';
47
-			}
48
-			if(! isset($attributes['accept-charset'])){
49
-				$attributes['accept-charset'] = get_config('charset', 'utf-8');
50
-			}
51
-			$str .= attributes_to_string($attributes);
52
-			$str .= '>';
53
-			//if CSRF is enabled in the configuration
54
-			if(get_config('csrf_enable', false) && $method == 'POST'){
55
-				$csrfValue = Security::generateCSRF();
56
-				$csrfName = get_config('csrf_key', 'csrf_key');
57
-				$str .= static::hidden($csrfName, $csrfValue);
58
-			}
59
-			return $str;
60
-		}
30
+        /**
31
+         * Generate the form opened tag
32
+         * @param  string $path       the form action path
33
+         * @param  array  $attributes the additional form attributes
34
+         * @param  string $method     the form method like 'GET', 'POST'
35
+         * @param  string $enctype    the form enctype like "multipart/form-data"
36
+         * @return string             the generated form html
37
+         */
38
+        public static function open($path = null, array $attributes = array(), $method = 'POST', $enctype = null){
39
+            if($path){
40
+                $path = Url::site_url($path);
41
+            }
42
+            $method = strtoupper($method);
43
+            $str = null;
44
+            $str .= '<form action = "'.$path.'" method = "'.$method.'"';
45
+            if(! empty($enctype)){
46
+                $str .= ' enctype = "'.$enctype.'" ';
47
+            }
48
+            if(! isset($attributes['accept-charset'])){
49
+                $attributes['accept-charset'] = get_config('charset', 'utf-8');
50
+            }
51
+            $str .= attributes_to_string($attributes);
52
+            $str .= '>';
53
+            //if CSRF is enabled in the configuration
54
+            if(get_config('csrf_enable', false) && $method == 'POST'){
55
+                $csrfValue = Security::generateCSRF();
56
+                $csrfName = get_config('csrf_key', 'csrf_key');
57
+                $str .= static::hidden($csrfName, $csrfValue);
58
+            }
59
+            return $str;
60
+        }
61 61
 
62
-		/**
63
-		 * Generate the form opened tag for multipart like to send a file
64
-		 * @see Form::open() for more details
65
-		 * @return string the generated multipart form html
66
-		 */
67
-		public static function openMultipart($path = null, array $attributes = array(), $method = 'POST'){
68
-			return self::open($path, $attributes, $method, 'multipart/form-data');
69
-		}
62
+        /**
63
+         * Generate the form opened tag for multipart like to send a file
64
+         * @see Form::open() for more details
65
+         * @return string the generated multipart form html
66
+         */
67
+        public static function openMultipart($path = null, array $attributes = array(), $method = 'POST'){
68
+            return self::open($path, $attributes, $method, 'multipart/form-data');
69
+        }
70 70
 
71
-		/**
72
-		 * Generate the form close
73
-		 * @return string the form close html
74
-		 */
75
-		public static function close(){
76
-			return '</form>';
77
-		}
71
+        /**
72
+         * Generate the form close
73
+         * @return string the form close html
74
+         */
75
+        public static function close(){
76
+            return '</form>';
77
+        }
78 78
 
79
-		/**
80
-		 * Generate the form fieldset & legend
81
-		 * @param  string $legend the legend tag value
82
-		 * @param  array  $fieldsetAttributes the fieldset additional HTML attributes
83
-		 * @param  array  $legendAttributes the legend additional HTML attributes. Is used only is $legend is not empty
84
-		 * @return string         the generated fieldset value
85
-		 */
86
-		public static function fieldset($legend = '', array $fieldsetAttributes = array(), array $legendAttributes = array()){
87
-			$str = '<fieldset' . attributes_to_string($fieldsetAttributes) . '>';
88
-			if($legend){
89
-				$str .= '<legend' . attributes_to_string($legendAttributes) . '>'.$legend.'</legend>';
90
-			}
91
-			return $str;
92
-		}
79
+        /**
80
+         * Generate the form fieldset & legend
81
+         * @param  string $legend the legend tag value
82
+         * @param  array  $fieldsetAttributes the fieldset additional HTML attributes
83
+         * @param  array  $legendAttributes the legend additional HTML attributes. Is used only is $legend is not empty
84
+         * @return string         the generated fieldset value
85
+         */
86
+        public static function fieldset($legend = '', array $fieldsetAttributes = array(), array $legendAttributes = array()){
87
+            $str = '<fieldset' . attributes_to_string($fieldsetAttributes) . '>';
88
+            if($legend){
89
+                $str .= '<legend' . attributes_to_string($legendAttributes) . '>'.$legend.'</legend>';
90
+            }
91
+            return $str;
92
+        }
93 93
 
94
-		/**
95
-		 * Generate the fieldset close tag
96
-		 * @return string the generated html for fieldset close
97
-		 */
98
-		public static function fieldsetClose(){
99
-			return '</fieldset>';
100
-		}
94
+        /**
95
+         * Generate the fieldset close tag
96
+         * @return string the generated html for fieldset close
97
+         */
98
+        public static function fieldsetClose(){
99
+            return '</fieldset>';
100
+        }
101 101
 
102
-		/**
103
-		 * Get the error message for the given form field name.
104
-		 * This use the form validation information to get the error information.
105
-		 * @param  string $name the form field name
106
-		 * @return string       the error message if exists and null if not
107
-		 */
108
-		public static function error($name){
109
-			$return = null;
110
-			$obj = & get_instance();
111
-			if(isset($obj->formvalidation)){
112
-				$errors = $obj->formvalidation->returnErrors();
113
-				if(isset($errors[$name])){
114
-					list($errorStart, $errorEnd) = $obj->formvalidation->getErrorDelimiter();
115
-					$return = $errorStart . $errors[$name] . $errorEnd;
116
-				}
117
-			}
118
-			return $return;
119
-		}
102
+        /**
103
+         * Get the error message for the given form field name.
104
+         * This use the form validation information to get the error information.
105
+         * @param  string $name the form field name
106
+         * @return string       the error message if exists and null if not
107
+         */
108
+        public static function error($name){
109
+            $return = null;
110
+            $obj = & get_instance();
111
+            if(isset($obj->formvalidation)){
112
+                $errors = $obj->formvalidation->returnErrors();
113
+                if(isset($errors[$name])){
114
+                    list($errorStart, $errorEnd) = $obj->formvalidation->getErrorDelimiter();
115
+                    $return = $errorStart . $errors[$name] . $errorEnd;
116
+                }
117
+            }
118
+            return $return;
119
+        }
120 120
 
121
-		/**
122
-		 * Get the form field value
123
-		 * @param  string $name    the form field name
124
-		 * @param  mixed $default the default value if can not found the given form field name
125
-		 * @return mixed the form field value if is set, otherwise return the default value.
126
-		 */
127
-		public static function value($name, $default = null){
128
-			$value = get_instance()->request->query($name);
129
-			if(strlen($value) > 0){
130
-				return $value;
131
-			}
132
-			return $default;
133
-		}
121
+        /**
122
+         * Get the form field value
123
+         * @param  string $name    the form field name
124
+         * @param  mixed $default the default value if can not found the given form field name
125
+         * @return mixed the form field value if is set, otherwise return the default value.
126
+         */
127
+        public static function value($name, $default = null){
128
+            $value = get_instance()->request->query($name);
129
+            if(strlen($value) > 0){
130
+                return $value;
131
+            }
132
+            return $default;
133
+        }
134 134
 
135
-		/**
136
-		 * Generate the form label html content
137
-		 * @param  string $label      the title of the label
138
-		 * @param  string $for        the value of the label "for" attribute
139
-		 * @param  array  $attributes the additional attributes to be added
140
-		 * @return string the generated label html content
141
-		 */
142
-		public static function label($label, $for = '', array $attributes = array()){
143
-			$str = '<label';
144
-			if($for){
145
-				$str .= ' for = "'.$for.'"';
146
-			}
147
-			$str .= attributes_to_string($attributes);
148
-			$str .= '>';
149
-			$str .= $label.'</label>';
150
-			return $str;
151
-		}
135
+        /**
136
+         * Generate the form label html content
137
+         * @param  string $label      the title of the label
138
+         * @param  string $for        the value of the label "for" attribute
139
+         * @param  array  $attributes the additional attributes to be added
140
+         * @return string the generated label html content
141
+         */
142
+        public static function label($label, $for = '', array $attributes = array()){
143
+            $str = '<label';
144
+            if($for){
145
+                $str .= ' for = "'.$for.'"';
146
+            }
147
+            $str .= attributes_to_string($attributes);
148
+            $str .= '>';
149
+            $str .= $label.'</label>';
150
+            return $str;
151
+        }
152 152
 
153
-		/**
154
-		 * Generate the form field for input like "text", "email", "password", etc.
155
-		 * @param  string $name       the form field name
156
-		 * @param  mixed $value      the form field value to be set
157
-		 * @param  array  $attributes the additional attributes to be added in the form input
158
-		 * @param  string $type       the type of the form field (password, text, submit, button, etc.)
159
-		 * @return string             the generated form field html content for the input
160
-		 */
161
-		public static function input($name, $value = null, array $attributes = array(), $type = 'text'){
162
-			$str = null;
163
-			$str .= '<input name = "'.$name.'" value = "'.$value.'" type = "'.$type.'"';
164
-			$str .= attributes_to_string($attributes);
165
-			$str .= '/>';
166
-			return $str;
167
-		}
153
+        /**
154
+         * Generate the form field for input like "text", "email", "password", etc.
155
+         * @param  string $name       the form field name
156
+         * @param  mixed $value      the form field value to be set
157
+         * @param  array  $attributes the additional attributes to be added in the form input
158
+         * @param  string $type       the type of the form field (password, text, submit, button, etc.)
159
+         * @return string             the generated form field html content for the input
160
+         */
161
+        public static function input($name, $value = null, array $attributes = array(), $type = 'text'){
162
+            $str = null;
163
+            $str .= '<input name = "'.$name.'" value = "'.$value.'" type = "'.$type.'"';
164
+            $str .= attributes_to_string($attributes);
165
+            $str .= '/>';
166
+            return $str;
167
+        }
168 168
 		
169
-		/**
170
-		 * Generate the form field for "text"
171
-		 * @see Form::input() for more details
172
-		 */
173
-		public static function text($name, $value = null, array $attributes = array()){
174
-			return self::input($name, $value, $attributes, 'text');
175
-		}
169
+        /**
170
+         * Generate the form field for "text"
171
+         * @see Form::input() for more details
172
+         */
173
+        public static function text($name, $value = null, array $attributes = array()){
174
+            return self::input($name, $value, $attributes, 'text');
175
+        }
176 176
 
177
-		/**
178
-		 * Generate the form field for "password"
179
-		 * @see Form::input() for more details
180
-		 */
181
-		public static function password($name, $value = null, array $attributes = array()){
182
-			return self::input($name, $value, $attributes, 'password');
183
-		}
177
+        /**
178
+         * Generate the form field for "password"
179
+         * @see Form::input() for more details
180
+         */
181
+        public static function password($name, $value = null, array $attributes = array()){
182
+            return self::input($name, $value, $attributes, 'password');
183
+        }
184 184
 
185
-		/**
186
-		 * Generate the form field for "radio"
187
-		 * @see Form::input() for more details
188
-		 */
189
-		public static function radio($name, $value = null,  $checked = false, array $attributes = array()){
190
-			if($checked){
191
-				$attributes['checked'] = true;
192
-			}
193
-			return self::input($name, $value, $attributes, 'radio');
194
-		}
185
+        /**
186
+         * Generate the form field for "radio"
187
+         * @see Form::input() for more details
188
+         */
189
+        public static function radio($name, $value = null,  $checked = false, array $attributes = array()){
190
+            if($checked){
191
+                $attributes['checked'] = true;
192
+            }
193
+            return self::input($name, $value, $attributes, 'radio');
194
+        }
195 195
 
196
-		/**
197
-		 * Generate the form field for "checkbox"
198
-		 * @see Form::input() for more details
199
-		 */
200
-		public static function checkbox($name, $value = null, $checked = false, array $attributes = array()){
201
-			if($checked){
202
-				$attributes['checked'] = true;
203
-			}
204
-			return self::input($name, $value, $attributes, 'checkbox');
205
-		}
196
+        /**
197
+         * Generate the form field for "checkbox"
198
+         * @see Form::input() for more details
199
+         */
200
+        public static function checkbox($name, $value = null, $checked = false, array $attributes = array()){
201
+            if($checked){
202
+                $attributes['checked'] = true;
203
+            }
204
+            return self::input($name, $value, $attributes, 'checkbox');
205
+        }
206 206
 
207
-		/**
208
-		 * Generate the form field for "number"
209
-		 * @see Form::input() for more details
210
-		 */
211
-		public static function number($name, $value = null, array $attributes = array()){
212
-			return self::input($name, $value, $attributes, 'number');
213
-		}
207
+        /**
208
+         * Generate the form field for "number"
209
+         * @see Form::input() for more details
210
+         */
211
+        public static function number($name, $value = null, array $attributes = array()){
212
+            return self::input($name, $value, $attributes, 'number');
213
+        }
214 214
 
215
-		/**
216
-		 * Generate the form field for "phone"
217
-		 * @see Form::input() for more details
218
-		 */
219
-		public static function phone($name, $value = null, array $attributes = array()){
220
-			return self::input($name, $value, $attributes, 'phone');
221
-		}
215
+        /**
216
+         * Generate the form field for "phone"
217
+         * @see Form::input() for more details
218
+         */
219
+        public static function phone($name, $value = null, array $attributes = array()){
220
+            return self::input($name, $value, $attributes, 'phone');
221
+        }
222 222
 
223
-		/**
224
-		 * Generate the form field for "email"
225
-		 * @see Form::input() for more details
226
-		 */
227
-		public static function email($name, $value = null, array $attributes = array()){
228
-			return self::input($name, $value, $attributes, 'email');
229
-		}
223
+        /**
224
+         * Generate the form field for "email"
225
+         * @see Form::input() for more details
226
+         */
227
+        public static function email($name, $value = null, array $attributes = array()){
228
+            return self::input($name, $value, $attributes, 'email');
229
+        }
230 230
 		
231
-		/**
232
-		 * Generate the form field for "search"
233
-		 * @see Form::input() for more details
234
-		 */
235
-		public static function search($name, $value = null, array $attributes = array()){
236
-			return self::input($name, $value, $attributes, 'search');
237
-		}
231
+        /**
232
+         * Generate the form field for "search"
233
+         * @see Form::input() for more details
234
+         */
235
+        public static function search($name, $value = null, array $attributes = array()){
236
+            return self::input($name, $value, $attributes, 'search');
237
+        }
238 238
 		
239
-		/**
240
-		 * Generate the form field for "hidden"
241
-		 * @see Form::input() for more details
242
-		 */
243
-		public static function hidden($name, $value = null, array $attributes = array()){
244
-			return self::input($name, $value, $attributes, 'hidden');
245
-		}
239
+        /**
240
+         * Generate the form field for "hidden"
241
+         * @see Form::input() for more details
242
+         */
243
+        public static function hidden($name, $value = null, array $attributes = array()){
244
+            return self::input($name, $value, $attributes, 'hidden');
245
+        }
246 246
 		
247
-		/**
248
-		 * Generate the form field for "file"
249
-		 * @see Form::input() for more details
250
-		 */
251
-		public static function file($name, array $attributes = array()){
252
-			return self::input($name, null, $attributes, 'file');
253
-		}
247
+        /**
248
+         * Generate the form field for "file"
249
+         * @see Form::input() for more details
250
+         */
251
+        public static function file($name, array $attributes = array()){
252
+            return self::input($name, null, $attributes, 'file');
253
+        }
254 254
 		
255
-		/**
256
-		 * Generate the form field for "button"
257
-		 * @see Form::input() for more details
258
-		 */
259
-		public static function button($name, $value = null, array $attributes = array()){
260
-			return self::input($name, $value, $attributes, 'button');
261
-		}
255
+        /**
256
+         * Generate the form field for "button"
257
+         * @see Form::input() for more details
258
+         */
259
+        public static function button($name, $value = null, array $attributes = array()){
260
+            return self::input($name, $value, $attributes, 'button');
261
+        }
262 262
 		
263
-		/**
264
-		 * Generate the form field for "reset"
265
-		 * @see Form::input() for more details
266
-		 */
267
-		public static function reset($name, $value = null, array $attributes = array()){
268
-			return self::input($name, $value, $attributes, 'reset');
269
-		}
263
+        /**
264
+         * Generate the form field for "reset"
265
+         * @see Form::input() for more details
266
+         */
267
+        public static function reset($name, $value = null, array $attributes = array()){
268
+            return self::input($name, $value, $attributes, 'reset');
269
+        }
270 270
 		
271
-		/**
272
-		 * Generate the form field for "submit"
273
-		 * @see Form::input() for more details
274
-		 */
275
-		public static function submit($name, $value = null, array $attributes = array()){
276
-			return self::input($name, $value, $attributes, 'submit');
277
-		}
271
+        /**
272
+         * Generate the form field for "submit"
273
+         * @see Form::input() for more details
274
+         */
275
+        public static function submit($name, $value = null, array $attributes = array()){
276
+            return self::input($name, $value, $attributes, 'submit');
277
+        }
278 278
 
279
-		/**
280
-		 * Generate the form field for textarea
281
-		 * @param  string $name       the name of the textarea field
282
-		 * @param  string $value      the textarea field value
283
-		 * @param  array  $attributes the additional attributes to be added
284
-		 * @return string             the generated textarea form html content
285
-		 */
286
-		public static function textarea($name, $value = '', array $attributes = array()){
287
-			$str = null;
288
-			$str .= '<textarea name = "'.$name.'"';
289
-			$str .= attributes_to_string($attributes);
290
-			$str .= '>';
291
-			$str .= $value.'</textarea>';
292
-			return $str;
293
-		}
279
+        /**
280
+         * Generate the form field for textarea
281
+         * @param  string $name       the name of the textarea field
282
+         * @param  string $value      the textarea field value
283
+         * @param  array  $attributes the additional attributes to be added
284
+         * @return string             the generated textarea form html content
285
+         */
286
+        public static function textarea($name, $value = '', array $attributes = array()){
287
+            $str = null;
288
+            $str .= '<textarea name = "'.$name.'"';
289
+            $str .= attributes_to_string($attributes);
290
+            $str .= '>';
291
+            $str .= $value.'</textarea>';
292
+            return $str;
293
+        }
294 294
 		
295
-		/**
296
-		 * Generate the form field for select
297
-		 * @param  string $name       the name of the form field
298
-		 * @param  mixed|array $values      the values used to populate the "option" tags
299
-		 * @param  mixed $selected   the selected value in the option list
300
-		 * @param  array  $attributes the additional attribute to be added
301
-		 * @return string             the generated form field html content for select
302
-		 */
303
-		public static function select($name, $values = null, $selected = null, array $attributes = array()){
304
-			if(! is_array($values)){
305
-				$values = array('' => $values);
306
-			}
307
-			$str = null;
308
-			$str .= '<select name = "'.$name.'"';
309
-			$str .= attributes_to_string($attributes);
310
-			$str .= '>';
311
-			foreach($values as $key => $val){
312
-				$select = '';
313
-				if($key == $selected){
314
-					$select = 'selected';
315
-				}
316
-				$str .= '<option value = "'.$key.'" '.$select.'>'.$val.'</option>';
317
-			}
318
-			$str .= '</select>';
319
-			return $str;
320
-		}
295
+        /**
296
+         * Generate the form field for select
297
+         * @param  string $name       the name of the form field
298
+         * @param  mixed|array $values      the values used to populate the "option" tags
299
+         * @param  mixed $selected   the selected value in the option list
300
+         * @param  array  $attributes the additional attribute to be added
301
+         * @return string             the generated form field html content for select
302
+         */
303
+        public static function select($name, $values = null, $selected = null, array $attributes = array()){
304
+            if(! is_array($values)){
305
+                $values = array('' => $values);
306
+            }
307
+            $str = null;
308
+            $str .= '<select name = "'.$name.'"';
309
+            $str .= attributes_to_string($attributes);
310
+            $str .= '>';
311
+            foreach($values as $key => $val){
312
+                $select = '';
313
+                if($key == $selected){
314
+                    $select = 'selected';
315
+                }
316
+                $str .= '<option value = "'.$key.'" '.$select.'>'.$val.'</option>';
317
+            }
318
+            $str .= '</select>';
319
+            return $str;
320
+        }
321 321
 
322
-	}
322
+    }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
 	*/
26 26
 
27 27
 
28
-	class Form{
28
+	class Form {
29 29
 
30 30
 		/**
31 31
 		 * Generate the form opened tag
@@ -35,23 +35,23 @@  discard block
 block discarded – undo
35 35
 		 * @param  string $enctype    the form enctype like "multipart/form-data"
36 36
 		 * @return string             the generated form html
37 37
 		 */
38
-		public static function open($path = null, array $attributes = array(), $method = 'POST', $enctype = null){
39
-			if($path){
38
+		public static function open($path = null, array $attributes = array(), $method = 'POST', $enctype = null) {
39
+			if ($path) {
40 40
 				$path = Url::site_url($path);
41 41
 			}
42 42
 			$method = strtoupper($method);
43 43
 			$str = null;
44
-			$str .= '<form action = "'.$path.'" method = "'.$method.'"';
45
-			if(! empty($enctype)){
46
-				$str .= ' enctype = "'.$enctype.'" ';
44
+			$str .= '<form action = "' . $path . '" method = "' . $method . '"';
45
+			if (!empty($enctype)) {
46
+				$str .= ' enctype = "' . $enctype . '" ';
47 47
 			}
48
-			if(! isset($attributes['accept-charset'])){
48
+			if (!isset($attributes['accept-charset'])) {
49 49
 				$attributes['accept-charset'] = get_config('charset', 'utf-8');
50 50
 			}
51 51
 			$str .= attributes_to_string($attributes);
52 52
 			$str .= '>';
53 53
 			//if CSRF is enabled in the configuration
54
-			if(get_config('csrf_enable', false) && $method == 'POST'){
54
+			if (get_config('csrf_enable', false) && $method == 'POST') {
55 55
 				$csrfValue = Security::generateCSRF();
56 56
 				$csrfName = get_config('csrf_key', 'csrf_key');
57 57
 				$str .= static::hidden($csrfName, $csrfValue);
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		 * @see Form::open() for more details
65 65
 		 * @return string the generated multipart form html
66 66
 		 */
67
-		public static function openMultipart($path = null, array $attributes = array(), $method = 'POST'){
67
+		public static function openMultipart($path = null, array $attributes = array(), $method = 'POST') {
68 68
 			return self::open($path, $attributes, $method, 'multipart/form-data');
69 69
 		}
70 70
 
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 		 * Generate the form close
73 73
 		 * @return string the form close html
74 74
 		 */
75
-		public static function close(){
75
+		public static function close() {
76 76
 			return '</form>';
77 77
 		}
78 78
 
@@ -83,10 +83,10 @@  discard block
 block discarded – undo
83 83
 		 * @param  array  $legendAttributes the legend additional HTML attributes. Is used only is $legend is not empty
84 84
 		 * @return string         the generated fieldset value
85 85
 		 */
86
-		public static function fieldset($legend = '', array $fieldsetAttributes = array(), array $legendAttributes = array()){
86
+		public static function fieldset($legend = '', array $fieldsetAttributes = array(), array $legendAttributes = array()) {
87 87
 			$str = '<fieldset' . attributes_to_string($fieldsetAttributes) . '>';
88
-			if($legend){
89
-				$str .= '<legend' . attributes_to_string($legendAttributes) . '>'.$legend.'</legend>';
88
+			if ($legend) {
89
+				$str .= '<legend' . attributes_to_string($legendAttributes) . '>' . $legend . '</legend>';
90 90
 			}
91 91
 			return $str;
92 92
 		}
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		 * Generate the fieldset close tag
96 96
 		 * @return string the generated html for fieldset close
97 97
 		 */
98
-		public static function fieldsetClose(){
98
+		public static function fieldsetClose() {
99 99
 			return '</fieldset>';
100 100
 		}
101 101
 
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
 		 * @param  string $name the form field name
106 106
 		 * @return string       the error message if exists and null if not
107 107
 		 */
108
-		public static function error($name){
108
+		public static function error($name) {
109 109
 			$return = null;
110 110
 			$obj = & get_instance();
111
-			if(isset($obj->formvalidation)){
111
+			if (isset($obj->formvalidation)) {
112 112
 				$errors = $obj->formvalidation->returnErrors();
113
-				if(isset($errors[$name])){
113
+				if (isset($errors[$name])) {
114 114
 					list($errorStart, $errorEnd) = $obj->formvalidation->getErrorDelimiter();
115 115
 					$return = $errorStart . $errors[$name] . $errorEnd;
116 116
 				}
@@ -124,9 +124,9 @@  discard block
 block discarded – undo
124 124
 		 * @param  mixed $default the default value if can not found the given form field name
125 125
 		 * @return mixed the form field value if is set, otherwise return the default value.
126 126
 		 */
127
-		public static function value($name, $default = null){
127
+		public static function value($name, $default = null) {
128 128
 			$value = get_instance()->request->query($name);
129
-			if(strlen($value) > 0){
129
+			if (strlen($value) > 0) {
130 130
 				return $value;
131 131
 			}
132 132
 			return $default;
@@ -139,14 +139,14 @@  discard block
 block discarded – undo
139 139
 		 * @param  array  $attributes the additional attributes to be added
140 140
 		 * @return string the generated label html content
141 141
 		 */
142
-		public static function label($label, $for = '', array $attributes = array()){
142
+		public static function label($label, $for = '', array $attributes = array()) {
143 143
 			$str = '<label';
144
-			if($for){
145
-				$str .= ' for = "'.$for.'"';
144
+			if ($for) {
145
+				$str .= ' for = "' . $for . '"';
146 146
 			}
147 147
 			$str .= attributes_to_string($attributes);
148 148
 			$str .= '>';
149
-			$str .= $label.'</label>';
149
+			$str .= $label . '</label>';
150 150
 			return $str;
151 151
 		}
152 152
 
@@ -158,9 +158,9 @@  discard block
 block discarded – undo
158 158
 		 * @param  string $type       the type of the form field (password, text, submit, button, etc.)
159 159
 		 * @return string             the generated form field html content for the input
160 160
 		 */
161
-		public static function input($name, $value = null, array $attributes = array(), $type = 'text'){
161
+		public static function input($name, $value = null, array $attributes = array(), $type = 'text') {
162 162
 			$str = null;
163
-			$str .= '<input name = "'.$name.'" value = "'.$value.'" type = "'.$type.'"';
163
+			$str .= '<input name = "' . $name . '" value = "' . $value . '" type = "' . $type . '"';
164 164
 			$str .= attributes_to_string($attributes);
165 165
 			$str .= '/>';
166 166
 			return $str;
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 		 * Generate the form field for "text"
171 171
 		 * @see Form::input() for more details
172 172
 		 */
173
-		public static function text($name, $value = null, array $attributes = array()){
173
+		public static function text($name, $value = null, array $attributes = array()) {
174 174
 			return self::input($name, $value, $attributes, 'text');
175 175
 		}
176 176
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 		 * Generate the form field for "password"
179 179
 		 * @see Form::input() for more details
180 180
 		 */
181
-		public static function password($name, $value = null, array $attributes = array()){
181
+		public static function password($name, $value = null, array $attributes = array()) {
182 182
 			return self::input($name, $value, $attributes, 'password');
183 183
 		}
184 184
 
@@ -186,8 +186,8 @@  discard block
 block discarded – undo
186 186
 		 * Generate the form field for "radio"
187 187
 		 * @see Form::input() for more details
188 188
 		 */
189
-		public static function radio($name, $value = null,  $checked = false, array $attributes = array()){
190
-			if($checked){
189
+		public static function radio($name, $value = null, $checked = false, array $attributes = array()) {
190
+			if ($checked) {
191 191
 				$attributes['checked'] = true;
192 192
 			}
193 193
 			return self::input($name, $value, $attributes, 'radio');
@@ -197,8 +197,8 @@  discard block
 block discarded – undo
197 197
 		 * Generate the form field for "checkbox"
198 198
 		 * @see Form::input() for more details
199 199
 		 */
200
-		public static function checkbox($name, $value = null, $checked = false, array $attributes = array()){
201
-			if($checked){
200
+		public static function checkbox($name, $value = null, $checked = false, array $attributes = array()) {
201
+			if ($checked) {
202 202
 				$attributes['checked'] = true;
203 203
 			}
204 204
 			return self::input($name, $value, $attributes, 'checkbox');
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 		 * Generate the form field for "number"
209 209
 		 * @see Form::input() for more details
210 210
 		 */
211
-		public static function number($name, $value = null, array $attributes = array()){
211
+		public static function number($name, $value = null, array $attributes = array()) {
212 212
 			return self::input($name, $value, $attributes, 'number');
213 213
 		}
214 214
 
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 		 * Generate the form field for "phone"
217 217
 		 * @see Form::input() for more details
218 218
 		 */
219
-		public static function phone($name, $value = null, array $attributes = array()){
219
+		public static function phone($name, $value = null, array $attributes = array()) {
220 220
 			return self::input($name, $value, $attributes, 'phone');
221 221
 		}
222 222
 
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 		 * Generate the form field for "email"
225 225
 		 * @see Form::input() for more details
226 226
 		 */
227
-		public static function email($name, $value = null, array $attributes = array()){
227
+		public static function email($name, $value = null, array $attributes = array()) {
228 228
 			return self::input($name, $value, $attributes, 'email');
229 229
 		}
230 230
 		
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 		 * Generate the form field for "search"
233 233
 		 * @see Form::input() for more details
234 234
 		 */
235
-		public static function search($name, $value = null, array $attributes = array()){
235
+		public static function search($name, $value = null, array $attributes = array()) {
236 236
 			return self::input($name, $value, $attributes, 'search');
237 237
 		}
238 238
 		
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 		 * Generate the form field for "hidden"
241 241
 		 * @see Form::input() for more details
242 242
 		 */
243
-		public static function hidden($name, $value = null, array $attributes = array()){
243
+		public static function hidden($name, $value = null, array $attributes = array()) {
244 244
 			return self::input($name, $value, $attributes, 'hidden');
245 245
 		}
246 246
 		
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		 * Generate the form field for "file"
249 249
 		 * @see Form::input() for more details
250 250
 		 */
251
-		public static function file($name, array $attributes = array()){
251
+		public static function file($name, array $attributes = array()) {
252 252
 			return self::input($name, null, $attributes, 'file');
253 253
 		}
254 254
 		
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 		 * Generate the form field for "button"
257 257
 		 * @see Form::input() for more details
258 258
 		 */
259
-		public static function button($name, $value = null, array $attributes = array()){
259
+		public static function button($name, $value = null, array $attributes = array()) {
260 260
 			return self::input($name, $value, $attributes, 'button');
261 261
 		}
262 262
 		
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 		 * Generate the form field for "reset"
265 265
 		 * @see Form::input() for more details
266 266
 		 */
267
-		public static function reset($name, $value = null, array $attributes = array()){
267
+		public static function reset($name, $value = null, array $attributes = array()) {
268 268
 			return self::input($name, $value, $attributes, 'reset');
269 269
 		}
270 270
 		
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 		 * Generate the form field for "submit"
273 273
 		 * @see Form::input() for more details
274 274
 		 */
275
-		public static function submit($name, $value = null, array $attributes = array()){
275
+		public static function submit($name, $value = null, array $attributes = array()) {
276 276
 			return self::input($name, $value, $attributes, 'submit');
277 277
 		}
278 278
 
@@ -283,12 +283,12 @@  discard block
 block discarded – undo
283 283
 		 * @param  array  $attributes the additional attributes to be added
284 284
 		 * @return string             the generated textarea form html content
285 285
 		 */
286
-		public static function textarea($name, $value = '', array $attributes = array()){
286
+		public static function textarea($name, $value = '', array $attributes = array()) {
287 287
 			$str = null;
288
-			$str .= '<textarea name = "'.$name.'"';
288
+			$str .= '<textarea name = "' . $name . '"';
289 289
 			$str .= attributes_to_string($attributes);
290 290
 			$str .= '>';
291
-			$str .= $value.'</textarea>';
291
+			$str .= $value . '</textarea>';
292 292
 			return $str;
293 293
 		}
294 294
 		
@@ -300,20 +300,20 @@  discard block
 block discarded – undo
300 300
 		 * @param  array  $attributes the additional attribute to be added
301 301
 		 * @return string             the generated form field html content for select
302 302
 		 */
303
-		public static function select($name, $values = null, $selected = null, array $attributes = array()){
304
-			if(! is_array($values)){
303
+		public static function select($name, $values = null, $selected = null, array $attributes = array()) {
304
+			if (!is_array($values)) {
305 305
 				$values = array('' => $values);
306 306
 			}
307 307
 			$str = null;
308
-			$str .= '<select name = "'.$name.'"';
308
+			$str .= '<select name = "' . $name . '"';
309 309
 			$str .= attributes_to_string($attributes);
310 310
 			$str .= '>';
311
-			foreach($values as $key => $val){
311
+			foreach ($values as $key => $val) {
312 312
 				$select = '';
313
-				if($key == $selected){
313
+				if ($key == $selected) {
314 314
 					$select = 'selected';
315 315
 				}
316
-				$str .= '<option value = "'.$key.'" '.$select.'>'.$val.'</option>';
316
+				$str .= '<option value = "' . $key . '" ' . $select . '>' . $val . '</option>';
317 317
 			}
318 318
 			$str .= '</select>';
319 319
 			return $str;
Please login to merge, or discard this patch.
core/libraries/Assets.php 2 patches
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -1,149 +1,149 @@
 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 Assets.php
29
-	 *    
30
-	 *  This class contains static methods for generating static content links (images, Javascript, CSS, etc.).
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
-	 *  @since 1.0.0
39
-	 *  @filesource
40
-	 */
41
-	class Assets extends BaseStaticClass{
27
+    /**
28
+     *  @file Assets.php
29
+     *    
30
+     *  This class contains static methods for generating static content links (images, Javascript, CSS, etc.).
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
+     *  @since 1.0.0
39
+     *  @filesource
40
+     */
41
+    class Assets extends BaseStaticClass{
42 42
 
43 43
 
44
-		/**
45
-		 *  Generate the link of the assets file.
46
-		 *  
47
-		 *  Generates the absolute link of a file inside ASSETS_PATH folder.
48
-		 *  For example :
49
-		 *  	echo Assets::path('foo/bar/css/style.css'); => http://mysite.com/assets/foo/bar/css/style.css
50
-		 *  Note:
51
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
52
-		 *  
53
-		 *  @param string $asset the name of the assets file path with the extension.
54
-		 *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
55
-		 */
56
-		public static function path($asset){
57
-			$logger = self::getLogger();	
58
-			$path = ASSETS_PATH . $asset;
44
+        /**
45
+         *  Generate the link of the assets file.
46
+         *  
47
+         *  Generates the absolute link of a file inside ASSETS_PATH folder.
48
+         *  For example :
49
+         *  	echo Assets::path('foo/bar/css/style.css'); => http://mysite.com/assets/foo/bar/css/style.css
50
+         *  Note:
51
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
52
+         *  
53
+         *  @param string $asset the name of the assets file path with the extension.
54
+         *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
55
+         */
56
+        public static function path($asset){
57
+            $logger = self::getLogger();	
58
+            $path = ASSETS_PATH . $asset;
59 59
 			
60
-			$logger->debug('Including the Assets file [' . $path . ']');
61
-			//Check if the file exists
62
-			if(file_exists($path)){
63
-				$logger->info('Assets file [' . $path . '] included successfully');
64
-				return Url::base_url($path);
65
-			}
66
-			$logger->warning('Assets file [' . $path . '] does not exist');
67
-			return null;
68
-		}
60
+            $logger->debug('Including the Assets file [' . $path . ']');
61
+            //Check if the file exists
62
+            if(file_exists($path)){
63
+                $logger->info('Assets file [' . $path . '] included successfully');
64
+                return Url::base_url($path);
65
+            }
66
+            $logger->warning('Assets file [' . $path . '] does not exist');
67
+            return null;
68
+        }
69 69
 		
70
-		/**
71
-		 *  Generate the link of the css file.
72
-		 *  
73
-		 *  Generates the absolute link of a file containing the CSS style.
74
-		 *  For example :
75
-		 *  	echo Assets::css('mystyle'); => http://mysite.com/assets/css/mystyle.css
76
-		 *  Note:
77
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
78
-		 *  
79
-		 *  @param string $path the name of the css file without the extension.
80
-		 *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
81
-		 */
82
-		public static function css($path){
83
-			$logger = self::getLogger();
84
-			/*
70
+        /**
71
+         *  Generate the link of the css file.
72
+         *  
73
+         *  Generates the absolute link of a file containing the CSS style.
74
+         *  For example :
75
+         *  	echo Assets::css('mystyle'); => http://mysite.com/assets/css/mystyle.css
76
+         *  Note:
77
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
78
+         *  
79
+         *  @param string $path the name of the css file without the extension.
80
+         *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
81
+         */
82
+        public static function css($path){
83
+            $logger = self::getLogger();
84
+            /*
85 85
 			* if the file name contains the ".css" extension, replace it with 
86 86
 			* an empty string for better processing.
87 87
 			*/
88
-			$path = str_ireplace('.css', '', $path);
89
-			$path = ASSETS_PATH . 'css/' . $path . '.css';
88
+            $path = str_ireplace('.css', '', $path);
89
+            $path = ASSETS_PATH . 'css/' . $path . '.css';
90 90
 			
91
-			$logger->debug('Including the Assets file [' . $path . '] for CSS');
92
-			//Check if the file exists
93
-			if(file_exists($path)){
94
-				$logger->info('Assets file [' . $path . '] for CSS included successfully');
95
-				return Url::base_url($path);
96
-			}
97
-			$logger->warning('Assets file [' . $path . '] for CSS does not exist');
98
-			return null;
99
-		}
91
+            $logger->debug('Including the Assets file [' . $path . '] for CSS');
92
+            //Check if the file exists
93
+            if(file_exists($path)){
94
+                $logger->info('Assets file [' . $path . '] for CSS included successfully');
95
+                return Url::base_url($path);
96
+            }
97
+            $logger->warning('Assets file [' . $path . '] for CSS does not exist');
98
+            return null;
99
+        }
100 100
 
101
-		/**
102
-		 *  Generate the link of the javascript file.
103
-		 *  
104
-		 *  Generates the absolute link of a file containing the javascript.
105
-		 *  For example :
106
-		 *  	echo Assets::js('myscript'); => http://mysite.com/assets/js/myscript.js
107
-		 *  Note:
108
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
109
-		 *  
110
-		 *  @param string $path the name of the javascript file without the extension.
111
-		 *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
112
-		 */
113
-		public static function js($path){
114
-			$logger = self::getLogger();
115
-			$path = str_ireplace('.js', '', $path);
116
-			$path = ASSETS_PATH . 'js/' . $path . '.js';
117
-			$logger->debug('Including the Assets file [' . $path . '] for javascript');
118
-			if(file_exists($path)){
119
-				$logger->info('Assets file [' . $path . '] for Javascript included successfully');
120
-				return Url::base_url($path);
121
-			}
122
-			$logger->warning('Assets file [' . $path . '] for Javascript does not exist');
123
-			return null;
124
-		}
101
+        /**
102
+         *  Generate the link of the javascript file.
103
+         *  
104
+         *  Generates the absolute link of a file containing the javascript.
105
+         *  For example :
106
+         *  	echo Assets::js('myscript'); => http://mysite.com/assets/js/myscript.js
107
+         *  Note:
108
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
109
+         *  
110
+         *  @param string $path the name of the javascript file without the extension.
111
+         *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
112
+         */
113
+        public static function js($path){
114
+            $logger = self::getLogger();
115
+            $path = str_ireplace('.js', '', $path);
116
+            $path = ASSETS_PATH . 'js/' . $path . '.js';
117
+            $logger->debug('Including the Assets file [' . $path . '] for javascript');
118
+            if(file_exists($path)){
119
+                $logger->info('Assets file [' . $path . '] for Javascript included successfully');
120
+                return Url::base_url($path);
121
+            }
122
+            $logger->warning('Assets file [' . $path . '] for Javascript does not exist');
123
+            return null;
124
+        }
125 125
 
126
-		/**
127
-		 *  Generate the link of the image file.
128
-		 *  
129
-		 *  Generates the absolute link of a file containing the image.
130
-		 *  For example :
131
-		 *  	echo Assets::img('myimage.png'); => http://mysite.com/assets/images/myimage.png
132
-		 *  Note:
133
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
134
-		 *  
135
-		 *  @param string $path the name of the image file with the extension.
136
-		 *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
137
-		 */
138
-		public static function img($path){
139
-			$logger = self::getLogger();
140
-			$path = ASSETS_PATH . 'images/' . $path;
141
-			$logger->debug('Including the Assets file [' . $path . '] for image');
142
-			if(file_exists($path)){
143
-				$logger->info('Assets file [' . $path . '] for image included successfully');
144
-				return Url::base_url($path);
145
-			}
146
-			$logger->warning('Assets file [' . $path . '] for image does not exist');
147
-			return null;
148
-		}
149
-	}
126
+        /**
127
+         *  Generate the link of the image file.
128
+         *  
129
+         *  Generates the absolute link of a file containing the image.
130
+         *  For example :
131
+         *  	echo Assets::img('myimage.png'); => http://mysite.com/assets/images/myimage.png
132
+         *  Note:
133
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
134
+         *  
135
+         *  @param string $path the name of the image file with the extension.
136
+         *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
137
+         */
138
+        public static function img($path){
139
+            $logger = self::getLogger();
140
+            $path = ASSETS_PATH . 'images/' . $path;
141
+            $logger->debug('Including the Assets file [' . $path . '] for image');
142
+            if(file_exists($path)){
143
+                $logger->info('Assets file [' . $path . '] for image included successfully');
144
+                return Url::base_url($path);
145
+            }
146
+            $logger->warning('Assets file [' . $path . '] for image does not exist');
147
+            return null;
148
+        }
149
+    }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 	 *  @since 1.0.0
39 39
 	 *  @filesource
40 40
 	 */
41
-	class Assets extends BaseStaticClass{
41
+	class Assets extends BaseStaticClass {
42 42
 
43 43
 
44 44
 		/**
@@ -53,13 +53,13 @@  discard block
 block discarded – undo
53 53
 		 *  @param string $asset the name of the assets file path with the extension.
54 54
 		 *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
55 55
 		 */
56
-		public static function path($asset){
56
+		public static function path($asset) {
57 57
 			$logger = self::getLogger();	
58 58
 			$path = ASSETS_PATH . $asset;
59 59
 			
60 60
 			$logger->debug('Including the Assets file [' . $path . ']');
61 61
 			//Check if the file exists
62
-			if(file_exists($path)){
62
+			if (file_exists($path)) {
63 63
 				$logger->info('Assets file [' . $path . '] included successfully');
64 64
 				return Url::base_url($path);
65 65
 			}
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 		 *  @param string $path the name of the css file without the extension.
80 80
 		 *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
81 81
 		 */
82
-		public static function css($path){
82
+		public static function css($path) {
83 83
 			$logger = self::getLogger();
84 84
 			/*
85 85
 			* if the file name contains the ".css" extension, replace it with 
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			
91 91
 			$logger->debug('Including the Assets file [' . $path . '] for CSS');
92 92
 			//Check if the file exists
93
-			if(file_exists($path)){
93
+			if (file_exists($path)) {
94 94
 				$logger->info('Assets file [' . $path . '] for CSS included successfully');
95 95
 				return Url::base_url($path);
96 96
 			}
@@ -110,12 +110,12 @@  discard block
 block discarded – undo
110 110
 		 *  @param string $path the name of the javascript file without the extension.
111 111
 		 *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
112 112
 		 */
113
-		public static function js($path){
113
+		public static function js($path) {
114 114
 			$logger = self::getLogger();
115 115
 			$path = str_ireplace('.js', '', $path);
116 116
 			$path = ASSETS_PATH . 'js/' . $path . '.js';
117 117
 			$logger->debug('Including the Assets file [' . $path . '] for javascript');
118
-			if(file_exists($path)){
118
+			if (file_exists($path)) {
119 119
 				$logger->info('Assets file [' . $path . '] for Javascript included successfully');
120 120
 				return Url::base_url($path);
121 121
 			}
@@ -135,11 +135,11 @@  discard block
 block discarded – undo
135 135
 		 *  @param string $path the name of the image file with the extension.
136 136
 		 *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
137 137
 		 */
138
-		public static function img($path){
138
+		public static function img($path) {
139 139
 			$logger = self::getLogger();
140 140
 			$path = ASSETS_PATH . 'images/' . $path;
141 141
 			$logger->debug('Including the Assets file [' . $path . '] for image');
142
-			if(file_exists($path)){
142
+			if (file_exists($path)) {
143 143
 				$logger->info('Assets file [' . $path . '] for image included successfully');
144 144
 				return Url::base_url($path);
145 145
 			}
Please login to merge, or discard this patch.
core/classes/DBSessionHandler.php 2 patches
Indentation   +296 added lines, -296 removed lines patch added patch discarded remove patch
@@ -1,75 +1,75 @@  discard block
 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
-	 * check if the interface "SessionHandlerInterface" exists (normally in PHP 5.4 this already exists)
29
-	 */
30
-	if ( !interface_exists('SessionHandlerInterface')){
31
-		show_error('"SessionHandlerInterface" interface does not exists or is disabled can not use it to handler database session.');
32
-	}
33
-
34
-	class DBSessionHandler extends BaseClass implements SessionHandlerInterface{
27
+    /**
28
+     * check if the interface "SessionHandlerInterface" exists (normally in PHP 5.4 this already exists)
29
+     */
30
+    if ( !interface_exists('SessionHandlerInterface')){
31
+        show_error('"SessionHandlerInterface" interface does not exists or is disabled can not use it to handler database session.');
32
+    }
33
+
34
+    class DBSessionHandler extends BaseClass implements SessionHandlerInterface{
35 35
 		
36
-		/**
37
-		 * The encryption method to use to encrypt session data in database
38
-		 * @const string
39
-		 */
40
-		const DB_SESSION_HASH_METHOD = 'AES-256-CBC';
36
+        /**
37
+         * The encryption method to use to encrypt session data in database
38
+         * @const string
39
+         */
40
+        const DB_SESSION_HASH_METHOD = 'AES-256-CBC';
41 41
 		
42
-		/**
43
-		 * Super global instance
44
-		 * @var object
45
-		 */
46
-		protected $OBJ = null;
47
-
48
-		/**
49
-		 * Session secret to use 
50
-		 * @var string
51
-		 */
52
-		private $sessionSecret = null;
53
-
54
-		/**
55
-		 * The initialisation vector to use for openssl
56
-		 * @var string
57
-		 */
58
-		private $iv = null;
59
-
60
-		/**
61
-		 * The model instance to use
62
-		 * @var object
63
-		 */
64
-		private $modelInstance = null;
65
-
66
-		/**
67
-		 * The columns of the table to use to store session data
68
-		 * @var array
69
-		 */
70
-		private $sessionTableColumns = array();
71
-
72
-		/**
42
+        /**
43
+         * Super global instance
44
+         * @var object
45
+         */
46
+        protected $OBJ = null;
47
+
48
+        /**
49
+         * Session secret to use 
50
+         * @var string
51
+         */
52
+        private $sessionSecret = null;
53
+
54
+        /**
55
+         * The initialisation vector to use for openssl
56
+         * @var string
57
+         */
58
+        private $iv = null;
59
+
60
+        /**
61
+         * The model instance to use
62
+         * @var object
63
+         */
64
+        private $modelInstance = null;
65
+
66
+        /**
67
+         * The columns of the table to use to store session data
68
+         * @var array
69
+         */
70
+        private $sessionTableColumns = array();
71
+
72
+        /**
73 73
          * Instance of the Loader class
74 74
          * @var Loader
75 75
          */
@@ -79,225 +79,225 @@  discard block
 block discarded – undo
79 79
          * Create new instance of Database session handler
80 80
          * @param object $modelInstance the model instance
81 81
          */
82
-		public function __construct(DBSessionHandlerModel $modelInstance = null){
83
-			parent::__construct();
82
+        public function __construct(DBSessionHandlerModel $modelInstance = null){
83
+            parent::__construct();
84 84
 			
85
-	    	//Set Loader instance to use
86
-	        $this->setDependencyInstanceFromParamOrCreate('loader', null, 'Loader', 'classes');
85
+            //Set Loader instance to use
86
+            $this->setDependencyInstanceFromParamOrCreate('loader', null, 'Loader', 'classes');
87 87
 	       
88
-		    $this->OBJ = & get_instance();
88
+            $this->OBJ = & get_instance();
89 89
 		    
90
-			if (is_object($modelInstance)){
91
-				$this->setModelInstance($modelInstance);
92
-			}
93
-		}
94
-
95
-		/**
96
-		 * Set the session secret used to encrypt the data in database 
97
-		 * @param string $secret the base64 string secret
98
-		 */
99
-		public function setSessionSecret($secret){
100
-			$this->sessionSecret = $secret;
101
-			return $this;
102
-		}
103
-
104
-		/**
105
-		 * Return the session secret
106
-		 * @return string 
107
-		 */
108
-		public function getSessionSecret(){
109
-			return $this->sessionSecret;
110
-		}
111
-
112
-
113
-		/**
114
-		 * Set the initializer vector for openssl 
115
-		 * @param string $key the session secret used in base64 format
116
-		 */
117
-		public function setInitializerVector($key){
118
-			$ivLength = openssl_cipher_iv_length(self::DB_SESSION_HASH_METHOD);
119
-			$key = base64_decode($key);
120
-			$this->iv = substr(hash('sha256', $key), 0, $ivLength);
121
-			return $this;
122
-		}
123
-
124
-		/**
125
-		 * Return the initializer vector
126
-		 * @return string 
127
-		 */
128
-		public function getInitializerVector(){
129
-			return $this->iv;
130
-		}
131
-
132
-		/**
133
-		 * Open the database session handler, here nothing to do just return true
134
-		 * @param  string $savePath    the session save path
135
-		 * @param  string $sessionName the session name
136
-		 * @return boolean 
137
-		 */
138
-		public function open($savePath, $sessionName){
139
-			$this->logger->debug('Opening database session handler for [' . $sessionName . ']');
140
-			//try to check if session secret is set before
141
-			$secret = $this->getSessionSecret();
142
-			if (empty($secret)){
143
-				$secret = get_config('session_secret', null);
144
-				$this->setSessionSecret($secret);
145
-			}
146
-			$this->logger->info('Session secret: ' . $secret);
147
-
148
-			if (! is_object($this->modelInstance)){
149
-				$this->setModelInstanceFromSessionConfig();
150
-			}
151
-			$this->setInitializerVector($secret);
152
-
153
-			//set session tables columns
154
-			$this->sessionTableColumns = $this->modelInstance->getSessionTableColumns();
155
-
156
-			if (empty($this->sessionTableColumns)){
157
-				show_error('The session handler is "database" but the table columns not set');
158
-			}
159
-			$this->logger->info('Database session, the model columns are listed below: ' . stringfy_vars($this->sessionTableColumns));
90
+            if (is_object($modelInstance)){
91
+                $this->setModelInstance($modelInstance);
92
+            }
93
+        }
94
+
95
+        /**
96
+         * Set the session secret used to encrypt the data in database 
97
+         * @param string $secret the base64 string secret
98
+         */
99
+        public function setSessionSecret($secret){
100
+            $this->sessionSecret = $secret;
101
+            return $this;
102
+        }
103
+
104
+        /**
105
+         * Return the session secret
106
+         * @return string 
107
+         */
108
+        public function getSessionSecret(){
109
+            return $this->sessionSecret;
110
+        }
111
+
112
+
113
+        /**
114
+         * Set the initializer vector for openssl 
115
+         * @param string $key the session secret used in base64 format
116
+         */
117
+        public function setInitializerVector($key){
118
+            $ivLength = openssl_cipher_iv_length(self::DB_SESSION_HASH_METHOD);
119
+            $key = base64_decode($key);
120
+            $this->iv = substr(hash('sha256', $key), 0, $ivLength);
121
+            return $this;
122
+        }
123
+
124
+        /**
125
+         * Return the initializer vector
126
+         * @return string 
127
+         */
128
+        public function getInitializerVector(){
129
+            return $this->iv;
130
+        }
131
+
132
+        /**
133
+         * Open the database session handler, here nothing to do just return true
134
+         * @param  string $savePath    the session save path
135
+         * @param  string $sessionName the session name
136
+         * @return boolean 
137
+         */
138
+        public function open($savePath, $sessionName){
139
+            $this->logger->debug('Opening database session handler for [' . $sessionName . ']');
140
+            //try to check if session secret is set before
141
+            $secret = $this->getSessionSecret();
142
+            if (empty($secret)){
143
+                $secret = get_config('session_secret', null);
144
+                $this->setSessionSecret($secret);
145
+            }
146
+            $this->logger->info('Session secret: ' . $secret);
147
+
148
+            if (! is_object($this->modelInstance)){
149
+                $this->setModelInstanceFromSessionConfig();
150
+            }
151
+            $this->setInitializerVector($secret);
152
+
153
+            //set session tables columns
154
+            $this->sessionTableColumns = $this->modelInstance->getSessionTableColumns();
155
+
156
+            if (empty($this->sessionTableColumns)){
157
+                show_error('The session handler is "database" but the table columns not set');
158
+            }
159
+            $this->logger->info('Database session, the model columns are listed below: ' . stringfy_vars($this->sessionTableColumns));
160 160
 			
161
-			//delete the expired session
162
-			$timeActivity = get_config('session_inactivity_time', 100);
163
-			$this->gc($timeActivity);
161
+            //delete the expired session
162
+            $timeActivity = get_config('session_inactivity_time', 100);
163
+            $this->gc($timeActivity);
164 164
 			
165
-			return true;
166
-		}
167
-
168
-		/**
169
-		 * Close the session
170
-		 * @return boolean
171
-		 */
172
-		public function close(){
173
-			$this->logger->debug('Closing database session handler');
174
-			return true;
175
-		}
176
-
177
-		/**
178
-		 * Get the session value for the given session id
179
-		 * @param  string $sid the session id to use
180
-		 * @return string      the session data in serialiaze format
181
-		 */
182
-		public function read($sid){
183
-			$this->logger->debug('Reading database session data for SID: ' . $sid);
184
-			$instance = $this->getModelInstance();
185
-			$columns = $this->sessionTableColumns;
186
-			$this->loader->functions('user_agent'); 
187
-			$this->loader->library('Browser'); 
165
+            return true;
166
+        }
167
+
168
+        /**
169
+         * Close the session
170
+         * @return boolean
171
+         */
172
+        public function close(){
173
+            $this->logger->debug('Closing database session handler');
174
+            return true;
175
+        }
176
+
177
+        /**
178
+         * Get the session value for the given session id
179
+         * @param  string $sid the session id to use
180
+         * @return string      the session data in serialiaze format
181
+         */
182
+        public function read($sid){
183
+            $this->logger->debug('Reading database session data for SID: ' . $sid);
184
+            $instance = $this->getModelInstance();
185
+            $columns = $this->sessionTableColumns;
186
+            $this->loader->functions('user_agent'); 
187
+            $this->loader->library('Browser'); 
188 188
 			
189
-			$ip = get_ip();
190
-			$host = @gethostbyaddr($ip) or null;
191
-			$browser = $this->OBJ->browser->getPlatform().', '.$this->OBJ->browser->getBrowser().' '.$this->OBJ->browser->getVersion();
189
+            $ip = get_ip();
190
+            $host = @gethostbyaddr($ip) or null;
191
+            $browser = $this->OBJ->browser->getPlatform().', '.$this->OBJ->browser->getBrowser().' '.$this->OBJ->browser->getVersion();
192 192
 			
193
-			$data = $instance->get_by(array($columns['sid'] => $sid, $columns['shost'] => $host, $columns['sbrowser'] => $browser));
194
-			if ($data && isset($data->{$columns['sdata']})){
195
-				//checking inactivity 
196
-				$timeInactivity = time() - get_config('session_inactivity_time', 100);
197
-				if ($data->{$columns['stime']} < $timeInactivity){
198
-					$this->logger->info('Database session data for SID: ' . $sid . ' already expired, destroy it');
199
-					$this->destroy($sid);
200
-					return null;
201
-				}
202
-				return $this->decode($data->{$columns['sdata']});
203
-			}
204
-			$this->logger->info('Database session data for SID: ' . $sid . ' is not valid return false, may be the session ID is wrong');
205
-			return null;
206
-		}
207
-
208
-		/**
209
-		 * Save the session data
210
-		 * @param  string $sid  the session ID
211
-		 * @param  mixed $data the session data to save in serialize format
212
-		 * @return boolean 
213
-		 */
214
-		public function write($sid, $data){
215
-			$this->logger->debug('Saving database session data for SID: ' . $sid . ', data: ' . stringfy_vars($data));
216
-			$instance = $this->getModelInstance();
217
-			$columns = $this->sessionTableColumns;
218
-
219
-			$this->loader->functions('user_agent'); 
220
-			$this->loader->library('Browser'); 
221
-
222
-			$ip = get_ip();
223
-			$keyValue = $instance->getKeyValue();
224
-			$host = @gethostbyaddr($ip) or null;
225
-			$browser = $this->OBJ->browser->getPlatform().', '.$this->OBJ->browser->getBrowser().' '.$this->OBJ->browser->getVersion();
226
-			$data = $this->encode($data);
227
-			$params = array(
228
-							$columns['sid'] => $sid,
229
-							$columns['sdata'] => $data,
230
-							$columns['stime'] => time(),
231
-							$columns['shost'] => $host,
232
-							$columns['sbrowser'] => $browser,
233
-							$columns['sip'] => $ip,
234
-							$columns['skey'] => $keyValue
235
-						);
236
-			$this->logger->info('Database session data to save are listed below :' . stringfy_vars($params));
237
-			$exists = $instance->get($sid);
238
-			if ($exists){
239
-				$this->logger->info('Session data for SID: ' . $sid . ' already exists, just update it');
240
-				//update
241
-				unset($params[$columns['sid']]);
242
-				return $instance->update($sid, $params);
243
-			}
244
-			$this->logger->info('Session data for SID: ' . $sid . ' not yet exists, insert it now');
245
-			return $instance->insert($params);
246
-		}
247
-
248
-
249
-		/**
250
-		 * Destroy the session data for the given session id
251
-		 * @param  string $sid the session id value
252
-		 * @return boolean
253
-		 */
254
-		public function destroy($sid){
255
-			$this->logger->debug('Destroy of session data for SID: ' . $sid);
256
-			$instance = $this->modelInstance;
257
-			$instance->delete($sid);
258
-			return true;
259
-		}
260
-
261
-		/**
262
-		 * Clean the expire session data to save espace
263
-		 * @param  integer $maxLifetime the max lifetime
264
-		 * @return boolean
265
-		 */
266
-		public function gc($maxLifetime){
267
-			$instance = $this->modelInstance;
268
-			$time = time() - $maxLifetime;
269
-			$this->logger->debug('Garbage collector of expired session. maxLifetime [' . $maxLifetime . '] sec, expired time [' . $time . ']');
270
-			$instance->deleteByTime($time);
271
-			return true;
272
-		}
273
-
274
-		/**
275
-		 * Encode the session data using the openssl
276
-		 * @param  mixed $data the session data to encode
277
-		 * @return mixed the encoded session data
278
-		 */
279
-		public function encode($data){
280
-			$key = base64_decode($this->sessionSecret);
281
-			$dataEncrypted = openssl_encrypt($data , self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
282
-			$output = base64_encode($dataEncrypted);
283
-			return $output;
284
-		}
285
-
286
-
287
-		/**
288
-		 * Decode the session data using the openssl
289
-		 * @param  mixed $data the data to decode
290
-		 * @return mixed       the decoded data
291
-		 */
292
-		public function decode($data){
293
-			$key = base64_decode($this->sessionSecret);
294
-			$data = base64_decode($data);
295
-			$data = openssl_decrypt($data, self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
296
-			return $data;
297
-		}
193
+            $data = $instance->get_by(array($columns['sid'] => $sid, $columns['shost'] => $host, $columns['sbrowser'] => $browser));
194
+            if ($data && isset($data->{$columns['sdata']})){
195
+                //checking inactivity 
196
+                $timeInactivity = time() - get_config('session_inactivity_time', 100);
197
+                if ($data->{$columns['stime']} < $timeInactivity){
198
+                    $this->logger->info('Database session data for SID: ' . $sid . ' already expired, destroy it');
199
+                    $this->destroy($sid);
200
+                    return null;
201
+                }
202
+                return $this->decode($data->{$columns['sdata']});
203
+            }
204
+            $this->logger->info('Database session data for SID: ' . $sid . ' is not valid return false, may be the session ID is wrong');
205
+            return null;
206
+        }
207
+
208
+        /**
209
+         * Save the session data
210
+         * @param  string $sid  the session ID
211
+         * @param  mixed $data the session data to save in serialize format
212
+         * @return boolean 
213
+         */
214
+        public function write($sid, $data){
215
+            $this->logger->debug('Saving database session data for SID: ' . $sid . ', data: ' . stringfy_vars($data));
216
+            $instance = $this->getModelInstance();
217
+            $columns = $this->sessionTableColumns;
218
+
219
+            $this->loader->functions('user_agent'); 
220
+            $this->loader->library('Browser'); 
221
+
222
+            $ip = get_ip();
223
+            $keyValue = $instance->getKeyValue();
224
+            $host = @gethostbyaddr($ip) or null;
225
+            $browser = $this->OBJ->browser->getPlatform().', '.$this->OBJ->browser->getBrowser().' '.$this->OBJ->browser->getVersion();
226
+            $data = $this->encode($data);
227
+            $params = array(
228
+                            $columns['sid'] => $sid,
229
+                            $columns['sdata'] => $data,
230
+                            $columns['stime'] => time(),
231
+                            $columns['shost'] => $host,
232
+                            $columns['sbrowser'] => $browser,
233
+                            $columns['sip'] => $ip,
234
+                            $columns['skey'] => $keyValue
235
+                        );
236
+            $this->logger->info('Database session data to save are listed below :' . stringfy_vars($params));
237
+            $exists = $instance->get($sid);
238
+            if ($exists){
239
+                $this->logger->info('Session data for SID: ' . $sid . ' already exists, just update it');
240
+                //update
241
+                unset($params[$columns['sid']]);
242
+                return $instance->update($sid, $params);
243
+            }
244
+            $this->logger->info('Session data for SID: ' . $sid . ' not yet exists, insert it now');
245
+            return $instance->insert($params);
246
+        }
247
+
248
+
249
+        /**
250
+         * Destroy the session data for the given session id
251
+         * @param  string $sid the session id value
252
+         * @return boolean
253
+         */
254
+        public function destroy($sid){
255
+            $this->logger->debug('Destroy of session data for SID: ' . $sid);
256
+            $instance = $this->modelInstance;
257
+            $instance->delete($sid);
258
+            return true;
259
+        }
260
+
261
+        /**
262
+         * Clean the expire session data to save espace
263
+         * @param  integer $maxLifetime the max lifetime
264
+         * @return boolean
265
+         */
266
+        public function gc($maxLifetime){
267
+            $instance = $this->modelInstance;
268
+            $time = time() - $maxLifetime;
269
+            $this->logger->debug('Garbage collector of expired session. maxLifetime [' . $maxLifetime . '] sec, expired time [' . $time . ']');
270
+            $instance->deleteByTime($time);
271
+            return true;
272
+        }
273
+
274
+        /**
275
+         * Encode the session data using the openssl
276
+         * @param  mixed $data the session data to encode
277
+         * @return mixed the encoded session data
278
+         */
279
+        public function encode($data){
280
+            $key = base64_decode($this->sessionSecret);
281
+            $dataEncrypted = openssl_encrypt($data , self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
282
+            $output = base64_encode($dataEncrypted);
283
+            return $output;
284
+        }
285
+
286
+
287
+        /**
288
+         * Decode the session data using the openssl
289
+         * @param  mixed $data the data to decode
290
+         * @return mixed       the decoded data
291
+         */
292
+        public function decode($data){
293
+            $key = base64_decode($this->sessionSecret);
294
+            $data = base64_decode($data);
295
+            $data = openssl_decrypt($data, self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
296
+            return $data;
297
+        }
298 298
 
299 299
 		
300
-		/**
300
+        /**
301 301
          * Return the loader instance
302 302
          * @return object Loader the loader instance
303 303
          */
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
          * set the loader instance for future use
310 310
          * @param object Loader $loader the loader object
311 311
          */
312
-         public function setLoader($loader){
312
+            public function setLoader($loader){
313 313
             $this->loader = $loader;
314 314
             return $this;
315 315
         }
@@ -326,27 +326,27 @@  discard block
 block discarded – undo
326 326
          * set the model instance for future use
327 327
          * @param DBSessionHandlerModel $modelInstance the model object
328 328
          */
329
-         public function setModelInstance(DBSessionHandlerModel $modelInstance){
329
+            public function setModelInstance(DBSessionHandlerModel $modelInstance){
330 330
             $this->modelInstance = $modelInstance;
331 331
             return $this;
332 332
         }
333 333
 
334
-	    /**
335
-	     * Set the model instance using the configuration for session
336
-	     */
337
-	    protected function setModelInstanceFromSessionConfig(){
338
-	    	$modelName = get_config('session_save_path');
339
-			$this->logger->info('The database session model: ' . $modelName);
340
-			$this->loader->model($modelName, 'dbsessionhandlerinstance'); 
341
-			//@codeCoverageIgnoreStart
334
+        /**
335
+         * Set the model instance using the configuration for session
336
+         */
337
+        protected function setModelInstanceFromSessionConfig(){
338
+            $modelName = get_config('session_save_path');
339
+            $this->logger->info('The database session model: ' . $modelName);
340
+            $this->loader->model($modelName, 'dbsessionhandlerinstance'); 
341
+            //@codeCoverageIgnoreStart
342 342
             if (isset($this->OBJ->dbsessionhandlerinstance) 
343
-            	&& ! ($this->OBJ->dbsessionhandlerinstance instanceof DBSessionHandlerModel)
343
+                && ! ($this->OBJ->dbsessionhandlerinstance instanceof DBSessionHandlerModel)
344 344
             ) {
345
-				show_error('To use database session handler, your class model "' . get_class($this->OBJ->dbsessionhandlerinstance) . '" need extends "DBSessionHandlerModel"');
346
-			}  
347
-			//@codeCoverageIgnoreEnd
345
+                show_error('To use database session handler, your class model "' . get_class($this->OBJ->dbsessionhandlerinstance) . '" need extends "DBSessionHandlerModel"');
346
+            }  
347
+            //@codeCoverageIgnoreEnd
348 348
 			
349
-			//set model instance
350
-			$this->modelInstance = $this->OBJ->dbsessionhandlerinstance;
351
-	    }
352
-	}
349
+            //set model instance
350
+            $this->modelInstance = $this->OBJ->dbsessionhandlerinstance;
351
+        }
352
+    }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -27,11 +27,11 @@  discard block
 block discarded – undo
27 27
 	/**
28 28
 	 * check if the interface "SessionHandlerInterface" exists (normally in PHP 5.4 this already exists)
29 29
 	 */
30
-	if ( !interface_exists('SessionHandlerInterface')){
30
+	if (!interface_exists('SessionHandlerInterface')) {
31 31
 		show_error('"SessionHandlerInterface" interface does not exists or is disabled can not use it to handler database session.');
32 32
 	}
33 33
 
34
-	class DBSessionHandler extends BaseClass implements SessionHandlerInterface{
34
+	class DBSessionHandler extends BaseClass implements SessionHandlerInterface {
35 35
 		
36 36
 		/**
37 37
 		 * The encryption method to use to encrypt session data in database
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
          * Create new instance of Database session handler
80 80
          * @param object $modelInstance the model instance
81 81
          */
82
-		public function __construct(DBSessionHandlerModel $modelInstance = null){
82
+		public function __construct(DBSessionHandlerModel $modelInstance = null) {
83 83
 			parent::__construct();
84 84
 			
85 85
 	    	//Set Loader instance to use
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	       
88 88
 		    $this->OBJ = & get_instance();
89 89
 		    
90
-			if (is_object($modelInstance)){
90
+			if (is_object($modelInstance)) {
91 91
 				$this->setModelInstance($modelInstance);
92 92
 			}
93 93
 		}
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 		 * Set the session secret used to encrypt the data in database 
97 97
 		 * @param string $secret the base64 string secret
98 98
 		 */
99
-		public function setSessionSecret($secret){
99
+		public function setSessionSecret($secret) {
100 100
 			$this->sessionSecret = $secret;
101 101
 			return $this;
102 102
 		}
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 		 * Return the session secret
106 106
 		 * @return string 
107 107
 		 */
108
-		public function getSessionSecret(){
108
+		public function getSessionSecret() {
109 109
 			return $this->sessionSecret;
110 110
 		}
111 111
 
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 		 * Set the initializer vector for openssl 
115 115
 		 * @param string $key the session secret used in base64 format
116 116
 		 */
117
-		public function setInitializerVector($key){
117
+		public function setInitializerVector($key) {
118 118
 			$ivLength = openssl_cipher_iv_length(self::DB_SESSION_HASH_METHOD);
119 119
 			$key = base64_decode($key);
120 120
 			$this->iv = substr(hash('sha256', $key), 0, $ivLength);
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		 * Return the initializer vector
126 126
 		 * @return string 
127 127
 		 */
128
-		public function getInitializerVector(){
128
+		public function getInitializerVector() {
129 129
 			return $this->iv;
130 130
 		}
131 131
 
@@ -135,17 +135,17 @@  discard block
 block discarded – undo
135 135
 		 * @param  string $sessionName the session name
136 136
 		 * @return boolean 
137 137
 		 */
138
-		public function open($savePath, $sessionName){
138
+		public function open($savePath, $sessionName) {
139 139
 			$this->logger->debug('Opening database session handler for [' . $sessionName . ']');
140 140
 			//try to check if session secret is set before
141 141
 			$secret = $this->getSessionSecret();
142
-			if (empty($secret)){
142
+			if (empty($secret)) {
143 143
 				$secret = get_config('session_secret', null);
144 144
 				$this->setSessionSecret($secret);
145 145
 			}
146 146
 			$this->logger->info('Session secret: ' . $secret);
147 147
 
148
-			if (! is_object($this->modelInstance)){
148
+			if (!is_object($this->modelInstance)) {
149 149
 				$this->setModelInstanceFromSessionConfig();
150 150
 			}
151 151
 			$this->setInitializerVector($secret);
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 			//set session tables columns
154 154
 			$this->sessionTableColumns = $this->modelInstance->getSessionTableColumns();
155 155
 
156
-			if (empty($this->sessionTableColumns)){
156
+			if (empty($this->sessionTableColumns)) {
157 157
 				show_error('The session handler is "database" but the table columns not set');
158 158
 			}
159 159
 			$this->logger->info('Database session, the model columns are listed below: ' . stringfy_vars($this->sessionTableColumns));
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 		 * Close the session
170 170
 		 * @return boolean
171 171
 		 */
172
-		public function close(){
172
+		public function close() {
173 173
 			$this->logger->debug('Closing database session handler');
174 174
 			return true;
175 175
 		}
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 		 * @param  string $sid the session id to use
180 180
 		 * @return string      the session data in serialiaze format
181 181
 		 */
182
-		public function read($sid){
182
+		public function read($sid) {
183 183
 			$this->logger->debug('Reading database session data for SID: ' . $sid);
184 184
 			$instance = $this->getModelInstance();
185 185
 			$columns = $this->sessionTableColumns;
@@ -188,13 +188,13 @@  discard block
 block discarded – undo
188 188
 			
189 189
 			$ip = get_ip();
190 190
 			$host = @gethostbyaddr($ip) or null;
191
-			$browser = $this->OBJ->browser->getPlatform().', '.$this->OBJ->browser->getBrowser().' '.$this->OBJ->browser->getVersion();
191
+			$browser = $this->OBJ->browser->getPlatform() . ', ' . $this->OBJ->browser->getBrowser() . ' ' . $this->OBJ->browser->getVersion();
192 192
 			
193 193
 			$data = $instance->get_by(array($columns['sid'] => $sid, $columns['shost'] => $host, $columns['sbrowser'] => $browser));
194
-			if ($data && isset($data->{$columns['sdata']})){
194
+			if ($data && isset($data->{$columns['sdata']})) {
195 195
 				//checking inactivity 
196 196
 				$timeInactivity = time() - get_config('session_inactivity_time', 100);
197
-				if ($data->{$columns['stime']} < $timeInactivity){
197
+				if ($data->{$columns['stime']} < $timeInactivity) {
198 198
 					$this->logger->info('Database session data for SID: ' . $sid . ' already expired, destroy it');
199 199
 					$this->destroy($sid);
200 200
 					return null;
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 		 * @param  mixed $data the session data to save in serialize format
212 212
 		 * @return boolean 
213 213
 		 */
214
-		public function write($sid, $data){
214
+		public function write($sid, $data) {
215 215
 			$this->logger->debug('Saving database session data for SID: ' . $sid . ', data: ' . stringfy_vars($data));
216 216
 			$instance = $this->getModelInstance();
217 217
 			$columns = $this->sessionTableColumns;
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 			$ip = get_ip();
223 223
 			$keyValue = $instance->getKeyValue();
224 224
 			$host = @gethostbyaddr($ip) or null;
225
-			$browser = $this->OBJ->browser->getPlatform().', '.$this->OBJ->browser->getBrowser().' '.$this->OBJ->browser->getVersion();
225
+			$browser = $this->OBJ->browser->getPlatform() . ', ' . $this->OBJ->browser->getBrowser() . ' ' . $this->OBJ->browser->getVersion();
226 226
 			$data = $this->encode($data);
227 227
 			$params = array(
228 228
 							$columns['sid'] => $sid,
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 						);
236 236
 			$this->logger->info('Database session data to save are listed below :' . stringfy_vars($params));
237 237
 			$exists = $instance->get($sid);
238
-			if ($exists){
238
+			if ($exists) {
239 239
 				$this->logger->info('Session data for SID: ' . $sid . ' already exists, just update it');
240 240
 				//update
241 241
 				unset($params[$columns['sid']]);
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 		 * @param  string $sid the session id value
252 252
 		 * @return boolean
253 253
 		 */
254
-		public function destroy($sid){
254
+		public function destroy($sid) {
255 255
 			$this->logger->debug('Destroy of session data for SID: ' . $sid);
256 256
 			$instance = $this->modelInstance;
257 257
 			$instance->delete($sid);
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 		 * @param  integer $maxLifetime the max lifetime
264 264
 		 * @return boolean
265 265
 		 */
266
-		public function gc($maxLifetime){
266
+		public function gc($maxLifetime) {
267 267
 			$instance = $this->modelInstance;
268 268
 			$time = time() - $maxLifetime;
269 269
 			$this->logger->debug('Garbage collector of expired session. maxLifetime [' . $maxLifetime . '] sec, expired time [' . $time . ']');
@@ -276,9 +276,9 @@  discard block
 block discarded – undo
276 276
 		 * @param  mixed $data the session data to encode
277 277
 		 * @return mixed the encoded session data
278 278
 		 */
279
-		public function encode($data){
279
+		public function encode($data) {
280 280
 			$key = base64_decode($this->sessionSecret);
281
-			$dataEncrypted = openssl_encrypt($data , self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
281
+			$dataEncrypted = openssl_encrypt($data, self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
282 282
 			$output = base64_encode($dataEncrypted);
283 283
 			return $output;
284 284
 		}
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 		 * @param  mixed $data the data to decode
290 290
 		 * @return mixed       the decoded data
291 291
 		 */
292
-		public function decode($data){
292
+		public function decode($data) {
293 293
 			$key = base64_decode($this->sessionSecret);
294 294
 			$data = base64_decode($data);
295 295
 			$data = openssl_decrypt($data, self::DB_SESSION_HASH_METHOD, $key, OPENSSL_RAW_DATA, $this->getInitializerVector());
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
          * Return the loader instance
302 302
          * @return object Loader the loader instance
303 303
          */
304
-        public function getLoader(){
304
+        public function getLoader() {
305 305
             return $this->loader;
306 306
         }
307 307
 
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
          * set the loader instance for future use
310 310
          * @param object Loader $loader the loader object
311 311
          */
312
-         public function setLoader($loader){
312
+         public function setLoader($loader) {
313 313
             $this->loader = $loader;
314 314
             return $this;
315 315
         }
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
          * Return the model instance
319 319
          * @return object DBSessionHandlerModel the model instance
320 320
          */
321
-        public function getModelInstance(){
321
+        public function getModelInstance() {
322 322
             return $this->modelInstance;
323 323
         }
324 324
 
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
          * set the model instance for future use
327 327
          * @param DBSessionHandlerModel $modelInstance the model object
328 328
          */
329
-         public function setModelInstance(DBSessionHandlerModel $modelInstance){
329
+         public function setModelInstance(DBSessionHandlerModel $modelInstance) {
330 330
             $this->modelInstance = $modelInstance;
331 331
             return $this;
332 332
         }
@@ -334,13 +334,13 @@  discard block
 block discarded – undo
334 334
 	    /**
335 335
 	     * Set the model instance using the configuration for session
336 336
 	     */
337
-	    protected function setModelInstanceFromSessionConfig(){
337
+	    protected function setModelInstanceFromSessionConfig() {
338 338
 	    	$modelName = get_config('session_save_path');
339 339
 			$this->logger->info('The database session model: ' . $modelName);
340 340
 			$this->loader->model($modelName, 'dbsessionhandlerinstance'); 
341 341
 			//@codeCoverageIgnoreStart
342 342
             if (isset($this->OBJ->dbsessionhandlerinstance) 
343
-            	&& ! ($this->OBJ->dbsessionhandlerinstance instanceof DBSessionHandlerModel)
343
+            	&& !($this->OBJ->dbsessionhandlerinstance instanceof DBSessionHandlerModel)
344 344
             ) {
345 345
 				show_error('To use database session handler, your class model "' . get_class($this->OBJ->dbsessionhandlerinstance) . '" need extends "DBSessionHandlerModel"');
346 346
 			}  
Please login to merge, or discard this patch.
core/classes/Router.php 3 patches
Indentation   +572 added lines, -572 removed lines patch added patch discarded remove patch
@@ -1,586 +1,586 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
26
-
27
-	class Router extends BaseClass{
28
-		/**
29
-		* @var array $pattern: The list of URIs to validate against
30
-		*/
31
-		private $pattern = array();
32
-
33
-		/**
34
-		* @var array $callback: The list of callback to call
35
-		*/
36
-		private $callback = array();
37
-
38
-		/**
39
-		* @var string $uriTrim: The char to remove from the URIs
40
-		*/
41
-		protected $uriTrim = '/\^$';
42
-
43
-		/**
44
-		* @var string $uri: The route URI to use
45
-		*/
46
-		protected $uri = '';
47
-
48
-		/**
49
-		 * The module name of the current request
50
-		 * @var string
51
-		 */
52
-		protected $module = null;
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+
27
+    class Router extends BaseClass{
28
+        /**
29
+         * @var array $pattern: The list of URIs to validate against
30
+         */
31
+        private $pattern = array();
32
+
33
+        /**
34
+         * @var array $callback: The list of callback to call
35
+         */
36
+        private $callback = array();
37
+
38
+        /**
39
+         * @var string $uriTrim: The char to remove from the URIs
40
+         */
41
+        protected $uriTrim = '/\^$';
42
+
43
+        /**
44
+         * @var string $uri: The route URI to use
45
+         */
46
+        protected $uri = '';
47
+
48
+        /**
49
+         * The module name of the current request
50
+         * @var string
51
+         */
52
+        protected $module = null;
53 53
 		
54
-		/**
55
-		 * The controller name of the current request
56
-		 * @var string
57
-		 */
58
-		protected $controller = null;
59
-
60
-		/**
61
-		 * The controller path
62
-		 * @var string
63
-		 */
64
-		protected $controllerPath = null;
65
-
66
-		/**
67
-		 * The method name. The default value is "index"
68
-		 * @var string
69
-		 */
70
-		protected $method = 'index';
71
-
72
-		/**
73
-		 * List of argument to pass to the method
74
-		 * @var array
75
-		 */
76
-		protected $args = array();
77
-
78
-		/**
79
-		 * List of routes configurations
80
-		 * @var array
81
-		 */
82
-		protected $routes = array();
83
-
84
-		/**
85
-		 * The segments array for the current request
86
-		 * @var array
87
-		 */
88
-		protected $segments = array();
89
-
90
-		/**
91
-		 * Construct the new Router instance
92
-		 */
93
-		public function __construct(){
94
-			parent::__construct();
54
+        /**
55
+         * The controller name of the current request
56
+         * @var string
57
+         */
58
+        protected $controller = null;
59
+
60
+        /**
61
+         * The controller path
62
+         * @var string
63
+         */
64
+        protected $controllerPath = null;
65
+
66
+        /**
67
+         * The method name. The default value is "index"
68
+         * @var string
69
+         */
70
+        protected $method = 'index';
71
+
72
+        /**
73
+         * List of argument to pass to the method
74
+         * @var array
75
+         */
76
+        protected $args = array();
77
+
78
+        /**
79
+         * List of routes configurations
80
+         * @var array
81
+         */
82
+        protected $routes = array();
83
+
84
+        /**
85
+         * The segments array for the current request
86
+         * @var array
87
+         */
88
+        protected $segments = array();
89
+
90
+        /**
91
+         * Construct the new Router instance
92
+         */
93
+        public function __construct(){
94
+            parent::__construct();
95 95
 			
96
-			//loading routes for module
97
-			$moduleRouteList = array();
98
-			$modulesRoutes = Module::getModulesRoutesConfig();
99
-			if($modulesRoutes && is_array($modulesRoutes)){
100
-				$moduleRouteList = $modulesRoutes;
101
-				unset($modulesRoutes);
102
-			}
103
-			$this->setRouteConfiguration($moduleRouteList);
104
-			$this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
105
-
106
-			//Set route informations
107
-			$this->setRouteConfigurationInfos();
108
-		}
109
-
110
-		/**
111
-		 * Get the route patterns
112
-		 * @return array
113
-		 */
114
-		public function getPattern(){
115
-			return $this->pattern;
116
-		}
117
-
118
-		/**
119
-		 * Get the route callbacks
120
-		 * @return array
121
-		 */
122
-		public function getCallback(){
123
-			return $this->callback;
124
-		}
125
-
126
-	    /**
127
-		 * Get the module name
128
-		 * @return string
129
-		 */
130
-		public function getModule(){
131
-			return $this->module;
132
-		}
96
+            //loading routes for module
97
+            $moduleRouteList = array();
98
+            $modulesRoutes = Module::getModulesRoutesConfig();
99
+            if($modulesRoutes && is_array($modulesRoutes)){
100
+                $moduleRouteList = $modulesRoutes;
101
+                unset($modulesRoutes);
102
+            }
103
+            $this->setRouteConfiguration($moduleRouteList);
104
+            $this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
105
+
106
+            //Set route informations
107
+            $this->setRouteConfigurationInfos();
108
+        }
109
+
110
+        /**
111
+         * Get the route patterns
112
+         * @return array
113
+         */
114
+        public function getPattern(){
115
+            return $this->pattern;
116
+        }
117
+
118
+        /**
119
+         * Get the route callbacks
120
+         * @return array
121
+         */
122
+        public function getCallback(){
123
+            return $this->callback;
124
+        }
125
+
126
+        /**
127
+         * Get the module name
128
+         * @return string
129
+         */
130
+        public function getModule(){
131
+            return $this->module;
132
+        }
133 133
 		
134
-		/**
135
-		 * Get the controller name
136
-		 * @return string
137
-		 */
138
-		public function getController(){
139
-			return $this->controller;
140
-		}
141
-
142
-		/**
143
-		 * Get the controller file path
144
-		 * @return string
145
-		 */
146
-		public function getControllerPath(){
147
-			return $this->controllerPath;
148
-		}
149
-
150
-		/**
151
-		 * Get the controller method
152
-		 * @return string
153
-		 */
154
-		public function getMethod(){
155
-			return $this->method;
156
-		}
157
-
158
-		/**
159
-		 * Get the request arguments
160
-		 * @return array
161
-		 */
162
-		public function getArgs(){
163
-			return $this->args;
164
-		}
165
-
166
-		/**
167
-		 * Get the URL segments array
168
-		 * @return array
169
-		 */
170
-		public function getSegments(){
171
-			return $this->segments;
172
-		}
173
-
174
-	    /**
175
-		 * Get the route URI
176
-		 * @return string
177
-		 */
178
-		public function getRouteUri(){
179
-			return $this->uri;
180
-		}
181
-
182
-		/**
183
-		* Add the URI and callback to the list of URIs to validate
184
-		*
185
-		* @param string $uri the request URI
186
-		* @param string $callback the callback function
187
-		*
188
-		* @return object the current instance
189
-		*/
190
-		public function add($uri, $callback) {
191
-			$uri = trim($uri, $this->uriTrim);
192
-			if(in_array($uri, $this->pattern)){
193
-				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
194
-			}
195
-			$this->pattern[] = $uri;
196
-			$this->callback[] = $callback;
197
-			return $this;
198
-		}
199
-
200
-		/**
201
-		* Remove the route configuration
202
-		*
203
-		* @param string $uri the URI
204
-		*
205
-		* @return object the current instance
206
-		*/
207
-		public function removeRoute($uri) {
208
-			$index  = array_search($uri, $this->pattern, true);
209
-			if($index !== false){
210
-				$this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
211
-				unset($this->pattern[$index]);
212
-				unset($this->callback[$index]);
213
-			}
214
-			return $this;
215
-		}
216
-
217
-
218
-		/**
219
-		* Remove all the routes from the configuration
220
-		*
221
-		* @return object the current instance
222
-		*/
223
-		public function removeAllRoute() {
224
-			$this->logger->info('Remove all routes from the configuration');
225
-			$this->pattern  = array();
226
-			$this->callback = array();
227
-			$this->routes = array();
228
-			return $this;
229
-		}
230
-
231
-
232
-		/**
233
-	     * Set the route URI to use later
234
-	     * @param string $uri the route URI, if is empty will determine automatically
235
-	     * @return object
236
-	     */
237
-	    public function setRouteUri($uri = ''){
238
-	    	$routeUri = '';
239
-	    	if(! empty($uri)){
240
-	    		$routeUri = $uri;
241
-	    	}
242
-	    	//if the application is running in CLI mode use the first argument
243
-			else if(IS_CLI && isset($_SERVER['argv'][1])){
244
-				$routeUri = $_SERVER['argv'][1];
245
-			}
246
-			else if(isset($_SERVER['REQUEST_URI'])){
247
-				$routeUri = $_SERVER['REQUEST_URI'];
248
-			}
249
-			$this->logger->debug('Check if URL suffix is enabled in the configuration');
250
-			//remove url suffix from the request URI
251
-			$suffix = get_config('url_suffix');
252
-			if ($suffix) {
253
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
254
-				$routeUri = str_ireplace($suffix, '', $routeUri);
255
-			} 
256
-			if (strpos($routeUri, '?') !== false){
257
-				$routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
258
-			}
259
-			$this->uri = trim($routeUri, $this->uriTrim);
260
-			return $this;
261
-	    }
262
-
263
-	     /**
264
-		 * Set the route segments informations
265
-		 * @param array $segements the route segments information
266
-		 * 
267
-		 * @return object
268
-		 */
269
-		public function setRouteSegments(array $segments = array()){
270
-			if(! empty($segments)){
271
-				$this->segments = $segments;
272
-			} else if (!empty($this->uri)) {
273
-				$this->segments = explode('/', $this->uri);
274
-			}
275
-			$segment = $this->segments;
276
-			$baseUrl = get_config('base_url');
277
-			//check if the app is not in DOCUMENT_ROOT
278
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
279
-				array_shift($segment);
280
-				$this->segments = $segment;
281
-			}
282
-			$this->logger->debug('Check if the request URI contains the front controller');
283
-			if(isset($segment[0]) && $segment[0] == SELF){
284
-				$this->logger->info('The request URI contains the front controller');
285
-				array_shift($segment);
286
-				$this->segments = $segment;
287
-			}
288
-			return $this;
289
-		}
290
-
291
-		/**
292
-		 * Setting the route parameters like module, controller, method, argument
293
-		 * @return object the current instance
294
-		 */
295
-		public function determineRouteParamsInformation() {
296
-			$this->logger->debug('Routing process start ...');
134
+        /**
135
+         * Get the controller name
136
+         * @return string
137
+         */
138
+        public function getController(){
139
+            return $this->controller;
140
+        }
141
+
142
+        /**
143
+         * Get the controller file path
144
+         * @return string
145
+         */
146
+        public function getControllerPath(){
147
+            return $this->controllerPath;
148
+        }
149
+
150
+        /**
151
+         * Get the controller method
152
+         * @return string
153
+         */
154
+        public function getMethod(){
155
+            return $this->method;
156
+        }
157
+
158
+        /**
159
+         * Get the request arguments
160
+         * @return array
161
+         */
162
+        public function getArgs(){
163
+            return $this->args;
164
+        }
165
+
166
+        /**
167
+         * Get the URL segments array
168
+         * @return array
169
+         */
170
+        public function getSegments(){
171
+            return $this->segments;
172
+        }
173
+
174
+        /**
175
+         * Get the route URI
176
+         * @return string
177
+         */
178
+        public function getRouteUri(){
179
+            return $this->uri;
180
+        }
181
+
182
+        /**
183
+         * Add the URI and callback to the list of URIs to validate
184
+         *
185
+         * @param string $uri the request URI
186
+         * @param string $callback the callback function
187
+         *
188
+         * @return object the current instance
189
+         */
190
+        public function add($uri, $callback) {
191
+            $uri = trim($uri, $this->uriTrim);
192
+            if(in_array($uri, $this->pattern)){
193
+                $this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
194
+            }
195
+            $this->pattern[] = $uri;
196
+            $this->callback[] = $callback;
197
+            return $this;
198
+        }
199
+
200
+        /**
201
+         * Remove the route configuration
202
+         *
203
+         * @param string $uri the URI
204
+         *
205
+         * @return object the current instance
206
+         */
207
+        public function removeRoute($uri) {
208
+            $index  = array_search($uri, $this->pattern, true);
209
+            if($index !== false){
210
+                $this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
211
+                unset($this->pattern[$index]);
212
+                unset($this->callback[$index]);
213
+            }
214
+            return $this;
215
+        }
216
+
217
+
218
+        /**
219
+         * Remove all the routes from the configuration
220
+         *
221
+         * @return object the current instance
222
+         */
223
+        public function removeAllRoute() {
224
+            $this->logger->info('Remove all routes from the configuration');
225
+            $this->pattern  = array();
226
+            $this->callback = array();
227
+            $this->routes = array();
228
+            return $this;
229
+        }
230
+
231
+
232
+        /**
233
+         * Set the route URI to use later
234
+         * @param string $uri the route URI, if is empty will determine automatically
235
+         * @return object
236
+         */
237
+        public function setRouteUri($uri = ''){
238
+            $routeUri = '';
239
+            if(! empty($uri)){
240
+                $routeUri = $uri;
241
+            }
242
+            //if the application is running in CLI mode use the first argument
243
+            else if(IS_CLI && isset($_SERVER['argv'][1])){
244
+                $routeUri = $_SERVER['argv'][1];
245
+            }
246
+            else if(isset($_SERVER['REQUEST_URI'])){
247
+                $routeUri = $_SERVER['REQUEST_URI'];
248
+            }
249
+            $this->logger->debug('Check if URL suffix is enabled in the configuration');
250
+            //remove url suffix from the request URI
251
+            $suffix = get_config('url_suffix');
252
+            if ($suffix) {
253
+                $this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
254
+                $routeUri = str_ireplace($suffix, '', $routeUri);
255
+            } 
256
+            if (strpos($routeUri, '?') !== false){
257
+                $routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
258
+            }
259
+            $this->uri = trim($routeUri, $this->uriTrim);
260
+            return $this;
261
+        }
262
+
263
+            /**
264
+             * Set the route segments informations
265
+             * @param array $segements the route segments information
266
+             * 
267
+             * @return object
268
+             */
269
+        public function setRouteSegments(array $segments = array()){
270
+            if(! empty($segments)){
271
+                $this->segments = $segments;
272
+            } else if (!empty($this->uri)) {
273
+                $this->segments = explode('/', $this->uri);
274
+            }
275
+            $segment = $this->segments;
276
+            $baseUrl = get_config('base_url');
277
+            //check if the app is not in DOCUMENT_ROOT
278
+            if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
279
+                array_shift($segment);
280
+                $this->segments = $segment;
281
+            }
282
+            $this->logger->debug('Check if the request URI contains the front controller');
283
+            if(isset($segment[0]) && $segment[0] == SELF){
284
+                $this->logger->info('The request URI contains the front controller');
285
+                array_shift($segment);
286
+                $this->segments = $segment;
287
+            }
288
+            return $this;
289
+        }
290
+
291
+        /**
292
+         * Setting the route parameters like module, controller, method, argument
293
+         * @return object the current instance
294
+         */
295
+        public function determineRouteParamsInformation() {
296
+            $this->logger->debug('Routing process start ...');
297 297
 			
298
-			//determine route parameters using the config
299
-			$this->determineRouteParamsFromConfig();
298
+            //determine route parameters using the config
299
+            $this->determineRouteParamsFromConfig();
300 300
 			
301
-			//if can not determine the module/controller/method via the defined routes configuration we will use
302
-			//the URL like http://domain.com/module/controller/method/arg1/arg2
303
-			if(! $this->controller){
304
-				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
305
-				//determine route parameters using the REQUEST_URI param
306
-				$this->determineRouteParamsFromRequestUri();
307
-			}
308
-			//Set the controller file path if not yet set
309
-			$this->setControllerFilePath();
310
-			$this->logger->debug('Routing process end.');
311
-
312
-			return $this;
313
-		}
301
+            //if can not determine the module/controller/method via the defined routes configuration we will use
302
+            //the URL like http://domain.com/module/controller/method/arg1/arg2
303
+            if(! $this->controller){
304
+                $this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
305
+                //determine route parameters using the REQUEST_URI param
306
+                $this->determineRouteParamsFromRequestUri();
307
+            }
308
+            //Set the controller file path if not yet set
309
+            $this->setControllerFilePath();
310
+            $this->logger->debug('Routing process end.');
311
+
312
+            return $this;
313
+        }
314 314
 	
315
-		 /**
316
-		 * Routing the request to the correspondant module/controller/method if exists
317
-		 * otherwise send 404 error.
318
-		 */
319
-	    public function processRequest(){
320
-	    	//Setting the route URI
321
-			$this->setRouteUri();
322
-
323
-			//setting route segments
324
-			$this->setRouteSegments();
325
-
326
-			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
327
-
328
-	    	//determine the route parameters information
329
-	    	$this->determineRouteParamsInformation();
330
-
331
-	    	$e404 = false;
332
-	    	$classFilePath = $this->controllerPath;
333
-	    	$controller = ucfirst($this->controller);
334
-	    	$this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
335
-	    	$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
315
+            /**
316
+             * Routing the request to the correspondant module/controller/method if exists
317
+             * otherwise send 404 error.
318
+             */
319
+        public function processRequest(){
320
+            //Setting the route URI
321
+            $this->setRouteUri();
322
+
323
+            //setting route segments
324
+            $this->setRouteSegments();
325
+
326
+            $this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
327
+
328
+            //determine the route parameters information
329
+            $this->determineRouteParamsInformation();
330
+
331
+            $e404 = false;
332
+            $classFilePath = $this->controllerPath;
333
+            $controller = ucfirst($this->controller);
334
+            $this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
335
+            $this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
336 336
 	    	
337
-			if(file_exists($classFilePath)){
338
-				require_once $classFilePath;
339
-				if(! class_exists($controller, false)){
340
-					$e404 = true;
341
-					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
342
-				}
343
-				else{
344
-					$controllerInstance = new $controller();
345
-					$controllerMethod = $this->getMethod();
346
-					if(! method_exists($controllerInstance, $controllerMethod)){
347
-						$e404 = true;
348
-						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
349
-					}
350
-					else{
351
-						$this->logger->info('Routing data is set correctly now GO!');
352
-						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
353
-						//render the final page to user
354
-						$this->logger->info('Render the final output to the browser');
355
-						get_instance()->response->renderFinalPage();
356
-					}
357
-				}
358
-			}
359
-			else{
360
-				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
361
-				$e404 = true;
362
-			}
363
-			if($e404){
364
-				if(IS_CLI){
365
-					set_http_status_header(404);
366
-					echo 'Error 404: page not found.';
367
-				} else {
368
-					$response =& class_loader('Response', 'classes');
369
-					$response->send404();
370
-				}
371
-			}
372
-	    }
373
-
374
-
375
-	    /**
376
-	    * Setting the route configuration using the configuration file and additional configuration from param
377
-	    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
378
-	    * @param boolean $useConfigFile whether to use route configuration file
379
-		* @return object
380
-	    */
381
-	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
382
-	        $route = array();
383
-	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
384
-	            require_once CONFIG_PATH . 'routes.php';
385
-	        }
386
-	        $route = array_merge($route, $overwriteConfig);
387
-	        $this->routes = $route;
388
-	        //if route is empty remove all configuration
389
-	        if(empty($route)){
390
-	        	$this->removeAllRoute();
391
-	        }
392
-			return $this;
393
-	    }
394
-
395
-	     /**
396
-		 * Get the route configuration
397
-		 * @return array
398
-		 */
399
-		public function getRouteConfiguration(){
400
-			return $this->routes;
401
-		}
337
+            if(file_exists($classFilePath)){
338
+                require_once $classFilePath;
339
+                if(! class_exists($controller, false)){
340
+                    $e404 = true;
341
+                    $this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
342
+                }
343
+                else{
344
+                    $controllerInstance = new $controller();
345
+                    $controllerMethod = $this->getMethod();
346
+                    if(! method_exists($controllerInstance, $controllerMethod)){
347
+                        $e404 = true;
348
+                        $this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
349
+                    }
350
+                    else{
351
+                        $this->logger->info('Routing data is set correctly now GO!');
352
+                        call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
353
+                        //render the final page to user
354
+                        $this->logger->info('Render the final output to the browser');
355
+                        get_instance()->response->renderFinalPage();
356
+                    }
357
+                }
358
+            }
359
+            else{
360
+                $this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
361
+                $e404 = true;
362
+            }
363
+            if($e404){
364
+                if(IS_CLI){
365
+                    set_http_status_header(404);
366
+                    echo 'Error 404: page not found.';
367
+                } else {
368
+                    $response =& class_loader('Response', 'classes');
369
+                    $response->send404();
370
+                }
371
+            }
372
+        }
373
+
374
+
375
+        /**
376
+         * Setting the route configuration using the configuration file and additional configuration from param
377
+         * @param array $overwriteConfig the additional configuration to overwrite with the existing one
378
+         * @param boolean $useConfigFile whether to use route configuration file
379
+         * @return object
380
+         */
381
+        public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
382
+            $route = array();
383
+            if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
384
+                require_once CONFIG_PATH . 'routes.php';
385
+            }
386
+            $route = array_merge($route, $overwriteConfig);
387
+            $this->routes = $route;
388
+            //if route is empty remove all configuration
389
+            if(empty($route)){
390
+                $this->removeAllRoute();
391
+            }
392
+            return $this;
393
+        }
394
+
395
+            /**
396
+             * Get the route configuration
397
+             * @return array
398
+             */
399
+        public function getRouteConfiguration(){
400
+            return $this->routes;
401
+        }
402 402
 
403 403
 	    
404
-	    /**
405
-	     * Set the controller file path if is not set
406
-	     * @param string $path the file path if is null will using the route 
407
-	     * information
408
-	     *
409
-	     * @return object the current instance
410
-	     */
411
-	    public function setControllerFilePath($path = null){
412
-	    	if($path !== null){
413
-	    		$this->controllerPath = $path;
414
-	    		return $this;
415
-	    	}
416
-	    	//did we set the controller, so set the controller path
417
-			if($this->controller && ! $this->controllerPath){
418
-				$this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
419
-				$controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
420
-				//if the controller is in module
421
-				if($this->module){
422
-					$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
423
-					if($path !== false){
424
-						$controllerPath = $path;
425
-					}
426
-				}
427
-				$this->controllerPath = $controllerPath;
428
-			}
429
-			return $this;
430
-	    }
431
-
432
-	    /**
433
-	     * Determine the route parameters from route configuration
434
-	     * @return void
435
-	     */
436
-	    protected function determineRouteParamsFromConfig(){
437
-	    	$uri = implode('/', $this->segments);
438
-	    	/*
404
+        /**
405
+         * Set the controller file path if is not set
406
+         * @param string $path the file path if is null will using the route 
407
+         * information
408
+         *
409
+         * @return object the current instance
410
+         */
411
+        public function setControllerFilePath($path = null){
412
+            if($path !== null){
413
+                $this->controllerPath = $path;
414
+                return $this;
415
+            }
416
+            //did we set the controller, so set the controller path
417
+            if($this->controller && ! $this->controllerPath){
418
+                $this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
419
+                $controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
420
+                //if the controller is in module
421
+                if($this->module){
422
+                    $path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
423
+                    if($path !== false){
424
+                        $controllerPath = $path;
425
+                    }
426
+                }
427
+                $this->controllerPath = $controllerPath;
428
+            }
429
+            return $this;
430
+        }
431
+
432
+        /**
433
+         * Determine the route parameters from route configuration
434
+         * @return void
435
+         */
436
+        protected function determineRouteParamsFromConfig(){
437
+            $uri = implode('/', $this->segments);
438
+            /*
439 439
 	   		* Generics routes patterns
440 440
 	    	*/
441
-			$pattern = array(':num', ':alpha', ':alnum', ':any');
442
-			$replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
443
-
444
-			$this->logger->debug(
445
-									'Begin to loop in the predefined routes configuration ' 
446
-									. 'to check if the current request match'
447
-									);
448
-
449
-			// Cycle through the URIs stored in the array
450
-			foreach ($this->pattern as $index => $uriList) {
451
-				$uriList = str_ireplace($pattern, $replace, $uriList);
452
-				// Check for an existant matching URI
453
-				if (preg_match("#^$uriList$#", $uri, $args)) {
454
-					$this->logger->info(
455
-										'Route found for request URI [' . $uri . '] using the predefined configuration '
456
-										. ' [' . $this->pattern[$index] . '] --> [' . $this->callback[$index] . ']'
457
-									);
458
-					array_shift($args);
459
-					//check if this contains an module
460
-					$moduleControllerMethod = explode('#', $this->callback[$index]);
461
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
462
-						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
463
-						$this->module = $moduleControllerMethod[0];
464
-						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
465
-					}
466
-					else{
467
-						$this->logger->info('The current request does not use the module');
468
-						$moduleControllerMethod = explode('@', $this->callback[$index]);
469
-					}
470
-					if(is_array($moduleControllerMethod)){
471
-						if(isset($moduleControllerMethod[0])){
472
-							$this->controller = $moduleControllerMethod[0];	
473
-						}
474
-						if(isset($moduleControllerMethod[1])){
475
-							$this->method = $moduleControllerMethod[1];
476
-						}
477
-						$this->args = $args;
478
-					}
479
-					// stop here
480
-					break;
481
-				}
482
-			}
483
-
484
-			//first if the controller is not set and the module is set use the module name as the controller
485
-			if(! $this->controller && $this->module){
486
-				$this->logger->info(
487
-									'After loop in predefined routes configuration, 
441
+            $pattern = array(':num', ':alpha', ':alnum', ':any');
442
+            $replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
443
+
444
+            $this->logger->debug(
445
+                                    'Begin to loop in the predefined routes configuration ' 
446
+                                    . 'to check if the current request match'
447
+                                    );
448
+
449
+            // Cycle through the URIs stored in the array
450
+            foreach ($this->pattern as $index => $uriList) {
451
+                $uriList = str_ireplace($pattern, $replace, $uriList);
452
+                // Check for an existant matching URI
453
+                if (preg_match("#^$uriList$#", $uri, $args)) {
454
+                    $this->logger->info(
455
+                                        'Route found for request URI [' . $uri . '] using the predefined configuration '
456
+                                        . ' [' . $this->pattern[$index] . '] --> [' . $this->callback[$index] . ']'
457
+                                    );
458
+                    array_shift($args);
459
+                    //check if this contains an module
460
+                    $moduleControllerMethod = explode('#', $this->callback[$index]);
461
+                    if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
462
+                        $this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
463
+                        $this->module = $moduleControllerMethod[0];
464
+                        $moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
465
+                    }
466
+                    else{
467
+                        $this->logger->info('The current request does not use the module');
468
+                        $moduleControllerMethod = explode('@', $this->callback[$index]);
469
+                    }
470
+                    if(is_array($moduleControllerMethod)){
471
+                        if(isset($moduleControllerMethod[0])){
472
+                            $this->controller = $moduleControllerMethod[0];	
473
+                        }
474
+                        if(isset($moduleControllerMethod[1])){
475
+                            $this->method = $moduleControllerMethod[1];
476
+                        }
477
+                        $this->args = $args;
478
+                    }
479
+                    // stop here
480
+                    break;
481
+                }
482
+            }
483
+
484
+            //first if the controller is not set and the module is set use the module name as the controller
485
+            if(! $this->controller && $this->module){
486
+                $this->logger->info(
487
+                                    'After loop in predefined routes configuration, 
488 488
 									the module name is set but the controller is not set, 
489 489
 									so we will use module as the controller'
490
-								);
491
-				$this->controller = $this->module;
492
-			}
493
-	    }
494
-
495
-	    /**
496
-	     * Determine the route parameters using the server variable "REQUEST_URI"
497
-	     * @return void
498
-	     */
499
-	    protected function determineRouteParamsFromRequestUri(){
500
-	    	$segment = $this->segments;
501
-	    	$nbSegment = count($segment);
502
-			//if segment is null so means no need to perform
503
-			if($nbSegment > 0){
504
-				//get the module list
505
-				$modules = Module::getModuleList();
506
-				//first check if no module
507
-				if(empty($modules)){
508
-					$this->logger->info('No module was loaded will skip the module checking');
509
-					//the application don't use module
510
-					//controller
511
-					if(isset($segment[0])){
512
-						$this->controller = $segment[0];
513
-						array_shift($segment);
514
-					}
515
-					//method
516
-					if(isset($segment[0])){
517
-						$this->method = $segment[0];
518
-						array_shift($segment);
519
-					}
520
-					//args
521
-					$this->args = $segment;
522
-				}
523
-				else{
524
-					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
525
-					if(in_array($segment[0], $modules)){
526
-						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
527
-						$this->module = $segment[0];
528
-						array_shift($segment);
529
-						//check if the second arg is the controller from module
530
-						if(isset($segment[0])){
531
-							$this->controller = $segment[0];
532
-							//check if the request use the same module name and controller
533
-							$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
534
-							if(! $path){
535
-								$this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
536
-								$this->controller = $this->module;
537
-							}
538
-							else{
539
-								$this->controllerPath = $path;
540
-								array_shift($segment);
541
-							}
542
-						}
543
-						//check for method
544
-						if(isset($segment[0])){
545
-							$this->method = $segment[0];
546
-							array_shift($segment);
547
-						}
548
-						//the remaining is for args
549
-						$this->args = $segment;
550
-					}
551
-					else{
552
-						$this->logger->info('The current request information is not found in the module list');
553
-						//controller
554
-						if(isset($segment[0])){
555
-							$this->controller = $segment[0];
556
-							array_shift($segment);
557
-						}
558
-						//method
559
-						if(isset($segment[0])){
560
-							$this->method = $segment[0];
561
-							array_shift($segment);
562
-						}
563
-						//args
564
-						$this->args = $segment;
565
-					}
566
-				}
567
-				if(! $this->controller && $this->module){
568
-					$this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
569
-					$this->controller = $this->module;
570
-				}
571
-			}
572
-	    }
573
-
574
-	    /**
575
-	     * Set the route informations using the configuration
576
-	     *
577
-	     * @return object the current instance
578
-	     */
579
-	    protected function setRouteConfigurationInfos(){
580
-	    	//adding route
581
-			foreach($this->routes as $pattern => $callback){
582
-				$this->add($pattern, $callback);
583
-			}
584
-			return $this;
585
-		}
586
-	}
490
+                                );
491
+                $this->controller = $this->module;
492
+            }
493
+        }
494
+
495
+        /**
496
+         * Determine the route parameters using the server variable "REQUEST_URI"
497
+         * @return void
498
+         */
499
+        protected function determineRouteParamsFromRequestUri(){
500
+            $segment = $this->segments;
501
+            $nbSegment = count($segment);
502
+            //if segment is null so means no need to perform
503
+            if($nbSegment > 0){
504
+                //get the module list
505
+                $modules = Module::getModuleList();
506
+                //first check if no module
507
+                if(empty($modules)){
508
+                    $this->logger->info('No module was loaded will skip the module checking');
509
+                    //the application don't use module
510
+                    //controller
511
+                    if(isset($segment[0])){
512
+                        $this->controller = $segment[0];
513
+                        array_shift($segment);
514
+                    }
515
+                    //method
516
+                    if(isset($segment[0])){
517
+                        $this->method = $segment[0];
518
+                        array_shift($segment);
519
+                    }
520
+                    //args
521
+                    $this->args = $segment;
522
+                }
523
+                else{
524
+                    $this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
525
+                    if(in_array($segment[0], $modules)){
526
+                        $this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
527
+                        $this->module = $segment[0];
528
+                        array_shift($segment);
529
+                        //check if the second arg is the controller from module
530
+                        if(isset($segment[0])){
531
+                            $this->controller = $segment[0];
532
+                            //check if the request use the same module name and controller
533
+                            $path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
534
+                            if(! $path){
535
+                                $this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
536
+                                $this->controller = $this->module;
537
+                            }
538
+                            else{
539
+                                $this->controllerPath = $path;
540
+                                array_shift($segment);
541
+                            }
542
+                        }
543
+                        //check for method
544
+                        if(isset($segment[0])){
545
+                            $this->method = $segment[0];
546
+                            array_shift($segment);
547
+                        }
548
+                        //the remaining is for args
549
+                        $this->args = $segment;
550
+                    }
551
+                    else{
552
+                        $this->logger->info('The current request information is not found in the module list');
553
+                        //controller
554
+                        if(isset($segment[0])){
555
+                            $this->controller = $segment[0];
556
+                            array_shift($segment);
557
+                        }
558
+                        //method
559
+                        if(isset($segment[0])){
560
+                            $this->method = $segment[0];
561
+                            array_shift($segment);
562
+                        }
563
+                        //args
564
+                        $this->args = $segment;
565
+                    }
566
+                }
567
+                if(! $this->controller && $this->module){
568
+                    $this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
569
+                    $this->controller = $this->module;
570
+                }
571
+            }
572
+        }
573
+
574
+        /**
575
+         * Set the route informations using the configuration
576
+         *
577
+         * @return object the current instance
578
+         */
579
+        protected function setRouteConfigurationInfos(){
580
+            //adding route
581
+            foreach($this->routes as $pattern => $callback){
582
+                $this->add($pattern, $callback);
583
+            }
584
+            return $this;
585
+        }
586
+    }
Please login to merge, or discard this patch.
Spacing   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Router extends BaseClass{
27
+	class Router extends BaseClass {
28 28
 		/**
29 29
 		* @var array $pattern: The list of URIs to validate against
30 30
 		*/
@@ -90,13 +90,13 @@  discard block
 block discarded – undo
90 90
 		/**
91 91
 		 * Construct the new Router instance
92 92
 		 */
93
-		public function __construct(){
93
+		public function __construct() {
94 94
 			parent::__construct();
95 95
 			
96 96
 			//loading routes for module
97 97
 			$moduleRouteList = array();
98 98
 			$modulesRoutes = Module::getModulesRoutesConfig();
99
-			if($modulesRoutes && is_array($modulesRoutes)){
99
+			if ($modulesRoutes && is_array($modulesRoutes)) {
100 100
 				$moduleRouteList = $modulesRoutes;
101 101
 				unset($modulesRoutes);
102 102
 			}
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		 * Get the route patterns
112 112
 		 * @return array
113 113
 		 */
114
-		public function getPattern(){
114
+		public function getPattern() {
115 115
 			return $this->pattern;
116 116
 		}
117 117
 
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 		 * Get the route callbacks
120 120
 		 * @return array
121 121
 		 */
122
-		public function getCallback(){
122
+		public function getCallback() {
123 123
 			return $this->callback;
124 124
 		}
125 125
 
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 		 * Get the module name
128 128
 		 * @return string
129 129
 		 */
130
-		public function getModule(){
130
+		public function getModule() {
131 131
 			return $this->module;
132 132
 		}
133 133
 		
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 		 * Get the controller name
136 136
 		 * @return string
137 137
 		 */
138
-		public function getController(){
138
+		public function getController() {
139 139
 			return $this->controller;
140 140
 		}
141 141
 
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 		 * Get the controller file path
144 144
 		 * @return string
145 145
 		 */
146
-		public function getControllerPath(){
146
+		public function getControllerPath() {
147 147
 			return $this->controllerPath;
148 148
 		}
149 149
 
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
 		 * Get the controller method
152 152
 		 * @return string
153 153
 		 */
154
-		public function getMethod(){
154
+		public function getMethod() {
155 155
 			return $this->method;
156 156
 		}
157 157
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		 * Get the request arguments
160 160
 		 * @return array
161 161
 		 */
162
-		public function getArgs(){
162
+		public function getArgs() {
163 163
 			return $this->args;
164 164
 		}
165 165
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 		 * Get the URL segments array
168 168
 		 * @return array
169 169
 		 */
170
-		public function getSegments(){
170
+		public function getSegments() {
171 171
 			return $this->segments;
172 172
 		}
173 173
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		 * Get the route URI
176 176
 		 * @return string
177 177
 		 */
178
-		public function getRouteUri(){
178
+		public function getRouteUri() {
179 179
 			return $this->uri;
180 180
 		}
181 181
 
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		*/
190 190
 		public function add($uri, $callback) {
191 191
 			$uri = trim($uri, $this->uriTrim);
192
-			if(in_array($uri, $this->pattern)){
192
+			if (in_array($uri, $this->pattern)) {
193 193
 				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
194 194
 			}
195 195
 			$this->pattern[] = $uri;
@@ -205,8 +205,8 @@  discard block
 block discarded – undo
205 205
 		* @return object the current instance
206 206
 		*/
207 207
 		public function removeRoute($uri) {
208
-			$index  = array_search($uri, $this->pattern, true);
209
-			if($index !== false){
208
+			$index = array_search($uri, $this->pattern, true);
209
+			if ($index !== false) {
210 210
 				$this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
211 211
 				unset($this->pattern[$index]);
212 212
 				unset($this->callback[$index]);
@@ -234,26 +234,26 @@  discard block
 block discarded – undo
234 234
 	     * @param string $uri the route URI, if is empty will determine automatically
235 235
 	     * @return object
236 236
 	     */
237
-	    public function setRouteUri($uri = ''){
237
+	    public function setRouteUri($uri = '') {
238 238
 	    	$routeUri = '';
239
-	    	if(! empty($uri)){
239
+	    	if (!empty($uri)) {
240 240
 	    		$routeUri = $uri;
241 241
 	    	}
242 242
 	    	//if the application is running in CLI mode use the first argument
243
-			else if(IS_CLI && isset($_SERVER['argv'][1])){
243
+			else if (IS_CLI && isset($_SERVER['argv'][1])) {
244 244
 				$routeUri = $_SERVER['argv'][1];
245 245
 			}
246
-			else if(isset($_SERVER['REQUEST_URI'])){
246
+			else if (isset($_SERVER['REQUEST_URI'])) {
247 247
 				$routeUri = $_SERVER['REQUEST_URI'];
248 248
 			}
249 249
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
250 250
 			//remove url suffix from the request URI
251 251
 			$suffix = get_config('url_suffix');
252 252
 			if ($suffix) {
253
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
253
+				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']');
254 254
 				$routeUri = str_ireplace($suffix, '', $routeUri);
255 255
 			} 
256
-			if (strpos($routeUri, '?') !== false){
256
+			if (strpos($routeUri, '?') !== false) {
257 257
 				$routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
258 258
 			}
259 259
 			$this->uri = trim($routeUri, $this->uriTrim);
@@ -266,8 +266,8 @@  discard block
 block discarded – undo
266 266
 		 * 
267 267
 		 * @return object
268 268
 		 */
269
-		public function setRouteSegments(array $segments = array()){
270
-			if(! empty($segments)){
269
+		public function setRouteSegments(array $segments = array()) {
270
+			if (!empty($segments)) {
271 271
 				$this->segments = $segments;
272 272
 			} else if (!empty($this->uri)) {
273 273
 				$this->segments = explode('/', $this->uri);
@@ -275,12 +275,12 @@  discard block
 block discarded – undo
275 275
 			$segment = $this->segments;
276 276
 			$baseUrl = get_config('base_url');
277 277
 			//check if the app is not in DOCUMENT_ROOT
278
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
278
+			if (isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false) {
279 279
 				array_shift($segment);
280 280
 				$this->segments = $segment;
281 281
 			}
282 282
 			$this->logger->debug('Check if the request URI contains the front controller');
283
-			if(isset($segment[0]) && $segment[0] == SELF){
283
+			if (isset($segment[0]) && $segment[0] == SELF) {
284 284
 				$this->logger->info('The request URI contains the front controller');
285 285
 				array_shift($segment);
286 286
 				$this->segments = $segment;
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 			
301 301
 			//if can not determine the module/controller/method via the defined routes configuration we will use
302 302
 			//the URL like http://domain.com/module/controller/method/arg1/arg2
303
-			if(! $this->controller){
303
+			if (!$this->controller) {
304 304
 				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
305 305
 				//determine route parameters using the REQUEST_URI param
306 306
 				$this->determineRouteParamsFromRequestUri();
@@ -316,14 +316,14 @@  discard block
 block discarded – undo
316 316
 		 * Routing the request to the correspondant module/controller/method if exists
317 317
 		 * otherwise send 404 error.
318 318
 		 */
319
-	    public function processRequest(){
319
+	    public function processRequest() {
320 320
 	    	//Setting the route URI
321 321
 			$this->setRouteUri();
322 322
 
323 323
 			//setting route segments
324 324
 			$this->setRouteSegments();
325 325
 
326
-			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
326
+			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']');
327 327
 
328 328
 	    	//determine the route parameters information
329 329
 	    	$this->determineRouteParamsInformation();
@@ -334,20 +334,20 @@  discard block
 block discarded – undo
334 334
 	    	$this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
335 335
 	    	$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
336 336
 	    	
337
-			if(file_exists($classFilePath)){
337
+			if (file_exists($classFilePath)) {
338 338
 				require_once $classFilePath;
339
-				if(! class_exists($controller, false)){
339
+				if (!class_exists($controller, false)) {
340 340
 					$e404 = true;
341
-					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
341
+					$this->logger->warning('The controller file [' . $classFilePath . '] exists but does not contain the class [' . $controller . ']');
342 342
 				}
343
-				else{
343
+				else {
344 344
 					$controllerInstance = new $controller();
345 345
 					$controllerMethod = $this->getMethod();
346
-					if(! method_exists($controllerInstance, $controllerMethod)){
346
+					if (!method_exists($controllerInstance, $controllerMethod)) {
347 347
 						$e404 = true;
348 348
 						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
349 349
 					}
350
-					else{
350
+					else {
351 351
 						$this->logger->info('Routing data is set correctly now GO!');
352 352
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
353 353
 						//render the final page to user
@@ -356,16 +356,16 @@  discard block
 block discarded – undo
356 356
 					}
357 357
 				}
358 358
 			}
359
-			else{
359
+			else {
360 360
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
361 361
 				$e404 = true;
362 362
 			}
363
-			if($e404){
364
-				if(IS_CLI){
363
+			if ($e404) {
364
+				if (IS_CLI) {
365 365
 					set_http_status_header(404);
366 366
 					echo 'Error 404: page not found.';
367 367
 				} else {
368
-					$response =& class_loader('Response', 'classes');
368
+					$response = & class_loader('Response', 'classes');
369 369
 					$response->send404();
370 370
 				}
371 371
 			}
@@ -378,15 +378,15 @@  discard block
 block discarded – undo
378 378
 	    * @param boolean $useConfigFile whether to use route configuration file
379 379
 		* @return object
380 380
 	    */
381
-	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
381
+	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
382 382
 	        $route = array();
383
-	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
383
+	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')) {
384 384
 	            require_once CONFIG_PATH . 'routes.php';
385 385
 	        }
386 386
 	        $route = array_merge($route, $overwriteConfig);
387 387
 	        $this->routes = $route;
388 388
 	        //if route is empty remove all configuration
389
-	        if(empty($route)){
389
+	        if (empty($route)) {
390 390
 	        	$this->removeAllRoute();
391 391
 	        }
392 392
 			return $this;
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
 		 * Get the route configuration
397 397
 		 * @return array
398 398
 		 */
399
-		public function getRouteConfiguration(){
399
+		public function getRouteConfiguration() {
400 400
 			return $this->routes;
401 401
 		}
402 402
 
@@ -408,19 +408,19 @@  discard block
 block discarded – undo
408 408
 	     *
409 409
 	     * @return object the current instance
410 410
 	     */
411
-	    public function setControllerFilePath($path = null){
412
-	    	if($path !== null){
411
+	    public function setControllerFilePath($path = null) {
412
+	    	if ($path !== null) {
413 413
 	    		$this->controllerPath = $path;
414 414
 	    		return $this;
415 415
 	    	}
416 416
 	    	//did we set the controller, so set the controller path
417
-			if($this->controller && ! $this->controllerPath){
417
+			if ($this->controller && !$this->controllerPath) {
418 418
 				$this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
419 419
 				$controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
420 420
 				//if the controller is in module
421
-				if($this->module){
421
+				if ($this->module) {
422 422
 					$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
423
-					if($path !== false){
423
+					if ($path !== false) {
424 424
 						$controllerPath = $path;
425 425
 					}
426 426
 				}
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 	     * Determine the route parameters from route configuration
434 434
 	     * @return void
435 435
 	     */
436
-	    protected function determineRouteParamsFromConfig(){
436
+	    protected function determineRouteParamsFromConfig() {
437 437
 	    	$uri = implode('/', $this->segments);
438 438
 	    	/*
439 439
 	   		* Generics routes patterns
@@ -458,20 +458,20 @@  discard block
 block discarded – undo
458 458
 					array_shift($args);
459 459
 					//check if this contains an module
460 460
 					$moduleControllerMethod = explode('#', $this->callback[$index]);
461
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
461
+					if (is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2) {
462 462
 						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
463 463
 						$this->module = $moduleControllerMethod[0];
464 464
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
465 465
 					}
466
-					else{
466
+					else {
467 467
 						$this->logger->info('The current request does not use the module');
468 468
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
469 469
 					}
470
-					if(is_array($moduleControllerMethod)){
471
-						if(isset($moduleControllerMethod[0])){
470
+					if (is_array($moduleControllerMethod)) {
471
+						if (isset($moduleControllerMethod[0])) {
472 472
 							$this->controller = $moduleControllerMethod[0];	
473 473
 						}
474
-						if(isset($moduleControllerMethod[1])){
474
+						if (isset($moduleControllerMethod[1])) {
475 475
 							$this->method = $moduleControllerMethod[1];
476 476
 						}
477 477
 						$this->args = $args;
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 			}
483 483
 
484 484
 			//first if the controller is not set and the module is set use the module name as the controller
485
-			if(! $this->controller && $this->module){
485
+			if (!$this->controller && $this->module) {
486 486
 				$this->logger->info(
487 487
 									'After loop in predefined routes configuration, 
488 488
 									the module name is set but the controller is not set, 
@@ -496,67 +496,67 @@  discard block
 block discarded – undo
496 496
 	     * Determine the route parameters using the server variable "REQUEST_URI"
497 497
 	     * @return void
498 498
 	     */
499
-	    protected function determineRouteParamsFromRequestUri(){
499
+	    protected function determineRouteParamsFromRequestUri() {
500 500
 	    	$segment = $this->segments;
501 501
 	    	$nbSegment = count($segment);
502 502
 			//if segment is null so means no need to perform
503
-			if($nbSegment > 0){
503
+			if ($nbSegment > 0) {
504 504
 				//get the module list
505 505
 				$modules = Module::getModuleList();
506 506
 				//first check if no module
507
-				if(empty($modules)){
507
+				if (empty($modules)) {
508 508
 					$this->logger->info('No module was loaded will skip the module checking');
509 509
 					//the application don't use module
510 510
 					//controller
511
-					if(isset($segment[0])){
511
+					if (isset($segment[0])) {
512 512
 						$this->controller = $segment[0];
513 513
 						array_shift($segment);
514 514
 					}
515 515
 					//method
516
-					if(isset($segment[0])){
516
+					if (isset($segment[0])) {
517 517
 						$this->method = $segment[0];
518 518
 						array_shift($segment);
519 519
 					}
520 520
 					//args
521 521
 					$this->args = $segment;
522 522
 				}
523
-				else{
523
+				else {
524 524
 					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
525
-					if(in_array($segment[0], $modules)){
525
+					if (in_array($segment[0], $modules)) {
526 526
 						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
527 527
 						$this->module = $segment[0];
528 528
 						array_shift($segment);
529 529
 						//check if the second arg is the controller from module
530
-						if(isset($segment[0])){
530
+						if (isset($segment[0])) {
531 531
 							$this->controller = $segment[0];
532 532
 							//check if the request use the same module name and controller
533 533
 							$path = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
534
-							if(! $path){
534
+							if (!$path) {
535 535
 								$this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
536 536
 								$this->controller = $this->module;
537 537
 							}
538
-							else{
538
+							else {
539 539
 								$this->controllerPath = $path;
540 540
 								array_shift($segment);
541 541
 							}
542 542
 						}
543 543
 						//check for method
544
-						if(isset($segment[0])){
544
+						if (isset($segment[0])) {
545 545
 							$this->method = $segment[0];
546 546
 							array_shift($segment);
547 547
 						}
548 548
 						//the remaining is for args
549 549
 						$this->args = $segment;
550 550
 					}
551
-					else{
551
+					else {
552 552
 						$this->logger->info('The current request information is not found in the module list');
553 553
 						//controller
554
-						if(isset($segment[0])){
554
+						if (isset($segment[0])) {
555 555
 							$this->controller = $segment[0];
556 556
 							array_shift($segment);
557 557
 						}
558 558
 						//method
559
-						if(isset($segment[0])){
559
+						if (isset($segment[0])) {
560 560
 							$this->method = $segment[0];
561 561
 							array_shift($segment);
562 562
 						}
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
 						$this->args = $segment;
565 565
 					}
566 566
 				}
567
-				if(! $this->controller && $this->module){
567
+				if (!$this->controller && $this->module) {
568 568
 					$this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
569 569
 					$this->controller = $this->module;
570 570
 				}
@@ -576,9 +576,9 @@  discard block
 block discarded – undo
576 576
 	     *
577 577
 	     * @return object the current instance
578 578
 	     */
579
-	    protected function setRouteConfigurationInfos(){
579
+	    protected function setRouteConfigurationInfos() {
580 580
 	    	//adding route
581
-			foreach($this->routes as $pattern => $callback){
581
+			foreach ($this->routes as $pattern => $callback) {
582 582
 				$this->add($pattern, $callback);
583 583
 			}
584 584
 			return $this;
Please login to merge, or discard this patch.
Braces   +8 added lines, -16 removed lines patch added patch discarded remove patch
@@ -242,8 +242,7 @@  discard block
 block discarded – undo
242 242
 	    	//if the application is running in CLI mode use the first argument
243 243
 			else if(IS_CLI && isset($_SERVER['argv'][1])){
244 244
 				$routeUri = $_SERVER['argv'][1];
245
-			}
246
-			else if(isset($_SERVER['REQUEST_URI'])){
245
+			} else if(isset($_SERVER['REQUEST_URI'])){
247 246
 				$routeUri = $_SERVER['REQUEST_URI'];
248 247
 			}
249 248
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
@@ -339,15 +338,13 @@  discard block
 block discarded – undo
339 338
 				if(! class_exists($controller, false)){
340 339
 					$e404 = true;
341 340
 					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
342
-				}
343
-				else{
341
+				} else{
344 342
 					$controllerInstance = new $controller();
345 343
 					$controllerMethod = $this->getMethod();
346 344
 					if(! method_exists($controllerInstance, $controllerMethod)){
347 345
 						$e404 = true;
348 346
 						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
349
-					}
350
-					else{
347
+					} else{
351 348
 						$this->logger->info('Routing data is set correctly now GO!');
352 349
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
353 350
 						//render the final page to user
@@ -355,8 +352,7 @@  discard block
 block discarded – undo
355 352
 						get_instance()->response->renderFinalPage();
356 353
 					}
357 354
 				}
358
-			}
359
-			else{
355
+			} else{
360 356
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
361 357
 				$e404 = true;
362 358
 			}
@@ -462,8 +458,7 @@  discard block
 block discarded – undo
462 458
 						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
463 459
 						$this->module = $moduleControllerMethod[0];
464 460
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
465
-					}
466
-					else{
461
+					} else{
467 462
 						$this->logger->info('The current request does not use the module');
468 463
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
469 464
 					}
@@ -519,8 +514,7 @@  discard block
 block discarded – undo
519 514
 					}
520 515
 					//args
521 516
 					$this->args = $segment;
522
-				}
523
-				else{
517
+				} else{
524 518
 					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
525 519
 					if(in_array($segment[0], $modules)){
526 520
 						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
@@ -534,8 +528,7 @@  discard block
 block discarded – undo
534 528
 							if(! $path){
535 529
 								$this->logger->info('The controller [' . $this->controller . '] not found in the module, may be will use the module [' . $this->module . '] as controller');
536 530
 								$this->controller = $this->module;
537
-							}
538
-							else{
531
+							} else{
539 532
 								$this->controllerPath = $path;
540 533
 								array_shift($segment);
541 534
 							}
@@ -547,8 +540,7 @@  discard block
 block discarded – undo
547 540
 						}
548 541
 						//the remaining is for args
549 542
 						$this->args = $segment;
550
-					}
551
-					else{
543
+					} else{
552 544
 						$this->logger->info('The current request information is not found in the module list');
553 545
 						//controller
554 546
 						if(isset($segment[0])){
Please login to merge, or discard this patch.