Passed
Push — 1.0.0-dev ( 407604...83bedf )
by nguereza
03:26
created
core/bootstrap.php 1 patch
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -1,195 +1,195 @@
 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 bootstrap.php
29
-	 *  
30
-	 *  Contains the loading process: loading of constants, common functions, libraries 
31
-	 *  configurations, etc
32
-	 *  verification of the environment and the routing of the request.
33
-	 *  
34
-	 *  @package	core	
35
-	 *  @author	Tony NGUEREZA
36
-	 *  @copyright	Copyright (c) 2017
37
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
38
-	 *  @link	http://www.iacademy.cf
39
-	 *  @version 1.0.0
40
-	 *  @filesource
41
-	 */
27
+    /**
28
+     *  @file bootstrap.php
29
+     *  
30
+     *  Contains the loading process: loading of constants, common functions, libraries 
31
+     *  configurations, etc
32
+     *  verification of the environment and the routing of the request.
33
+     *  
34
+     *  @package	core	
35
+     *  @author	Tony NGUEREZA
36
+     *  @copyright	Copyright (c) 2017
37
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
38
+     *  @link	http://www.iacademy.cf
39
+     *  @version 1.0.0
40
+     *  @filesource
41
+     */
42 42
 	
43
-	//if the application is running in CLI mode $_SESSION global variable is not available
44
-	if(IS_CLI){
45
-		$_SESSION = array();
46
-	}
43
+    //if the application is running in CLI mode $_SESSION global variable is not available
44
+    if(IS_CLI){
45
+        $_SESSION = array();
46
+    }
47 47
 		
48
-	/**
49
-	*  inclusion of global constants of the environment that contain : name of the framework,
50
-	*  version, release date, version of PHP required, etc.
51
-	*/
52
-	require_once CORE_PATH . 'constants.php';	
48
+    /**
49
+     *  inclusion of global constants of the environment that contain : name of the framework,
50
+     *  version, release date, version of PHP required, etc.
51
+     */
52
+    require_once CORE_PATH . 'constants.php';	
53 53
 	
54
-	/**
55
-	 *  include file containing commons functions used in the framework such: show_error, 
56
-	 *  php_exception_handler, php_error_handler, get_instance, etc.
57
-	 */
58
-	require_once CORE_PATH . 'common.php';
54
+    /**
55
+     *  include file containing commons functions used in the framework such: show_error, 
56
+     *  php_exception_handler, php_error_handler, get_instance, etc.
57
+     */
58
+    require_once CORE_PATH . 'common.php';
59 59
 
60
-	/**
61
-	 * The Benchmark class
62
-	 */
63
-	$BENCHMARK =& class_loader('Benchmark');
60
+    /**
61
+     * The Benchmark class
62
+     */
63
+    $BENCHMARK =& class_loader('Benchmark');
64 64
 	
65
-	$BENCHMARK->mark('APP_EXECUTION_START');
65
+    $BENCHMARK->mark('APP_EXECUTION_START');
66 66
 	
67
-	/**
68
-    * instance of the Log class
69
-    */
67
+    /**
68
+     * instance of the Log class
69
+     */
70 70
     $LOGGER =& class_loader('Log', 'classes');
71 71
 
72 72
     $LOGGER->setLogger('ApplicationBootstrap');
73 73
 
74 74
     $LOGGER->debug('Checking PHP version ...');	
75 75
 	
76
-	/**
77
-	* Verification of the PHP environment: minimum and maximum version
78
-	*/
79
-	if (version_compare(phpversion(), TNH_REQUIRED_PHP_MIN_VERSION, '<')){
80
-		show_error('Your PHP Version [' . phpversion() . '] is less than [' . TNH_REQUIRED_PHP_MIN_VERSION . '], please install a new version or update your PHP to the latest.', 'PHP Error environment');	
81
-	}
82
-	else if(version_compare(phpversion(), TNH_REQUIRED_PHP_MAX_VERSION, '>')){
83
-		show_error('Your PHP Version [' . phpversion() . '] is greather than [' . TNH_REQUIRED_PHP_MAX_VERSION . '] please install a PHP version that is compatible.', 'PHP Error environment');	
84
-	}
85
-	$LOGGER->info('PHP version [' . phpversion() . '] is OK [REQUIRED MINIMUM: ' . TNH_REQUIRED_PHP_MIN_VERSION . ', REQUIRED MAXIMUM: ' . TNH_REQUIRED_PHP_MAX_VERSION . '], application can work without any issue');
76
+    /**
77
+     * Verification of the PHP environment: minimum and maximum version
78
+     */
79
+    if (version_compare(phpversion(), TNH_REQUIRED_PHP_MIN_VERSION, '<')){
80
+        show_error('Your PHP Version [' . phpversion() . '] is less than [' . TNH_REQUIRED_PHP_MIN_VERSION . '], please install a new version or update your PHP to the latest.', 'PHP Error environment');	
81
+    }
82
+    else if(version_compare(phpversion(), TNH_REQUIRED_PHP_MAX_VERSION, '>')){
83
+        show_error('Your PHP Version [' . phpversion() . '] is greather than [' . TNH_REQUIRED_PHP_MAX_VERSION . '] please install a PHP version that is compatible.', 'PHP Error environment');	
84
+    }
85
+    $LOGGER->info('PHP version [' . phpversion() . '] is OK [REQUIRED MINIMUM: ' . TNH_REQUIRED_PHP_MIN_VERSION . ', REQUIRED MAXIMUM: ' . TNH_REQUIRED_PHP_MAX_VERSION . '], application can work without any issue');
86 86
 
87
-	/**
88
-	* Setting of the PHP error message handling function
89
-	*/
90
-	set_error_handler('php_error_handler');
87
+    /**
88
+     * Setting of the PHP error message handling function
89
+     */
90
+    set_error_handler('php_error_handler');
91 91
 
92
-	/**
93
-	* Setting of the PHP error exception handling function
94
-	*/
95
-	set_exception_handler('php_exception_handler');
92
+    /**
93
+     * Setting of the PHP error exception handling function
94
+     */
95
+    set_exception_handler('php_exception_handler');
96 96
 
97
-	/**
98
-	 * Setting of the PHP shutdown handling function
99
-	 */
100
-	register_shutdown_function('php_shudown_handler');
97
+    /**
98
+     * Setting of the PHP shutdown handling function
99
+     */
100
+    register_shutdown_function('php_shudown_handler');
101 101
 	
102
-	//if user have some composer packages
103
-	$LOGGER->debug('Check for composer autoload');
104
-	if(file_exists(VENDOR_PATH . 'autoload.php')){
105
-		$LOGGER->info('The composer autoload file exists include it');
106
-		require_once VENDOR_PATH . 'autoload.php';
107
-	}
108
-	else{
109
-		$LOGGER->info('The composer autoload file does not exist skipping');
110
-	}
102
+    //if user have some composer packages
103
+    $LOGGER->debug('Check for composer autoload');
104
+    if(file_exists(VENDOR_PATH . 'autoload.php')){
105
+        $LOGGER->info('The composer autoload file exists include it');
106
+        require_once VENDOR_PATH . 'autoload.php';
107
+    }
108
+    else{
109
+        $LOGGER->info('The composer autoload file does not exist skipping');
110
+    }
111 111
 	
112
-	$LOGGER->debug('Begin to load the required resources');
112
+    $LOGGER->debug('Begin to load the required resources');
113 113
 
114
-	/**
115
-	 * Load the EventInfo class file
116
-	 */
117
-	require_once CORE_CLASSES_PATH . 'EventInfo.php';
114
+    /**
115
+     * Load the EventInfo class file
116
+     */
117
+    require_once CORE_CLASSES_PATH . 'EventInfo.php';
118 118
 
119 119
 
120
-	$BENCHMARK->mark('CONFIG_INIT_START');
121
-	/**
122
-	* Load configurations and using the 
123
-	* static method "init()" to initialize the Config class .
124
-	*/
125
-	$CONFIG =& class_loader('Config', 'classes');	
126
-	$CONFIG->init();
127
-	$BENCHMARK->mark('CONFIG_INIT_END');
120
+    $BENCHMARK->mark('CONFIG_INIT_START');
121
+    /**
122
+     * Load configurations and using the 
123
+     * static method "init()" to initialize the Config class .
124
+     */
125
+    $CONFIG =& class_loader('Config', 'classes');	
126
+    $CONFIG->init();
127
+    $BENCHMARK->mark('CONFIG_INIT_END');
128 128
 
129
-	$BENCHMARK->mark('MODULE_INIT_START');
130
-	/**
131
-	* Load modules and using the 
132
-	* static method "init()" to initialize the Module class.
133
-	*/
134
-	$MODULE =& class_loader('Module', 'classes');
135
-	$MODULE->init();
136
-	$BENCHMARK->mark('MODULE_INIT_END');
129
+    $BENCHMARK->mark('MODULE_INIT_START');
130
+    /**
131
+     * Load modules and using the 
132
+     * static method "init()" to initialize the Module class.
133
+     */
134
+    $MODULE =& class_loader('Module', 'classes');
135
+    $MODULE->init();
136
+    $BENCHMARK->mark('MODULE_INIT_END');
137 137
 
138
-	$LOGGER->debug('Loading Base Controller ...');
139
-	/**
140
-	 * Include of the file containing the Base Controller class 
141
-	 */
142
-	require_once CORE_CLASSES_PATH . 'Controller.php';
143
-	$LOGGER->info('Base Controller loaded successfully');
138
+    $LOGGER->debug('Loading Base Controller ...');
139
+    /**
140
+     * Include of the file containing the Base Controller class 
141
+     */
142
+    require_once CORE_CLASSES_PATH . 'Controller.php';
143
+    $LOGGER->info('Base Controller loaded successfully');
144 144
 
145
-	/**
146
-	* Register controllers autoload function
147
-	*/
148
-	 spl_autoload_register('autoload_controller');
145
+    /**
146
+     * Register controllers autoload function
147
+     */
148
+        spl_autoload_register('autoload_controller');
149 149
 
150
-	/**
151
-	* Loading Security class
152
-	*/
153
-	$SECURITY =& class_loader('Security', 'classes');
154
-	$SECURITY->checkWhiteListIpAccess();
150
+    /**
151
+     * Loading Security class
152
+     */
153
+    $SECURITY =& class_loader('Security', 'classes');
154
+    $SECURITY->checkWhiteListIpAccess();
155 155
 	
156
-	/**
157
-	* Loading Url class
158
-	*/
159
-	$URL =& class_loader('Url', 'classes');
156
+    /**
157
+     * Loading Url class
158
+     */
159
+    $URL =& class_loader('Url', 'classes');
160 160
 	
161
-	if(get_config('cache_enable', false)){
162
-		/**
163
-		 * Load Cache interface file
164
-		 */
165
-		require_once CORE_CLASSES_CACHE_PATH . 'CacheInterface.php';
166
-		$cacheHandler = get_config('cache_handler');
167
-		if(! $cacheHandler){
168
-			show_error('The cache feature is enabled in the configuration but the cache handler class is not set.');
169
-		}
170
-		$CACHE = null;
171
-		//first check if the cache handler is the system driver
172
-		if(file_exists(CORE_CLASSES_CACHE_PATH . $cacheHandler . '.php')){
173
-			$CACHE =& class_loader($cacheHandler, 'classes/cache');
174
-		}
175
-		else{
176
-			//it's not a system driver use user library
177
-			$CACHE =& class_loader($cacheHandler);
178
-		}
179
-		//check if the page already cached
180
-		if(! empty($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'get'){
181
-			$RESPONSE = & class_loader('Response', 'classes');
182
-			$RESPONSE->renderFinalPageFromCache($CACHE);
183
-		}
184
-	}
161
+    if(get_config('cache_enable', false)){
162
+        /**
163
+         * Load Cache interface file
164
+         */
165
+        require_once CORE_CLASSES_CACHE_PATH . 'CacheInterface.php';
166
+        $cacheHandler = get_config('cache_handler');
167
+        if(! $cacheHandler){
168
+            show_error('The cache feature is enabled in the configuration but the cache handler class is not set.');
169
+        }
170
+        $CACHE = null;
171
+        //first check if the cache handler is the system driver
172
+        if(file_exists(CORE_CLASSES_CACHE_PATH . $cacheHandler . '.php')){
173
+            $CACHE =& class_loader($cacheHandler, 'classes/cache');
174
+        }
175
+        else{
176
+            //it's not a system driver use user library
177
+            $CACHE =& class_loader($cacheHandler);
178
+        }
179
+        //check if the page already cached
180
+        if(! empty($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'get'){
181
+            $RESPONSE = & class_loader('Response', 'classes');
182
+            $RESPONSE->renderFinalPageFromCache($CACHE);
183
+        }
184
+    }
185 185
 	
186
-	//load model class
187
-	require_once CORE_CLASSES_MODEL_PATH . 'Model.php';
186
+    //load model class
187
+    require_once CORE_CLASSES_MODEL_PATH . 'Model.php';
188 188
 	
189
-	$LOGGER->info('Everything is OK load Router library and dispatch the request to the corresponding controller');
190
-	/**
191
-	* Routing
192
-	* instantiation of the "Router" class and request processing.
193
-	*/
194
-	$ROUTER = & class_loader('Router', 'classes');
195
-	$ROUTER->processRequest();
189
+    $LOGGER->info('Everything is OK load Router library and dispatch the request to the corresponding controller');
190
+    /**
191
+     * Routing
192
+     * instantiation of the "Router" class and request processing.
193
+     */
194
+    $ROUTER = & class_loader('Router', 'classes');
195
+    $ROUTER->processRequest();
Please login to merge, or discard this patch.
core/classes/Url.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') 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 27
 
28
-	class Url{
28
+    class Url{
29 29
 
30
-		/**
31
-		 * Return the link using base_url config without front controller "index.php"
32
-		 * @param  string $path the link path or full URL
33
-		 * @return string the full link URL
34
-		 */
35
-		public static function base_url($path = ''){
36
-			if(is_url($path)){
37
-				return $path;
38
-			}
39
-			return get_config('base_url') . $path;
40
-		}
30
+        /**
31
+         * Return the link using base_url config without front controller "index.php"
32
+         * @param  string $path the link path or full URL
33
+         * @return string the full link URL
34
+         */
35
+        public static function base_url($path = ''){
36
+            if(is_url($path)){
37
+                return $path;
38
+            }
39
+            return get_config('base_url') . $path;
40
+        }
41 41
 
42
-		/**
43
-		 * Return the link using base_url config with front controller "index.php"
44
-		 * @param  string $path the link path or full URL
45
-		 * @return string the full link URL
46
-		 */
47
-		public static function site_url($path = ''){
48
-			if(is_url($path)){
49
-				return $path;
50
-			}
51
-			$path = rtrim($path, '/');
52
-			$baseUrl = get_config('base_url');
53
-			$frontController = get_config('front_controller');
54
-			$url = $baseUrl;
55
-			if($frontController){
56
-				$url .= $frontController . '/';
57
-			}
58
-			if(($suffix = get_config('url_suffix')) && $path){
59
-				if(strpos($path, '?') !== false){
60
-					$query = explode('?', $path);
61
-					$query[0] = str_ireplace($suffix, '', $query[0]);
62
-					$query[0] = rtrim($query[0], '/');
63
-					$query[0] .= $suffix;
64
-					$path = implode('?', $query);
65
-				}
66
-				else{
67
-					$path .= $suffix;
68
-				}
69
-			}
70
-			return $url . $path;
71
-		}
42
+        /**
43
+         * Return the link using base_url config with front controller "index.php"
44
+         * @param  string $path the link path or full URL
45
+         * @return string the full link URL
46
+         */
47
+        public static function site_url($path = ''){
48
+            if(is_url($path)){
49
+                return $path;
50
+            }
51
+            $path = rtrim($path, '/');
52
+            $baseUrl = get_config('base_url');
53
+            $frontController = get_config('front_controller');
54
+            $url = $baseUrl;
55
+            if($frontController){
56
+                $url .= $frontController . '/';
57
+            }
58
+            if(($suffix = get_config('url_suffix')) && $path){
59
+                if(strpos($path, '?') !== false){
60
+                    $query = explode('?', $path);
61
+                    $query[0] = str_ireplace($suffix, '', $query[0]);
62
+                    $query[0] = rtrim($query[0], '/');
63
+                    $query[0] .= $suffix;
64
+                    $path = implode('?', $query);
65
+                }
66
+                else{
67
+                    $path .= $suffix;
68
+                }
69
+            }
70
+            return $url . $path;
71
+        }
72 72
 
73
-		/**
74
-		 * Return the current site URL
75
-		 * @return string
76
-		 */
77
-		public static function current(){
78
-			$current = '/';
79
-			$requestUri = get_instance()->request->requestUri();
80
-			if($requestUri){
81
-				$current = $requestUri;
82
-			}
83
-			return static::domain() . $current;
84
-		}
73
+        /**
74
+         * Return the current site URL
75
+         * @return string
76
+         */
77
+        public static function current(){
78
+            $current = '/';
79
+            $requestUri = get_instance()->request->requestUri();
80
+            if($requestUri){
81
+                $current = $requestUri;
82
+            }
83
+            return static::domain() . $current;
84
+        }
85 85
 
86
-		/**
87
-		 * Generate a friendly  text to use in link (slugs)
88
-		 * @param  string  $str       the title or text to use to get the friendly text
89
-		 * @param  string  $separator the caracters separator
90
-		 * @param  boolean $lowercase whether to set the final text to lowe case or not
91
-		 * @return string the friendly generated text
92
-		 */
93
-		public static function title($str = null, $separator = '-', $lowercase = true){
94
-			$str = trim($str);
95
-			$from = array('ç','À','Á','Â','Ã','Ä','Å','à','á','â','ã','ä','å','Ò','Ó','Ô','Õ','Ö','Ø','ò','ó','ô','õ','ö','ø','È','É','Ê','Ë','è','é','ê','ë','Ç','ç','Ì','Í','Î','Ï','ì','í','î','ï','Ù','Ú','Û','Ü','ù','ú','û','ü','ÿ','Ñ','ñ');
96
-			$to = array('c','a','a','a','a','a','a','a','a','a','a','a','a','o','o','o','o','o','o','o','o','o','o','o','o','e','e','e','e','e','e','e','e','e','e','i','i','i','i','i','i','i','i','u','u','u','u','u','u','u','u','y','n','n');
97
-			$str = str_replace($from, $to, $str);
98
-			$str = preg_replace('#([^a-z0-9]+)#i', $separator, $str);
99
-			$str = str_replace('--', $separator, $str);
100
-			//if after process we get something like one-two-three-, need truncate the last separator "-"
101
-			if(substr($str, -1) == $separator){
102
-				$str = substr($str, 0, -1);
103
-			}
104
-			if($lowercase){
105
-				$str = strtolower($str);
106
-			}
107
-			return $str;
108
-		}
86
+        /**
87
+         * Generate a friendly  text to use in link (slugs)
88
+         * @param  string  $str       the title or text to use to get the friendly text
89
+         * @param  string  $separator the caracters separator
90
+         * @param  boolean $lowercase whether to set the final text to lowe case or not
91
+         * @return string the friendly generated text
92
+         */
93
+        public static function title($str = null, $separator = '-', $lowercase = true){
94
+            $str = trim($str);
95
+            $from = array('ç','À','Á','Â','Ã','Ä','Å','à','á','â','ã','ä','å','Ò','Ó','Ô','Õ','Ö','Ø','ò','ó','ô','õ','ö','ø','È','É','Ê','Ë','è','é','ê','ë','Ç','ç','Ì','Í','Î','Ï','ì','í','î','ï','Ù','Ú','Û','Ü','ù','ú','û','ü','ÿ','Ñ','ñ');
96
+            $to = array('c','a','a','a','a','a','a','a','a','a','a','a','a','o','o','o','o','o','o','o','o','o','o','o','o','e','e','e','e','e','e','e','e','e','e','i','i','i','i','i','i','i','i','u','u','u','u','u','u','u','u','y','n','n');
97
+            $str = str_replace($from, $to, $str);
98
+            $str = preg_replace('#([^a-z0-9]+)#i', $separator, $str);
99
+            $str = str_replace('--', $separator, $str);
100
+            //if after process we get something like one-two-three-, need truncate the last separator "-"
101
+            if(substr($str, -1) == $separator){
102
+                $str = substr($str, 0, -1);
103
+            }
104
+            if($lowercase){
105
+                $str = strtolower($str);
106
+            }
107
+            return $str;
108
+        }
109 109
 
110
-		/**
111
-		 * Get the current application domain with protocol
112
-		 * @return string the domain name
113
-		 */
114
-		public static function domain(){
115
-			$domain = 'localhost';
116
-			$port = get_instance()->request->server('SERVER_PORT');
117
-			$protocol = 'http';
118
-			if(is_https()){
119
-				$protocol = 'https';
120
-			}
110
+        /**
111
+         * Get the current application domain with protocol
112
+         * @return string the domain name
113
+         */
114
+        public static function domain(){
115
+            $domain = 'localhost';
116
+            $port = get_instance()->request->server('SERVER_PORT');
117
+            $protocol = 'http';
118
+            if(is_https()){
119
+                $protocol = 'https';
120
+            }
121 121
 
122
-			$domainserverVars = array(
123
-				'HTTP_HOST',
124
-				'SERVER_NAME',
125
-				'SERVER_ADDR'
126
-			);
122
+            $domainserverVars = array(
123
+                'HTTP_HOST',
124
+                'SERVER_NAME',
125
+                'SERVER_ADDR'
126
+            );
127 127
 
128
-			foreach ($domainserverVars as $var) {
129
-				$value = get_instance()->request->server($var);
130
-				if($value){
131
-					$domain = $value;
132
-					break;
133
-				}
134
-			}
128
+            foreach ($domainserverVars as $var) {
129
+                $value = get_instance()->request->server($var);
130
+                if($value){
131
+                    $domain = $value;
132
+                    break;
133
+                }
134
+            }
135 135
 			
136
-			if($port && ((is_https() && $port != 443) || (!is_https() && $port != 80))){
137
-				$domain .= ':'.$port;
138
-			}
139
-			return $protocol.'://'.$domain;
140
-		}
136
+            if($port && ((is_https() && $port != 443) || (!is_https() && $port != 80))){
137
+                $domain .= ':'.$port;
138
+            }
139
+            return $protocol.'://'.$domain;
140
+        }
141 141
 
142
-		/**
143
-		 * Get the current request query string
144
-		 * @return string
145
-		 */
146
-		public static function queryString(){
147
-			return get_instance()->request->server('QUERY_STRING');
148
-		}
149
-	}
142
+        /**
143
+         * Get the current request query string
144
+         * @return string
145
+         */
146
+        public static function queryString(){
147
+            return get_instance()->request->server('QUERY_STRING');
148
+        }
149
+    }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -25,15 +25,15 @@  discard block
 block discarded – undo
25 25
 	*/
26 26
 
27 27
 
28
-	class Url{
28
+	class Url {
29 29
 
30 30
 		/**
31 31
 		 * Return the link using base_url config without front controller "index.php"
32 32
 		 * @param  string $path the link path or full URL
33 33
 		 * @return string the full link URL
34 34
 		 */
35
-		public static function base_url($path = ''){
36
-			if(is_url($path)){
35
+		public static function base_url($path = '') {
36
+			if (is_url($path)) {
37 37
 				return $path;
38 38
 			}
39 39
 			return get_config('base_url') . $path;
@@ -44,26 +44,26 @@  discard block
 block discarded – undo
44 44
 		 * @param  string $path the link path or full URL
45 45
 		 * @return string the full link URL
46 46
 		 */
47
-		public static function site_url($path = ''){
48
-			if(is_url($path)){
47
+		public static function site_url($path = '') {
48
+			if (is_url($path)) {
49 49
 				return $path;
50 50
 			}
51 51
 			$path = rtrim($path, '/');
52 52
 			$baseUrl = get_config('base_url');
53 53
 			$frontController = get_config('front_controller');
54 54
 			$url = $baseUrl;
55
-			if($frontController){
55
+			if ($frontController) {
56 56
 				$url .= $frontController . '/';
57 57
 			}
58
-			if(($suffix = get_config('url_suffix')) && $path){
59
-				if(strpos($path, '?') !== false){
58
+			if (($suffix = get_config('url_suffix')) && $path) {
59
+				if (strpos($path, '?') !== false) {
60 60
 					$query = explode('?', $path);
61 61
 					$query[0] = str_ireplace($suffix, '', $query[0]);
62 62
 					$query[0] = rtrim($query[0], '/');
63 63
 					$query[0] .= $suffix;
64 64
 					$path = implode('?', $query);
65 65
 				}
66
-				else{
66
+				else {
67 67
 					$path .= $suffix;
68 68
 				}
69 69
 			}
@@ -74,10 +74,10 @@  discard block
 block discarded – undo
74 74
 		 * Return the current site URL
75 75
 		 * @return string
76 76
 		 */
77
-		public static function current(){
77
+		public static function current() {
78 78
 			$current = '/';
79 79
 			$requestUri = get_instance()->request->requestUri();
80
-			if($requestUri){
80
+			if ($requestUri) {
81 81
 				$current = $requestUri;
82 82
 			}
83 83
 			return static::domain() . $current;
@@ -90,18 +90,18 @@  discard block
 block discarded – undo
90 90
 		 * @param  boolean $lowercase whether to set the final text to lowe case or not
91 91
 		 * @return string the friendly generated text
92 92
 		 */
93
-		public static function title($str = null, $separator = '-', $lowercase = true){
93
+		public static function title($str = null, $separator = '-', $lowercase = true) {
94 94
 			$str = trim($str);
95
-			$from = array('ç','À','Á','Â','Ã','Ä','Å','à','á','â','ã','ä','å','Ò','Ó','Ô','Õ','Ö','Ø','ò','ó','ô','õ','ö','ø','È','É','Ê','Ë','è','é','ê','ë','Ç','ç','Ì','Í','Î','Ï','ì','í','î','ï','Ù','Ú','Û','Ü','ù','ú','û','ü','ÿ','Ñ','ñ');
96
-			$to = array('c','a','a','a','a','a','a','a','a','a','a','a','a','o','o','o','o','o','o','o','o','o','o','o','o','e','e','e','e','e','e','e','e','e','e','i','i','i','i','i','i','i','i','u','u','u','u','u','u','u','u','y','n','n');
95
+			$from = array('ç', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'à', 'á', 'â', 'ã', 'ä', 'å', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'È', 'É', 'Ê', 'Ë', 'è', 'é', 'ê', 'ë', 'Ç', 'ç', 'Ì', 'Í', 'Î', 'Ï', 'ì', 'í', 'î', 'ï', 'Ù', 'Ú', 'Û', 'Ü', 'ù', 'ú', 'û', 'ü', 'ÿ', 'Ñ', 'ñ');
96
+			$to = array('c', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'y', 'n', 'n');
97 97
 			$str = str_replace($from, $to, $str);
98 98
 			$str = preg_replace('#([^a-z0-9]+)#i', $separator, $str);
99 99
 			$str = str_replace('--', $separator, $str);
100 100
 			//if after process we get something like one-two-three-, need truncate the last separator "-"
101
-			if(substr($str, -1) == $separator){
101
+			if (substr($str, -1) == $separator) {
102 102
 				$str = substr($str, 0, -1);
103 103
 			}
104
-			if($lowercase){
104
+			if ($lowercase) {
105 105
 				$str = strtolower($str);
106 106
 			}
107 107
 			return $str;
@@ -111,11 +111,11 @@  discard block
 block discarded – undo
111 111
 		 * Get the current application domain with protocol
112 112
 		 * @return string the domain name
113 113
 		 */
114
-		public static function domain(){
114
+		public static function domain() {
115 115
 			$domain = 'localhost';
116 116
 			$port = get_instance()->request->server('SERVER_PORT');
117 117
 			$protocol = 'http';
118
-			if(is_https()){
118
+			if (is_https()) {
119 119
 				$protocol = 'https';
120 120
 			}
121 121
 
@@ -127,23 +127,23 @@  discard block
 block discarded – undo
127 127
 
128 128
 			foreach ($domainserverVars as $var) {
129 129
 				$value = get_instance()->request->server($var);
130
-				if($value){
130
+				if ($value) {
131 131
 					$domain = $value;
132 132
 					break;
133 133
 				}
134 134
 			}
135 135
 			
136
-			if($port && ((is_https() && $port != 443) || (!is_https() && $port != 80))){
137
-				$domain .= ':'.$port;
136
+			if ($port && ((is_https() && $port != 443) || (!is_https() && $port != 80))) {
137
+				$domain .= ':' . $port;
138 138
 			}
139
-			return $protocol.'://'.$domain;
139
+			return $protocol . '://' . $domain;
140 140
 		}
141 141
 
142 142
 		/**
143 143
 		 * Get the current request query string
144 144
 		 * @return string
145 145
 		 */
146
-		public static function queryString(){
146
+		public static function queryString() {
147 147
 			return get_instance()->request->server('QUERY_STRING');
148 148
 		}
149 149
 	}
Please login to merge, or discard this patch.
core/classes/database/Database.php 2 patches
Indentation   +329 added lines, -329 removed lines patch added patch discarded remove patch
@@ -1,119 +1,119 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
     defined('ROOT_PATH') || exit('Access denied');
3
-  /**
4
-   * TNH Framework
5
-   *
6
-   * A simple PHP framework using HMVC architecture
7
-   *
8
-   * This content is released under the GNU GPL License (GPL)
9
-   *
10
-   * Copyright (C) 2017 Tony NGUEREZA
11
-   *
12
-   * This program is free software; you can redistribute it and/or
13
-   * modify it under the terms of the GNU General Public License
14
-   * as published by the Free Software Foundation; either version 3
15
-   * of the License, or (at your option) any later version.
16
-   *
17
-   * This program is distributed in the hope that it will be useful,
18
-   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-   * GNU General Public License for more details.
21
-   *
22
-   * You should have received a copy of the GNU General Public License
23
-   * along with this program; if not, write to the Free Software
24
-   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-  */
26
-  class Database{
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+    class Database{
27 27
 	
28
-  	/**
29
-  	 * The PDO instance
30
-  	 * @var object
31
-  	*/
28
+        /**
29
+         * The PDO instance
30
+         * @var object
31
+         */
32 32
     private $pdo                 = null;
33 33
     
34
-  	/**
35
-  	 * The database name used for the application
36
-  	 * @var string
37
-  	*/
38
-	  private $databaseName        = null;
34
+        /**
35
+         * The database name used for the application
36
+         * @var string
37
+         */
38
+        private $databaseName        = null;
39 39
 	
40
-  	/**
41
-  	 * The number of rows returned by the last query
42
-  	 * @var int
43
-  	*/
40
+        /**
41
+         * The number of rows returned by the last query
42
+         * @var int
43
+         */
44 44
     private $numRows             = 0;
45 45
 	
46
-  	/**
47
-  	 * The last insert id for the primary key column that have auto increment or sequence
48
-  	 * @var mixed
49
-  	*/
46
+        /**
47
+         * The last insert id for the primary key column that have auto increment or sequence
48
+         * @var mixed
49
+         */
50 50
     private $insertId            = null;
51 51
 	
52
-  	/**
53
-  	 * The full SQL query statment after build for each command
54
-  	 * @var string
55
-  	*/
52
+        /**
53
+         * The full SQL query statment after build for each command
54
+         * @var string
55
+         */
56 56
     private $query               = null;
57 57
 	
58
-  	/**
59
-  	 * The result returned for the last query
60
-  	 * @var mixed
61
-  	*/
58
+        /**
59
+         * The result returned for the last query
60
+         * @var mixed
61
+         */
62 62
     private $result              = array();
63 63
 	
64
-  	/**
65
-  	 * The cache default time to live in second. 0 means no need to use the cache feature
66
-  	 * @var int
67
-  	*/
68
-  	private $cacheTtl             = 0;
64
+        /**
65
+         * The cache default time to live in second. 0 means no need to use the cache feature
66
+         * @var int
67
+         */
68
+        private $cacheTtl             = 0;
69 69
 	
70
-  	/**
71
-  	 * The cache current time to live. 0 means no need to use the cache feature
72
-  	 * @var int
73
-  	*/
70
+        /**
71
+         * The cache current time to live. 0 means no need to use the cache feature
72
+         * @var int
73
+         */
74 74
     private $temporaryCacheTtl   = 0;
75 75
 	
76
-  	/**
77
-  	 * The number of executed query for the current request
78
-  	 * @var int
79
-  	*/
76
+        /**
77
+         * The number of executed query for the current request
78
+         * @var int
79
+         */
80 80
     private $queryCount          = 0;
81 81
 	
82
-  	/**
83
-  	 * The default data to be used in the statments query INSERT, UPDATE
84
-  	 * @var array
85
-  	*/
82
+        /**
83
+         * The default data to be used in the statments query INSERT, UPDATE
84
+         * @var array
85
+         */
86 86
     private $data                = array();
87 87
 	
88
-  	/**
89
-  	 * The database configuration
90
-  	 * @var array
91
-  	*/
88
+        /**
89
+         * The database configuration
90
+         * @var array
91
+         */
92 92
     private $config              = array();
93 93
 	
94
-  	/**
95
-  	 * The logger instance
96
-  	 * @var object
97
-  	 */
94
+        /**
95
+         * The logger instance
96
+         * @var object
97
+         */
98 98
     private $logger              = null;
99 99
 
100 100
     /**
101
-    * The cache instance
102
-    * @var object
103
-    */
101
+     * The cache instance
102
+     * @var object
103
+     */
104 104
     private $cacheInstance       = null;
105 105
 
106 106
     
107
-  	/**
108
-    * The DatabaseQueryBuilder instance
109
-    * @var object
110
-    */
107
+        /**
108
+         * The DatabaseQueryBuilder instance
109
+         * @var object
110
+         */
111 111
     private $queryBuilder        = null;
112 112
     
113 113
     /**
114
-    * The DatabaseQueryRunner instance
115
-    * @var object
116
-    */
114
+     * The DatabaseQueryRunner instance
115
+     * @var object
116
+     */
117 117
     private $queryRunner         = null;
118 118
 
119 119
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
         //Set Log instance to use
126 126
         $this->setLoggerFromParamOrCreateNewInstance(null);
127 127
 		
128
-    		//Set DatabaseQueryBuilder instance to use
129
-    		$this->setQueryBuilderFromParamOrCreateNewInstance(null);
128
+            //Set DatabaseQueryBuilder instance to use
129
+            $this->setQueryBuilderFromParamOrCreateNewInstance(null);
130 130
 
131 131
         //Set DatabaseQueryRunner instance to use
132 132
         $this->setQueryRunnerFromParamOrCreateNewInstance(null);
@@ -143,22 +143,22 @@  discard block
 block discarded – undo
143 143
      * @return bool 
144 144
      */
145 145
     public function connect(){
146
-      $config = $this->getDatabaseConfiguration();
147
-      if (! empty($config)){
146
+        $config = $this->getDatabaseConfiguration();
147
+        if (! empty($config)){
148 148
         try{
149 149
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
150 150
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
151 151
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
152 152
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
153 153
             return true;
154
-          }
155
-          catch (PDOException $e){
154
+            }
155
+            catch (PDOException $e){
156 156
             $this->logger->fatal($e->getMessage());
157 157
             show_error('Cannot connect to Database.');
158 158
             return false;
159
-          }
160
-      }
161
-      return false;
159
+            }
160
+        }
161
+        return false;
162 162
     }
163 163
 
164 164
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
      * @return int
168 168
      */
169 169
     public function numRows(){
170
-      return $this->numRows;
170
+        return $this->numRows;
171 171
     }
172 172
 
173 173
     /**
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
      * @return mixed
176 176
      */
177 177
     public function insertId(){
178
-      return $this->insertId;
178
+        return $this->insertId;
179 179
     }
180 180
 
181 181
 
@@ -186,13 +186,13 @@  discard block
 block discarded – undo
186 186
      * @return mixed       the query SQL string or the record result
187 187
      */
188 188
     public function get($returnSQLQueryOrResultType = false){
189
-      $this->getQueryBuilder()->limit(1);
190
-      $query = $this->getAll(true);
191
-      if ($returnSQLQueryOrResultType === true){
189
+        $this->getQueryBuilder()->limit(1);
190
+        $query = $this->getAll(true);
191
+        if ($returnSQLQueryOrResultType === true){
192 192
         return $query;
193
-      } else {
193
+        } else {
194 194
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
195
-      }
195
+        }
196 196
     }
197 197
 
198 198
     /**
@@ -202,11 +202,11 @@  discard block
 block discarded – undo
202 202
      * @return mixed       the query SQL string or the record result
203 203
      */
204 204
     public function getAll($returnSQLQueryOrResultType = false){
205
-	   $query = $this->getQueryBuilder()->getQuery();
206
-	   if ($returnSQLQueryOrResultType === true){
207
-      	return $query;
208
-      }
209
-      return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
205
+        $query = $this->getQueryBuilder()->getQuery();
206
+        if ($returnSQLQueryOrResultType === true){
207
+            return $query;
208
+        }
209
+        return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
210 210
     }
211 211
 
212 212
     /**
@@ -216,19 +216,19 @@  discard block
 block discarded – undo
216 216
      * @return mixed          the insert id of the new record or null
217 217
      */
218 218
     public function insert($data = array(), $escape = true){
219
-      if (empty($data) && $this->getData()){
219
+        if (empty($data) && $this->getData()){
220 220
         //as when using $this->setData() may be the data already escaped
221 221
         $escape = false;
222 222
         $data = $this->getData();
223
-      }
224
-      $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
225
-      $result = $this->query($query);
226
-      if ($result){
223
+        }
224
+        $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
225
+        $result = $this->query($query);
226
+        if ($result){
227 227
         $this->insertId = $this->pdo->lastInsertId();
228
-		    //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
228
+            //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
229 229
         return ! $this->insertId() ? true : $this->insertId();
230
-      }
231
-      return false;
230
+        }
231
+        return false;
232 232
     }
233 233
 
234 234
     /**
@@ -238,13 +238,13 @@  discard block
 block discarded – undo
238 238
      * @return mixed          the update status
239 239
      */
240 240
     public function update($data = array(), $escape = true){
241
-      if (empty($data) && $this->getData()){
241
+        if (empty($data) && $this->getData()){
242 242
         //as when using $this->setData() may be the data already escaped
243 243
         $escape = false;
244 244
         $data = $this->getData();
245
-      }
246
-      $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
247
-      return $this->query($query);
245
+        }
246
+        $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
247
+        return $this->query($query);
248 248
     }
249 249
 
250 250
     /**
@@ -252,8 +252,8 @@  discard block
 block discarded – undo
252 252
      * @return mixed the delete status
253 253
      */
254 254
     public function delete(){
255
-		$query = $this->getQueryBuilder()->delete()->getQuery();
256
-    	return $this->query($query);
255
+        $query = $this->getQueryBuilder()->delete()->getQuery();
256
+        return $this->query($query);
257 257
     }
258 258
 
259 259
     /**
@@ -262,21 +262,21 @@  discard block
 block discarded – undo
262 262
      * @return object        the current Database instance
263 263
      */
264 264
     public function setCache($ttl = 0){
265
-      if ($ttl > 0){
265
+        if ($ttl > 0){
266 266
         $this->cacheTtl = $ttl;
267 267
         $this->temporaryCacheTtl = $ttl;
268
-      }
269
-      return $this;
268
+        }
269
+        return $this;
270 270
     }
271 271
 	
272
-	/**
273
-	 * Enabled cache temporary for the current query not globally	
274
-	 * @param  integer $ttl the cache time to live in second
275
-	 * @return object        the current Database instance
276
-	 */
277
-  	public function cached($ttl = 0){
272
+    /**
273
+     * Enabled cache temporary for the current query not globally	
274
+     * @param  integer $ttl the cache time to live in second
275
+     * @return object        the current Database instance
276
+     */
277
+        public function cached($ttl = 0){
278 278
         if ($ttl > 0){
279
-          $this->temporaryCacheTtl = $ttl;
279
+            $this->temporaryCacheTtl = $ttl;
280 280
         }
281 281
         return $this;
282 282
     }
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
      * @return mixed       the data after escaped or the same data if not
289 289
      */
290 290
     public function escape($data, $escaped = true){
291
-      return $escaped ? 
291
+        return $escaped ? 
292 292
                       $this->pdo->quote(trim($data)) 
293 293
                       : $data; 
294 294
     }
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
      * @return int
299 299
      */
300 300
     public function queryCount(){
301
-      return $this->queryCount;
301
+        return $this->queryCount;
302 302
     }
303 303
 
304 304
     /**
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
      * @return string
307 307
      */
308 308
     public function getQuery(){
309
-      return $this->query;
309
+        return $this->query;
310 310
     }
311 311
 
312 312
     /**
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
      * @return string
315 315
      */
316 316
     public function getDatabaseName(){
317
-      return $this->databaseName;
317
+        return $this->databaseName;
318 318
     }
319 319
 
320 320
     /**
@@ -322,17 +322,17 @@  discard block
 block discarded – undo
322 322
      * @return object
323 323
      */
324 324
     public function getPdo(){
325
-      return $this->pdo;
325
+        return $this->pdo;
326 326
     }
327 327
 
328 328
     /**
329 329
      * Set the PDO instance
330 330
      * @param object $pdo the pdo object
331
-	 * @return object Database
331
+     * @return object Database
332 332
      */
333 333
     public function setPdo(PDO $pdo){
334
-      $this->pdo = $pdo;
335
-      return $this;
334
+        $this->pdo = $pdo;
335
+        return $this;
336 336
     }
337 337
 
338 338
 
@@ -341,44 +341,44 @@  discard block
 block discarded – undo
341 341
      * @return Log
342 342
      */
343 343
     public function getLogger(){
344
-      return $this->logger;
344
+        return $this->logger;
345 345
     }
346 346
 
347 347
     /**
348 348
      * Set the log instance
349 349
      * @param Log $logger the log object
350
-	 * @return object Database
350
+     * @return object Database
351 351
      */
352 352
     public function setLogger($logger){
353
-      $this->logger = $logger;
354
-      return $this;
353
+        $this->logger = $logger;
354
+        return $this;
355 355
     }
356 356
 
357
-     /**
358
-     * Return the cache instance
359
-     * @return CacheInterface
360
-     */
357
+        /**
358
+         * Return the cache instance
359
+         * @return CacheInterface
360
+         */
361 361
     public function getCacheInstance(){
362
-      return $this->cacheInstance;
362
+        return $this->cacheInstance;
363 363
     }
364 364
 
365 365
     /**
366 366
      * Set the cache instance
367 367
      * @param CacheInterface $cache the cache object
368
-	 * @return object Database
368
+     * @return object Database
369 369
      */
370 370
     public function setCacheInstance($cache){
371
-      $this->cacheInstance = $cache;
372
-      return $this;
371
+        $this->cacheInstance = $cache;
372
+        return $this;
373 373
     }
374 374
 	
375 375
 	
376
-	   /**
377
-     * Return the DatabaseQueryBuilder instance
378
-     * @return object DatabaseQueryBuilder
379
-     */
376
+        /**
377
+         * Return the DatabaseQueryBuilder instance
378
+         * @return object DatabaseQueryBuilder
379
+         */
380 380
     public function getQueryBuilder(){
381
-      return $this->queryBuilder;
381
+        return $this->queryBuilder;
382 382
     }
383 383
 
384 384
     /**
@@ -386,8 +386,8 @@  discard block
 block discarded – undo
386 386
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
387 387
      */
388 388
     public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
389
-      $this->queryBuilder = $queryBuilder;
390
-      return $this;
389
+        $this->queryBuilder = $queryBuilder;
390
+        return $this;
391 391
     }
392 392
     
393 393
     /**
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
      * @return object DatabaseQueryRunner
396 396
      */
397 397
     public function getQueryRunner(){
398
-      return $this->queryRunner;
398
+        return $this->queryRunner;
399 399
     }
400 400
 
401 401
     /**
@@ -403,8 +403,8 @@  discard block
 block discarded – undo
403 403
      * @param object DatabaseQueryRunner $queryRunner the DatabaseQueryRunner object
404 404
      */
405 405
     public function setQueryRunner(DatabaseQueryRunner $queryRunner){
406
-      $this->queryRunner = $queryRunner;
407
-      return $this;
406
+        $this->queryRunner = $queryRunner;
407
+        return $this;
408 408
     }
409 409
 
410 410
     /**
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
      * @return array
413 413
      */
414 414
     public function getData(){
415
-      return $this->data;
415
+        return $this->data;
416 416
     }
417 417
 
418 418
     /**
@@ -423,56 +423,56 @@  discard block
 block discarded – undo
423 423
      * @return object        the current Database instance
424 424
      */
425 425
     public function setData($key, $value = null, $escape = true){
426
-  	  if(is_array($key)){
427
-    		foreach($key as $k => $v){
428
-    			$this->setData($k, $v, $escape);
429
-    		}	
430
-  	  } else {
426
+        if(is_array($key)){
427
+            foreach($key as $k => $v){
428
+                $this->setData($k, $v, $escape);
429
+            }	
430
+        } else {
431 431
         $this->data[$key] = $this->escape($value, $escape);
432
-  	  }
433
-      return $this;
432
+        }
433
+        return $this;
434 434
     }
435 435
 
436
-     /**
437
-     * Execute an SQL query
438
-     * @param  string  $query the query SQL string
439
-     * @param  boolean $returnAsList  indicate whether to return all record or just one row 
440
-     * @param  boolean $returnAsArray return the result as array or not
441
-     * @return mixed         the query result
442
-     */
436
+        /**
437
+         * Execute an SQL query
438
+         * @param  string  $query the query SQL string
439
+         * @param  boolean $returnAsList  indicate whether to return all record or just one row 
440
+         * @param  boolean $returnAsArray return the result as array or not
441
+         * @return mixed         the query result
442
+         */
443 443
     public function query($query, $returnAsList = true, $returnAsArray = false){
444
-      $this->reset();
445
-      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
446
-      //If is the SELECT query
447
-      $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
444
+        $this->reset();
445
+        $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
446
+        //If is the SELECT query
447
+        $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
448 448
 
449
-      //cache expire time
450
-      $cacheExpire = $this->temporaryCacheTtl;
449
+        //cache expire time
450
+        $cacheExpire = $this->temporaryCacheTtl;
451 451
       
452
-      //return to the initial cache time
453
-      $this->temporaryCacheTtl = $this->cacheTtl;
452
+        //return to the initial cache time
453
+        $this->temporaryCacheTtl = $this->cacheTtl;
454 454
       
455
-      //config for cache
456
-      $cacheEnable = get_config('cache_enable');
455
+        //config for cache
456
+        $cacheEnable = get_config('cache_enable');
457 457
       
458
-      //the database cache content
459
-      $cacheContent = null;
458
+        //the database cache content
459
+        $cacheContent = null;
460 460
 
461
-      //if can use cache feature for this query
462
-      $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
461
+        //if can use cache feature for this query
462
+        $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
463 463
     
464
-      if ($dbCacheStatus && $isSqlSELECTQuery){
465
-          $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
466
-          $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
467
-      }
464
+        if ($dbCacheStatus && $isSqlSELECTQuery){
465
+            $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
466
+            $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
467
+        }
468 468
       
469
-      if ( !$cacheContent){
470
-  	   	//count the number of query execution to server
469
+        if ( !$cacheContent){
470
+                //count the number of query execution to server
471 471
         $this->queryCount++;
472 472
         
473 473
         $this->queryRunner->setQuery($query)
474
-                          ->setReturnType($returnAsList)
475
-                          ->setReturnAsArray($returnAsArray);
474
+                            ->setReturnType($returnAsList)
475
+                            ->setReturnAsArray($returnAsArray);
476 476
         
477 477
         $queryResult = $this->queryRunner->execute();
478 478
         if (is_object($queryResult)){
@@ -482,33 +482,33 @@  discard block
 block discarded – undo
482 482
                 $key = $this->getCacheKeyForQuery($this->query, $returnAsList, $returnAsArray);
483 483
                 $this->setCacheContentForQuery($this->query, $key, $this->result, $cacheExpire);
484 484
             if (! $this->result){
485
-              $this->logger->info('No result where found for the query [' . $query . ']');
485
+                $this->logger->info('No result where found for the query [' . $query . ']');
486 486
             }
487
-          }
487
+            }
488
+        }
489
+        } else if ($isSqlSELECTQuery){
490
+            $this->logger->info('The result for query [' .$this->query. '] already cached use it');
491
+            $this->result = $cacheContent;
492
+            $this->numRows = count($this->result);
488 493
         }
489
-      } else if ($isSqlSELECTQuery){
490
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
491
-          $this->result = $cacheContent;
492
-          $this->numRows = count($this->result);
493
-      }
494
-      return $this->result;
494
+        return $this->result;
495 495
     }
496 496
 	
497 497
 	
498
-	 /**
499
-	 * Return the database configuration
500
-	 * @return array
501
-	 */
502
-  	public  function getDatabaseConfiguration(){
503
-  	  return $this->config;
504
-  	}
505
-
506
-   /**
507
-    * Setting the database configuration using the configuration file and additional configuration from param
508
-    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
509
-    * @param boolean $useConfigFile whether to use database configuration file
510
-	  * @return object Database
511
-    */
498
+        /**
499
+         * Return the database configuration
500
+         * @return array
501
+         */
502
+        public  function getDatabaseConfiguration(){
503
+        return $this->config;
504
+        }
505
+
506
+    /**
507
+     * Setting the database configuration using the configuration file and additional configuration from param
508
+     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
509
+     * @param boolean $useConfigFile whether to use database configuration file
510
+     * @return object Database
511
+     */
512 512
     public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
513 513
         $db = array();
514 514
         if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
@@ -521,50 +521,50 @@  discard block
 block discarded – undo
521 521
         
522 522
         //default configuration
523 523
         $config = array(
524
-          'driver' => 'mysql',
525
-          'username' => 'root',
526
-          'password' => '',
527
-          'database' => '',
528
-          'hostname' => 'localhost',
529
-          'charset' => 'utf8',
530
-          'collation' => 'utf8_general_ci',
531
-          'prefix' => '',
532
-          'port' => ''
524
+            'driver' => 'mysql',
525
+            'username' => 'root',
526
+            'password' => '',
527
+            'database' => '',
528
+            'hostname' => 'localhost',
529
+            'charset' => 'utf8',
530
+            'collation' => 'utf8_general_ci',
531
+            'prefix' => '',
532
+            'port' => ''
533 533
         );
534 534
 		
535
-    	$config = array_merge($config, $db);
536
-    	//determine the port using the hostname like localhost:3307
537
-      //hostname will be "localhost", and port "3307"
538
-      $p = explode(':', $config['hostname']);
539
-  	  if (count($p) >= 2){
540
-  		  $config['hostname'] = $p[0];
541
-  		  $config['port'] = $p[1];
542
-  		}
535
+        $config = array_merge($config, $db);
536
+        //determine the port using the hostname like localhost:3307
537
+        //hostname will be "localhost", and port "3307"
538
+        $p = explode(':', $config['hostname']);
539
+        if (count($p) >= 2){
540
+            $config['hostname'] = $p[0];
541
+            $config['port'] = $p[1];
542
+            }
543 543
 		
544
-		 $this->databaseName = $config['database'];
545
-		 $this->config = $config;
546
-		 $this->logger->info(
547
-								'The database configuration are listed below: ' 
548
-								. stringfy_vars(array_merge(
549
-															$this->config, 
550
-															array('password' => string_hidden($this->config['password']))
551
-												))
552
-							);
544
+            $this->databaseName = $config['database'];
545
+            $this->config = $config;
546
+            $this->logger->info(
547
+                                'The database configuration are listed below: ' 
548
+                                . stringfy_vars(array_merge(
549
+                                                            $this->config, 
550
+                                                            array('password' => string_hidden($this->config['password']))
551
+                                                ))
552
+                            );
553 553
 	  
554
-		 //Now connect to the database
555
-		 $this->connect();
554
+            //Now connect to the database
555
+            $this->connect();
556 556
 		 
557
-     //do update of QueryRunner and Builder
558
-     $this->updateQueryBuilderAndRunnerProperties();
557
+        //do update of QueryRunner and Builder
558
+        $this->updateQueryBuilderAndRunnerProperties();
559 559
 
560
-		 return $this;
560
+            return $this;
561 561
     }
562 562
 
563 563
     /**
564 564
      * Close the connexion
565 565
      */
566 566
     public function close(){
567
-      $this->pdo = null;
567
+        $this->pdo = null;
568 568
     }
569 569
 
570 570
     /**
@@ -572,18 +572,18 @@  discard block
 block discarded – undo
572 572
      * @return void
573 573
      */
574 574
     protected function updateQueryBuilderAndRunnerProperties(){
575
-       //update queryBuilder with some properties needed
576
-     if(is_object($this->queryBuilder)){
575
+        //update queryBuilder with some properties needed
576
+        if(is_object($this->queryBuilder)){
577 577
         $this->queryBuilder->setDriver($this->config['driver'])
578
-                           ->setPrefix($this->config['prefix'])
579
-                           ->setPdo($this->pdo);
580
-     }
578
+                            ->setPrefix($this->config['prefix'])
579
+                            ->setPdo($this->pdo);
580
+        }
581 581
 
582
-      //update queryRunner with some properties needed
583
-     if(is_object($this->queryRunner)){
582
+        //update queryRunner with some properties needed
583
+        if(is_object($this->queryRunner)){
584 584
         $this->queryRunner->setDriver($this->config['driver'])
585
-                          ->setPdo($this->pdo);
586
-     }
585
+                            ->setPdo($this->pdo);
586
+        }
587 587
     }
588 588
 	
589 589
 
@@ -592,24 +592,24 @@  discard block
 block discarded – undo
592 592
      * @return string the DSN string
593 593
      */
594 594
     protected function getDsnFromDriver(){
595
-      $config = $this->getDatabaseConfiguration();
596
-      if (! empty($config)){
595
+        $config = $this->getDatabaseConfiguration();
596
+        if (! empty($config)){
597 597
         $driver = $config['driver'];
598 598
         $driverDsnMap = array(
599
-                              'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
600
-                                          . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
601
-                                          . 'dbname=' . $config['database'],
602
-                              'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
603
-                                          . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
604
-                                          . 'dbname=' . $config['database'],
605
-                              'sqlite' => 'sqlite:' . $config['database'],
606
-                              'oracle' => 'oci:dbname=' . $config['hostname'] 
599
+                                'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
600
+                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
601
+                                            . 'dbname=' . $config['database'],
602
+                                'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
603
+                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
604
+                                            . 'dbname=' . $config['database'],
605
+                                'sqlite' => 'sqlite:' . $config['database'],
606
+                                'oracle' => 'oci:dbname=' . $config['hostname'] 
607 607
                                             . (($config['port']) != '' ? ':' . $config['port'] : '')
608 608
                                             . '/' . $config['database']
609
-                              );
609
+                                );
610 610
         return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : '';
611
-      }                   
612
-      return null;
611
+        }                   
612
+        return null;
613 613
     }
614 614
 
615 615
     /**
@@ -621,11 +621,11 @@  discard block
 block discarded – undo
621 621
     protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray){
622 622
         $cacheKey = $this->getCacheKeyForQuery($query, $returnAsList, $returnAsArray);
623 623
         if (! is_object($this->cacheInstance)){
624
-    			//can not call method with reference in argument
625
-    			//like $this->setCacheInstance(& get_instance()->cache);
626
-    			//use temporary variable
627
-    			$instance = & get_instance()->cache;
628
-    			$this->cacheInstance = $instance;
624
+                //can not call method with reference in argument
625
+                //like $this->setCacheInstance(& get_instance()->cache);
626
+                //use temporary variable
627
+                $instance = & get_instance()->cache;
628
+                $this->cacheInstance = $instance;
629 629
         }
630 630
         return $this->cacheInstance->get($cacheKey);
631 631
     }
@@ -637,87 +637,87 @@  discard block
 block discarded – undo
637 637
      * @param mixed $result the query result to save
638 638
      * @param int $expire the cache TTL
639 639
      */
640
-     protected function setCacheContentForQuery($query, $key, $result, $expire){
640
+        protected function setCacheContentForQuery($query, $key, $result, $expire){
641 641
         $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
642 642
         if (! is_object($this->cacheInstance)){
643
-  				//can not call method with reference in argument
644
-  				//like $this->setCacheInstance(& get_instance()->cache);
645
-  				//use temporary variable
646
-  				$instance = & get_instance()->cache;
647
-  				$this->cacheInstance = $instance;
648
-  			}
643
+                    //can not call method with reference in argument
644
+                    //like $this->setCacheInstance(& get_instance()->cache);
645
+                    //use temporary variable
646
+                    $instance = & get_instance()->cache;
647
+                    $this->cacheInstance = $instance;
648
+                }
649 649
         $this->cacheInstance->set($key, $result, $expire);
650
-     }
650
+        }
651 651
 
652 652
     
653
-	 /**
654
-     * Return the cache key for the given query
655
-     * @see Database::query
656
-     * 
657
-     *  @return string
658
-     */
653
+        /**
654
+         * Return the cache key for the given query
655
+         * @see Database::query
656
+         * 
657
+         *  @return string
658
+         */
659 659
     protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray){
660
-      return md5($query . $returnAsList . $returnAsArray);
660
+        return md5($query . $returnAsList . $returnAsArray);
661 661
     }
662 662
     
663
-	   /**
664
-     * Set the Log instance using argument or create new instance
665
-     * @param object $logger the Log instance if not null
666
-     */
663
+        /**
664
+         * Set the Log instance using argument or create new instance
665
+         * @param object $logger the Log instance if not null
666
+         */
667 667
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
668
-      if ($logger !== null){
668
+        if ($logger !== null){
669 669
         $this->logger = $logger;
670
-      }
671
-      else{
672
-          $this->logger =& class_loader('Log', 'classes');
673
-          $this->logger->setLogger('Library::Database');
674
-      }
670
+        }
671
+        else{
672
+            $this->logger =& class_loader('Log', 'classes');
673
+            $this->logger->setLogger('Library::Database');
674
+        }
675 675
     }
676 676
 	
677
-   /**
678
-   * Set the DatabaseQueryBuilder instance using argument or create new instance
679
-   * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
680
-   */
681
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
682
-	  if ($queryBuilder !== null){
677
+    /**
678
+     * Set the DatabaseQueryBuilder instance using argument or create new instance
679
+     * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
680
+     */
681
+    protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
682
+        if ($queryBuilder !== null){
683 683
         $this->queryBuilder = $queryBuilder;
684
-	  }
685
-	  else{
686
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
687
-	  }
688
-	}
689
-
690
-  /**
691
-   * Set the DatabaseQueryRunner instance using argument or create new instance
692
-   * @param object $queryRunner the DatabaseQueryRunner instance if not null
693
-   */
694
-  protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
684
+        }
685
+        else{
686
+            $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
687
+        }
688
+    }
689
+
690
+    /**
691
+     * Set the DatabaseQueryRunner instance using argument or create new instance
692
+     * @param object $queryRunner the DatabaseQueryRunner instance if not null
693
+     */
694
+    protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
695 695
     if ($queryRunner !== null){
696 696
         $this->queryRunner = $queryRunner;
697 697
     }
698 698
     else{
699
-      $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
699
+        $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
700
+    }
700 701
     }
701
-  }
702 702
 
703 703
     /**
704 704
      * Reset the database class attributs to the initail values before each query.
705 705
      */
706 706
     private function reset(){
707
-	   //query builder reset
708
-      $this->getQueryBuilder()->reset();
709
-      $this->numRows  = 0;
710
-      $this->insertId = null;
711
-      $this->query    = null;
712
-      $this->result   = array();
713
-      $this->data     = array();
707
+        //query builder reset
708
+        $this->getQueryBuilder()->reset();
709
+        $this->numRows  = 0;
710
+        $this->insertId = null;
711
+        $this->query    = null;
712
+        $this->result   = array();
713
+        $this->data     = array();
714 714
     }
715 715
 
716 716
     /**
717 717
      * The class destructor
718 718
      */
719 719
     public function __destruct(){
720
-      $this->pdo = null;
720
+        $this->pdo = null;
721 721
     }
722 722
 
723 723
 }
Please login to merge, or discard this patch.
Spacing   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -23,105 +23,105 @@  discard block
 block discarded – undo
23 23
    * along with this program; if not, write to the Free Software
24 24
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
   */
26
-  class Database{
26
+  class Database {
27 27
 	
28 28
   	/**
29 29
   	 * The PDO instance
30 30
   	 * @var object
31 31
   	*/
32
-    private $pdo                 = null;
32
+    private $pdo = null;
33 33
     
34 34
   	/**
35 35
   	 * The database name used for the application
36 36
   	 * @var string
37 37
   	*/
38
-	  private $databaseName        = null;
38
+	  private $databaseName = null;
39 39
 	
40 40
   	/**
41 41
   	 * The number of rows returned by the last query
42 42
   	 * @var int
43 43
   	*/
44
-    private $numRows             = 0;
44
+    private $numRows = 0;
45 45
 	
46 46
   	/**
47 47
   	 * The last insert id for the primary key column that have auto increment or sequence
48 48
   	 * @var mixed
49 49
   	*/
50
-    private $insertId            = null;
50
+    private $insertId = null;
51 51
 	
52 52
   	/**
53 53
   	 * The full SQL query statment after build for each command
54 54
   	 * @var string
55 55
   	*/
56
-    private $query               = null;
56
+    private $query = null;
57 57
 	
58 58
   	/**
59 59
   	 * The result returned for the last query
60 60
   	 * @var mixed
61 61
   	*/
62
-    private $result              = array();
62
+    private $result = array();
63 63
 	
64 64
   	/**
65 65
   	 * The cache default time to live in second. 0 means no need to use the cache feature
66 66
   	 * @var int
67 67
   	*/
68
-  	private $cacheTtl             = 0;
68
+  	private $cacheTtl = 0;
69 69
 	
70 70
   	/**
71 71
   	 * The cache current time to live. 0 means no need to use the cache feature
72 72
   	 * @var int
73 73
   	*/
74
-    private $temporaryCacheTtl   = 0;
74
+    private $temporaryCacheTtl = 0;
75 75
 	
76 76
   	/**
77 77
   	 * The number of executed query for the current request
78 78
   	 * @var int
79 79
   	*/
80
-    private $queryCount          = 0;
80
+    private $queryCount = 0;
81 81
 	
82 82
   	/**
83 83
   	 * The default data to be used in the statments query INSERT, UPDATE
84 84
   	 * @var array
85 85
   	*/
86
-    private $data                = array();
86
+    private $data = array();
87 87
 	
88 88
   	/**
89 89
   	 * The database configuration
90 90
   	 * @var array
91 91
   	*/
92
-    private $config              = array();
92
+    private $config = array();
93 93
 	
94 94
   	/**
95 95
   	 * The logger instance
96 96
   	 * @var object
97 97
   	 */
98
-    private $logger              = null;
98
+    private $logger = null;
99 99
 
100 100
     /**
101 101
     * The cache instance
102 102
     * @var object
103 103
     */
104
-    private $cacheInstance       = null;
104
+    private $cacheInstance = null;
105 105
 
106 106
     
107 107
   	/**
108 108
     * The DatabaseQueryBuilder instance
109 109
     * @var object
110 110
     */
111
-    private $queryBuilder        = null;
111
+    private $queryBuilder = null;
112 112
     
113 113
     /**
114 114
     * The DatabaseQueryRunner instance
115 115
     * @var object
116 116
     */
117
-    private $queryRunner         = null;
117
+    private $queryRunner = null;
118 118
 
119 119
 
120 120
     /**
121 121
      * Construct new database
122 122
      * @param array $overwriteConfig the config to overwrite with the config set in database.php
123 123
      */
124
-    public function __construct($overwriteConfig = array()){
124
+    public function __construct($overwriteConfig = array()) {
125 125
         //Set Log instance to use
126 126
         $this->setLoggerFromParamOrCreateNewInstance(null);
127 127
 		
@@ -142,17 +142,17 @@  discard block
 block discarded – undo
142 142
      * This is used to connect to database
143 143
      * @return bool 
144 144
      */
145
-    public function connect(){
145
+    public function connect() {
146 146
       $config = $this->getDatabaseConfiguration();
147
-      if (! empty($config)){
148
-        try{
147
+      if (!empty($config)) {
148
+        try {
149 149
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
150 150
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
151 151
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
152 152
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
153 153
             return true;
154 154
           }
155
-          catch (PDOException $e){
155
+          catch (PDOException $e) {
156 156
             $this->logger->fatal($e->getMessage());
157 157
             show_error('Cannot connect to Database.');
158 158
             return false;
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
      * Return the number of rows returned by the current query
167 167
      * @return int
168 168
      */
169
-    public function numRows(){
169
+    public function numRows() {
170 170
       return $this->numRows;
171 171
     }
172 172
 
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
      * Return the last insert id value
175 175
      * @return mixed
176 176
      */
177
-    public function insertId(){
177
+    public function insertId() {
178 178
       return $this->insertId;
179 179
     }
180 180
 
@@ -185,10 +185,10 @@  discard block
 block discarded – undo
185 185
      * If is string will determine the result type "array" or "object"
186 186
      * @return mixed       the query SQL string or the record result
187 187
      */
188
-    public function get($returnSQLQueryOrResultType = false){
188
+    public function get($returnSQLQueryOrResultType = false) {
189 189
       $this->getQueryBuilder()->limit(1);
190 190
       $query = $this->getAll(true);
191
-      if ($returnSQLQueryOrResultType === true){
191
+      if ($returnSQLQueryOrResultType === true) {
192 192
         return $query;
193 193
       } else {
194 194
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
@@ -201,9 +201,9 @@  discard block
 block discarded – undo
201 201
      * If is string will determine the result type "array" or "object"
202 202
      * @return mixed       the query SQL string or the record result
203 203
      */
204
-    public function getAll($returnSQLQueryOrResultType = false){
204
+    public function getAll($returnSQLQueryOrResultType = false) {
205 205
 	   $query = $this->getQueryBuilder()->getQuery();
206
-	   if ($returnSQLQueryOrResultType === true){
206
+	   if ($returnSQLQueryOrResultType === true) {
207 207
       	return $query;
208 208
       }
209 209
       return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
      * @param  boolean $escape  whether to escape or not the values
216 216
      * @return mixed          the insert id of the new record or null
217 217
      */
218
-    public function insert($data = array(), $escape = true){
219
-      if (empty($data) && $this->getData()){
218
+    public function insert($data = array(), $escape = true) {
219
+      if (empty($data) && $this->getData()) {
220 220
         //as when using $this->setData() may be the data already escaped
221 221
         $escape = false;
222 222
         $data = $this->getData();
223 223
       }
224 224
       $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
225 225
       $result = $this->query($query);
226
-      if ($result){
226
+      if ($result) {
227 227
         $this->insertId = $this->pdo->lastInsertId();
228 228
 		    //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
229
-        return ! $this->insertId() ? true : $this->insertId();
229
+        return !$this->insertId() ? true : $this->insertId();
230 230
       }
231 231
       return false;
232 232
     }
@@ -237,8 +237,8 @@  discard block
 block discarded – undo
237 237
      * @param  boolean $escape  whether to escape or not the values
238 238
      * @return mixed          the update status
239 239
      */
240
-    public function update($data = array(), $escape = true){
241
-      if (empty($data) && $this->getData()){
240
+    public function update($data = array(), $escape = true) {
241
+      if (empty($data) && $this->getData()) {
242 242
         //as when using $this->setData() may be the data already escaped
243 243
         $escape = false;
244 244
         $data = $this->getData();
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
      * Delete the record in database
252 252
      * @return mixed the delete status
253 253
      */
254
-    public function delete(){
254
+    public function delete() {
255 255
 		$query = $this->getQueryBuilder()->delete()->getQuery();
256 256
     	return $this->query($query);
257 257
     }
@@ -261,8 +261,8 @@  discard block
 block discarded – undo
261 261
      * @param integer $ttl the cache time to live in second
262 262
      * @return object        the current Database instance
263 263
      */
264
-    public function setCache($ttl = 0){
265
-      if ($ttl > 0){
264
+    public function setCache($ttl = 0) {
265
+      if ($ttl > 0) {
266 266
         $this->cacheTtl = $ttl;
267 267
         $this->temporaryCacheTtl = $ttl;
268 268
       }
@@ -274,8 +274,8 @@  discard block
 block discarded – undo
274 274
 	 * @param  integer $ttl the cache time to live in second
275 275
 	 * @return object        the current Database instance
276 276
 	 */
277
-  	public function cached($ttl = 0){
278
-        if ($ttl > 0){
277
+  	public function cached($ttl = 0) {
278
+        if ($ttl > 0) {
279 279
           $this->temporaryCacheTtl = $ttl;
280 280
         }
281 281
         return $this;
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
      * @param boolean $escaped whether we can do escape of not 
288 288
      * @return mixed       the data after escaped or the same data if not
289 289
      */
290
-    public function escape($data, $escaped = true){
290
+    public function escape($data, $escaped = true) {
291 291
       return $escaped ? 
292 292
                       $this->pdo->quote(trim($data)) 
293 293
                       : $data; 
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
      * Return the number query executed count for the current request
298 298
      * @return int
299 299
      */
300
-    public function queryCount(){
300
+    public function queryCount() {
301 301
       return $this->queryCount;
302 302
     }
303 303
 
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
      * Return the current query SQL string
306 306
      * @return string
307 307
      */
308
-    public function getQuery(){
308
+    public function getQuery() {
309 309
       return $this->query;
310 310
     }
311 311
 
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
      * Return the application database name
314 314
      * @return string
315 315
      */
316
-    public function getDatabaseName(){
316
+    public function getDatabaseName() {
317 317
       return $this->databaseName;
318 318
     }
319 319
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
      * Return the PDO instance
322 322
      * @return object
323 323
      */
324
-    public function getPdo(){
324
+    public function getPdo() {
325 325
       return $this->pdo;
326 326
     }
327 327
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
      * @param object $pdo the pdo object
331 331
 	 * @return object Database
332 332
      */
333
-    public function setPdo(PDO $pdo){
333
+    public function setPdo(PDO $pdo) {
334 334
       $this->pdo = $pdo;
335 335
       return $this;
336 336
     }
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
      * Return the Log instance
341 341
      * @return Log
342 342
      */
343
-    public function getLogger(){
343
+    public function getLogger() {
344 344
       return $this->logger;
345 345
     }
346 346
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
      * @param Log $logger the log object
350 350
 	 * @return object Database
351 351
      */
352
-    public function setLogger($logger){
352
+    public function setLogger($logger) {
353 353
       $this->logger = $logger;
354 354
       return $this;
355 355
     }
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
      * Return the cache instance
359 359
      * @return CacheInterface
360 360
      */
361
-    public function getCacheInstance(){
361
+    public function getCacheInstance() {
362 362
       return $this->cacheInstance;
363 363
     }
364 364
 
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
      * @param CacheInterface $cache the cache object
368 368
 	 * @return object Database
369 369
      */
370
-    public function setCacheInstance($cache){
370
+    public function setCacheInstance($cache) {
371 371
       $this->cacheInstance = $cache;
372 372
       return $this;
373 373
     }
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
      * Return the DatabaseQueryBuilder instance
378 378
      * @return object DatabaseQueryBuilder
379 379
      */
380
-    public function getQueryBuilder(){
380
+    public function getQueryBuilder() {
381 381
       return $this->queryBuilder;
382 382
     }
383 383
 
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
      * Set the DatabaseQueryBuilder instance
386 386
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
387 387
      */
388
-    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
388
+    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder) {
389 389
       $this->queryBuilder = $queryBuilder;
390 390
       return $this;
391 391
     }
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
      * Return the DatabaseQueryRunner instance
395 395
      * @return object DatabaseQueryRunner
396 396
      */
397
-    public function getQueryRunner(){
397
+    public function getQueryRunner() {
398 398
       return $this->queryRunner;
399 399
     }
400 400
 
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
      * Set the DatabaseQueryRunner instance
403 403
      * @param object DatabaseQueryRunner $queryRunner the DatabaseQueryRunner object
404 404
      */
405
-    public function setQueryRunner(DatabaseQueryRunner $queryRunner){
405
+    public function setQueryRunner(DatabaseQueryRunner $queryRunner) {
406 406
       $this->queryRunner = $queryRunner;
407 407
       return $this;
408 408
     }
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
      * Return the data to be used for insert, update, etc.
412 412
      * @return array
413 413
      */
414
-    public function getData(){
414
+    public function getData() {
415 415
       return $this->data;
416 416
     }
417 417
 
@@ -422,9 +422,9 @@  discard block
 block discarded – undo
422 422
      * @param boolean $escape whether to escape or not the $value
423 423
      * @return object        the current Database instance
424 424
      */
425
-    public function setData($key, $value = null, $escape = true){
426
-  	  if(is_array($key)){
427
-    		foreach($key as $k => $v){
425
+    public function setData($key, $value = null, $escape = true) {
426
+  	  if (is_array($key)) {
427
+    		foreach ($key as $k => $v) {
428 428
     			$this->setData($k, $v, $escape);
429 429
     		}	
430 430
   	  } else {
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
      * @param  boolean $returnAsArray return the result as array or not
441 441
      * @return mixed         the query result
442 442
      */
443
-    public function query($query, $returnAsList = true, $returnAsArray = false){
443
+    public function query($query, $returnAsList = true, $returnAsArray = false) {
444 444
       $this->reset();
445 445
       $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
446 446
       //If is the SELECT query
@@ -461,12 +461,12 @@  discard block
 block discarded – undo
461 461
       //if can use cache feature for this query
462 462
       $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
463 463
     
464
-      if ($dbCacheStatus && $isSqlSELECTQuery){
464
+      if ($dbCacheStatus && $isSqlSELECTQuery) {
465 465
           $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
466 466
           $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
467 467
       }
468 468
       
469
-      if ( !$cacheContent){
469
+      if (!$cacheContent) {
470 470
   	   	//count the number of query execution to server
471 471
         $this->queryCount++;
472 472
         
@@ -475,19 +475,19 @@  discard block
 block discarded – undo
475 475
                           ->setReturnAsArray($returnAsArray);
476 476
         
477 477
         $queryResult = $this->queryRunner->execute();
478
-        if (is_object($queryResult)){
478
+        if (is_object($queryResult)) {
479 479
             $this->result  = $queryResult->getResult();
480 480
             $this->numRows = $queryResult->getNumRows();
481
-            if ($isSqlSELECTQuery && $dbCacheStatus){
481
+            if ($isSqlSELECTQuery && $dbCacheStatus) {
482 482
                 $key = $this->getCacheKeyForQuery($this->query, $returnAsList, $returnAsArray);
483 483
                 $this->setCacheContentForQuery($this->query, $key, $this->result, $cacheExpire);
484
-            if (! $this->result){
484
+            if (!$this->result) {
485 485
               $this->logger->info('No result where found for the query [' . $query . ']');
486 486
             }
487 487
           }
488 488
         }
489
-      } else if ($isSqlSELECTQuery){
490
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
489
+      } else if ($isSqlSELECTQuery) {
490
+          $this->logger->info('The result for query [' . $this->query . '] already cached use it');
491 491
           $this->result = $cacheContent;
492 492
           $this->numRows = count($this->result);
493 493
       }
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 	 * Return the database configuration
500 500
 	 * @return array
501 501
 	 */
502
-  	public  function getDatabaseConfiguration(){
502
+  	public  function getDatabaseConfiguration() {
503 503
   	  return $this->config;
504 504
   	}
505 505
 
@@ -509,9 +509,9 @@  discard block
 block discarded – undo
509 509
     * @param boolean $useConfigFile whether to use database configuration file
510 510
 	  * @return object Database
511 511
     */
512
-    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
512
+    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
513 513
         $db = array();
514
-        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
514
+        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')) {
515 515
             //here don't use require_once because somewhere user can create database instance directly
516 516
             require CONFIG_PATH . 'database.php';
517 517
         }
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
     	//determine the port using the hostname like localhost:3307
537 537
       //hostname will be "localhost", and port "3307"
538 538
       $p = explode(':', $config['hostname']);
539
-  	  if (count($p) >= 2){
539
+  	  if (count($p) >= 2) {
540 540
   		  $config['hostname'] = $p[0];
541 541
   		  $config['port'] = $p[1];
542 542
   		}
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
     /**
564 564
      * Close the connexion
565 565
      */
566
-    public function close(){
566
+    public function close() {
567 567
       $this->pdo = null;
568 568
     }
569 569
 
@@ -571,16 +571,16 @@  discard block
 block discarded – undo
571 571
      * Update the DatabaseQueryBuilder and DatabaseQueryRunner properties
572 572
      * @return void
573 573
      */
574
-    protected function updateQueryBuilderAndRunnerProperties(){
574
+    protected function updateQueryBuilderAndRunnerProperties() {
575 575
        //update queryBuilder with some properties needed
576
-     if(is_object($this->queryBuilder)){
576
+     if (is_object($this->queryBuilder)) {
577 577
         $this->queryBuilder->setDriver($this->config['driver'])
578 578
                            ->setPrefix($this->config['prefix'])
579 579
                            ->setPdo($this->pdo);
580 580
      }
581 581
 
582 582
       //update queryRunner with some properties needed
583
-     if(is_object($this->queryRunner)){
583
+     if (is_object($this->queryRunner)) {
584 584
         $this->queryRunner->setDriver($this->config['driver'])
585 585
                           ->setPdo($this->pdo);
586 586
      }
@@ -591,9 +591,9 @@  discard block
 block discarded – undo
591 591
      * This method is used to get the PDO DSN string using the configured driver
592 592
      * @return string the DSN string
593 593
      */
594
-    protected function getDsnFromDriver(){
594
+    protected function getDsnFromDriver() {
595 595
       $config = $this->getDatabaseConfiguration();
596
-      if (! empty($config)){
596
+      if (!empty($config)) {
597 597
         $driver = $config['driver'];
598 598
         $driverDsnMap = array(
599 599
                               'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
@@ -618,9 +618,9 @@  discard block
 block discarded – undo
618 618
      *      
619 619
      * @return mixed
620 620
      */
621
-    protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray){
621
+    protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray) {
622 622
         $cacheKey = $this->getCacheKeyForQuery($query, $returnAsList, $returnAsArray);
623
-        if (! is_object($this->cacheInstance)){
623
+        if (!is_object($this->cacheInstance)) {
624 624
     			//can not call method with reference in argument
625 625
     			//like $this->setCacheInstance(& get_instance()->cache);
626 626
     			//use temporary variable
@@ -637,9 +637,9 @@  discard block
 block discarded – undo
637 637
      * @param mixed $result the query result to save
638 638
      * @param int $expire the cache TTL
639 639
      */
640
-     protected function setCacheContentForQuery($query, $key, $result, $expire){
641
-        $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
642
-        if (! is_object($this->cacheInstance)){
640
+     protected function setCacheContentForQuery($query, $key, $result, $expire) {
641
+        $this->logger->info('Save the result for query [' . $query . '] into cache for future use');
642
+        if (!is_object($this->cacheInstance)) {
643 643
   				//can not call method with reference in argument
644 644
   				//like $this->setCacheInstance(& get_instance()->cache);
645 645
   				//use temporary variable
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
      * 
657 657
      *  @return string
658 658
      */
659
-    protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray){
659
+    protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray) {
660 660
       return md5($query . $returnAsList . $returnAsArray);
661 661
     }
662 662
     
@@ -664,12 +664,12 @@  discard block
 block discarded – undo
664 664
      * Set the Log instance using argument or create new instance
665 665
      * @param object $logger the Log instance if not null
666 666
      */
667
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
668
-      if ($logger !== null){
667
+    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
668
+      if ($logger !== null) {
669 669
         $this->logger = $logger;
670 670
       }
671
-      else{
672
-          $this->logger =& class_loader('Log', 'classes');
671
+      else {
672
+          $this->logger = & class_loader('Log', 'classes');
673 673
           $this->logger->setLogger('Library::Database');
674 674
       }
675 675
     }
@@ -678,12 +678,12 @@  discard block
 block discarded – undo
678 678
    * Set the DatabaseQueryBuilder instance using argument or create new instance
679 679
    * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
680 680
    */
681
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
682
-	  if ($queryBuilder !== null){
681
+	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null) {
682
+	  if ($queryBuilder !== null) {
683 683
         $this->queryBuilder = $queryBuilder;
684 684
 	  }
685
-	  else{
686
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
685
+	  else {
686
+		  $this->queryBuilder = & class_loader('DatabaseQueryBuilder', 'classes/database');
687 687
 	  }
688 688
 	}
689 689
 
@@ -691,19 +691,19 @@  discard block
 block discarded – undo
691 691
    * Set the DatabaseQueryRunner instance using argument or create new instance
692 692
    * @param object $queryRunner the DatabaseQueryRunner instance if not null
693 693
    */
694
-  protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
695
-    if ($queryRunner !== null){
694
+  protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null) {
695
+    if ($queryRunner !== null) {
696 696
         $this->queryRunner = $queryRunner;
697 697
     }
698
-    else{
699
-      $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
698
+    else {
699
+      $this->queryRunner = & class_loader('DatabaseQueryRunner', 'classes/database');
700 700
     }
701 701
   }
702 702
 
703 703
     /**
704 704
      * Reset the database class attributs to the initail values before each query.
705 705
      */
706
-    private function reset(){
706
+    private function reset() {
707 707
 	   //query builder reset
708 708
       $this->getQueryBuilder()->reset();
709 709
       $this->numRows  = 0;
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
     /**
717 717
      * The class destructor
718 718
      */
719
-    public function __destruct(){
719
+    public function __destruct() {
720 720
       $this->pdo = null;
721 721
     }
722 722
 
Please login to merge, or discard this patch.
core/classes/Router.php 3 patches
Indentation   +608 added lines, -608 removed lines patch added patch discarded remove patch
@@ -1,622 +1,622 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
26
-
27
-	class Router {
28
-		/**
29
-		* @var array $pattern: The list of URIs to validate against
30
-		*/
31
-		private $pattern = array();
32
-
33
-		/**
34
-		* @var array $callback: The list of callback to call
35
-		*/
36
-		private $callback = array();
37
-
38
-		/**
39
-		* @var string $uriTrim: The char to remove from the URIs
40
-		*/
41
-		protected $uriTrim = '/\^$';
42
-
43
-		/**
44
-		* @var string $uri: The route URI to use
45
-		*/
46
-		protected $uri = '';
47
-
48
-		/**
49
-		 * The module name of the current request
50
-		 * @var string
51
-		 */
52
-		protected $module = null;
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26
+
27
+    class Router {
28
+        /**
29
+         * @var array $pattern: The list of URIs to validate against
30
+         */
31
+        private $pattern = array();
32
+
33
+        /**
34
+         * @var array $callback: The list of callback to call
35
+         */
36
+        private $callback = array();
37
+
38
+        /**
39
+         * @var string $uriTrim: The char to remove from the URIs
40
+         */
41
+        protected $uriTrim = '/\^$';
42
+
43
+        /**
44
+         * @var string $uri: The route URI to use
45
+         */
46
+        protected $uri = '';
47
+
48
+        /**
49
+         * The module name of the current request
50
+         * @var string
51
+         */
52
+        protected $module = null;
53 53
 		
54
-		/**
55
-		 * The controller name of the current request
56
-		 * @var string
57
-		 */
58
-		protected $controller = null;
59
-
60
-		/**
61
-		 * The controller path
62
-		 * @var string
63
-		 */
64
-		protected $controllerPath = null;
65
-
66
-		/**
67
-		 * The method name. The default value is "index"
68
-		 * @var string
69
-		 */
70
-		protected $method = 'index';
71
-
72
-		/**
73
-		 * List of argument to pass to the method
74
-		 * @var array
75
-		 */
76
-		protected $args = array();
77
-
78
-		/**
79
-		 * List of routes configurations
80
-		 * @var array
81
-		 */
82
-		protected $routes = array();
83
-
84
-		/**
85
-		 * The segments array for the current request
86
-		 * @var array
87
-		 */
88
-		protected $segments = array();
89
-
90
-		/**
91
-		 * The logger instance
92
-		 * @var Log
93
-		 */
94
-		private $logger;
95
-
96
-		/**
97
-		 * Construct the new Router instance
98
-		 */
99
-		public function __construct(){
100
-			$this->setLoggerFromParamOrCreateNewInstance(null);
54
+        /**
55
+         * The controller name of the current request
56
+         * @var string
57
+         */
58
+        protected $controller = null;
59
+
60
+        /**
61
+         * The controller path
62
+         * @var string
63
+         */
64
+        protected $controllerPath = null;
65
+
66
+        /**
67
+         * The method name. The default value is "index"
68
+         * @var string
69
+         */
70
+        protected $method = 'index';
71
+
72
+        /**
73
+         * List of argument to pass to the method
74
+         * @var array
75
+         */
76
+        protected $args = array();
77
+
78
+        /**
79
+         * List of routes configurations
80
+         * @var array
81
+         */
82
+        protected $routes = array();
83
+
84
+        /**
85
+         * The segments array for the current request
86
+         * @var array
87
+         */
88
+        protected $segments = array();
89
+
90
+        /**
91
+         * The logger instance
92
+         * @var Log
93
+         */
94
+        private $logger;
95
+
96
+        /**
97
+         * Construct the new Router instance
98
+         */
99
+        public function __construct(){
100
+            $this->setLoggerFromParamOrCreateNewInstance(null);
101 101
 			
102
-			//loading routes for module
103
-			$moduleRouteList = array();
104
-			$modulesRoutes = Module::getModulesRoutes();
105
-			if($modulesRoutes && is_array($modulesRoutes)){
106
-				$moduleRouteList = $modulesRoutes;
107
-				unset($modulesRoutes);
108
-			}
109
-			$this->setRouteConfiguration($moduleRouteList);
110
-			$this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
111
-
112
-			//Set route informations
113
-			$this->setRouteConfigurationInfos();
114
-		}
115
-
116
-		/**
117
-		 * Get the route patterns
118
-		 * @return array
119
-		 */
120
-		public function getPattern(){
121
-			return $this->pattern;
122
-		}
123
-
124
-		/**
125
-		 * Get the route callbacks
126
-		 * @return array
127
-		 */
128
-		public function getCallback(){
129
-			return $this->callback;
130
-		}
131
-
132
-	    /**
133
-		 * Get the module name
134
-		 * @return string
135
-		 */
136
-		public function getModule(){
137
-			return $this->module;
138
-		}
102
+            //loading routes for module
103
+            $moduleRouteList = array();
104
+            $modulesRoutes = Module::getModulesRoutes();
105
+            if($modulesRoutes && is_array($modulesRoutes)){
106
+                $moduleRouteList = $modulesRoutes;
107
+                unset($modulesRoutes);
108
+            }
109
+            $this->setRouteConfiguration($moduleRouteList);
110
+            $this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
111
+
112
+            //Set route informations
113
+            $this->setRouteConfigurationInfos();
114
+        }
115
+
116
+        /**
117
+         * Get the route patterns
118
+         * @return array
119
+         */
120
+        public function getPattern(){
121
+            return $this->pattern;
122
+        }
123
+
124
+        /**
125
+         * Get the route callbacks
126
+         * @return array
127
+         */
128
+        public function getCallback(){
129
+            return $this->callback;
130
+        }
131
+
132
+        /**
133
+         * Get the module name
134
+         * @return string
135
+         */
136
+        public function getModule(){
137
+            return $this->module;
138
+        }
139 139
 		
140
-		/**
141
-		 * Get the controller name
142
-		 * @return string
143
-		 */
144
-		public function getController(){
145
-			return $this->controller;
146
-		}
147
-
148
-		/**
149
-		 * Get the controller file path
150
-		 * @return string
151
-		 */
152
-		public function getControllerPath(){
153
-			return $this->controllerPath;
154
-		}
155
-
156
-		/**
157
-		 * Get the controller method
158
-		 * @return string
159
-		 */
160
-		public function getMethod(){
161
-			return $this->method;
162
-		}
163
-
164
-		/**
165
-		 * Get the request arguments
166
-		 * @return array
167
-		 */
168
-		public function getArgs(){
169
-			return $this->args;
170
-		}
171
-
172
-		/**
173
-		 * Get the URL segments array
174
-		 * @return array
175
-		 */
176
-		public function getSegments(){
177
-			return $this->segments;
178
-		}
179
-
180
-		/**
181
-	     * Return the Log instance
182
-	     * @return Log
183
-	     */
184
-	    public function getLogger(){
185
-	      return $this->logger;
186
-	    }
187
-
188
-	    /**
189
-	     * Set the log instance
190
-	     * @param Log $logger the log object
191
-		 * @return object
192
-	     */
193
-	    public function setLogger($logger){
194
-	      $this->logger = $logger;
195
-	      return $this;
196
-	    }
197
-
198
-	    /**
199
-		 * Get the route URI
200
-		 * @return string
201
-		 */
202
-		public function getRouteUri(){
203
-			return $this->uri;
204
-		}
205
-
206
-		/**
207
-		* Add the URI and callback to the list of URIs to validate
208
-		*
209
-		* @param string $uri the request URI
210
-		* @param object $callback the callback function
211
-		*
212
-		* @return object the current instance
213
-		*/
214
-		public function add($uri, $callback) {
215
-			$uri = trim($uri, $this->uriTrim);
216
-			if(in_array($uri, $this->pattern)){
217
-				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
218
-			}
219
-			$this->pattern[] = $uri;
220
-			$this->callback[] = $callback;
221
-			return $this;
222
-		}
223
-
224
-		/**
225
-		* Remove the route configuration
226
-		*
227
-		* @param string $uri the URI
228
-		*
229
-		* @return object the current instance
230
-		*/
231
-		public function removeRoute($uri) {
232
-			$index  = array_search($uri, $this->pattern, true);
233
-			if($index !== false){
234
-				$this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
235
-				unset($this->pattern[$index]);
236
-				unset($this->callback[$index]);
237
-			}
238
-			return $this;
239
-		}
240
-
241
-
242
-		/**
243
-		* Remove all the routes from the configuration
244
-		*
245
-		* @return object the current instance
246
-		*/
247
-		public function removeAllRoute() {
248
-			$this->logger->info('Remove all routes from the configuration');
249
-			$this->pattern  = array();
250
-			$this->callback = array();
251
-			$this->routes = array();
252
-			return $this;
253
-		}
254
-
255
-
256
-		/**
257
-	     * Set the route URI to use later
258
-	     * @param string $uri the route URI, if is empty will determine automatically
259
-	     * @return object
260
-	     */
261
-	    public function setRouteUri($uri = ''){
262
-	    	$routeUri = '';
263
-	    	if(! empty($uri)){
264
-	    		$routeUri = $uri;
265
-	    	}
266
-	    	//if the application is running in CLI mode use the first argument
267
-			else if(IS_CLI){
268
-				if(isset($_SERVER['argv'][1])){
269
-					$routeUri = $_SERVER['argv'][1];
270
-				}
271
-			}
272
-			else if(isset($_SERVER['REQUEST_URI'])){
273
-				$routeUri = $_SERVER['REQUEST_URI'];
274
-			}
275
-			$this->logger->debug('Check if URL suffix is enabled in the configuration');
276
-			//remove url suffix from the request URI
277
-			$suffix = get_config('url_suffix');
278
-			if ($suffix) {
279
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
280
-				$routeUri = str_ireplace($suffix, '', $routeUri);
281
-			} 
282
-			if (strpos($routeUri, '?') !== false){
283
-				$routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
284
-			}
285
-			$this->uri = trim($routeUri, $this->uriTrim);
286
-			return $this;
287
-	    }
288
-
289
-	     /**
290
-		 * Set the route segments informations
291
-		 * @param array $segements the route segments information
292
-		 * 
293
-		 * @return object
294
-		 */
295
-		public function setRouteSegments(array $segments = array()){
296
-			if(! empty($segments)){
297
-				$this->segments = $segments;
298
-			} else if (!empty($this->uri)) {
299
-				$this->segments = explode('/', $this->uri);
300
-			}
301
-			$segment = $this->segments;
302
-			$baseUrl = get_config('base_url');
303
-			//check if the app is not in DOCUMENT_ROOT
304
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
305
-				array_shift($segment);
306
-				$this->segments = $segment;
307
-			}
308
-			$this->logger->debug('Check if the request URI contains the front controller');
309
-			if(isset($segment[0]) && $segment[0] == SELF){
310
-				$this->logger->info('The request URI contains the front controller');
311
-				array_shift($segment);
312
-				$this->segments = $segment;
313
-			}
314
-			return $this;
315
-		}
316
-
317
-		/**
318
-		 * Setting the route parameters like module, controller, method, argument
319
-		 * @return object the current instance
320
-		 */
321
-		public function determineRouteParamsInformation() {
322
-			$this->logger->debug('Routing process start ...');
140
+        /**
141
+         * Get the controller name
142
+         * @return string
143
+         */
144
+        public function getController(){
145
+            return $this->controller;
146
+        }
147
+
148
+        /**
149
+         * Get the controller file path
150
+         * @return string
151
+         */
152
+        public function getControllerPath(){
153
+            return $this->controllerPath;
154
+        }
155
+
156
+        /**
157
+         * Get the controller method
158
+         * @return string
159
+         */
160
+        public function getMethod(){
161
+            return $this->method;
162
+        }
163
+
164
+        /**
165
+         * Get the request arguments
166
+         * @return array
167
+         */
168
+        public function getArgs(){
169
+            return $this->args;
170
+        }
171
+
172
+        /**
173
+         * Get the URL segments array
174
+         * @return array
175
+         */
176
+        public function getSegments(){
177
+            return $this->segments;
178
+        }
179
+
180
+        /**
181
+         * Return the Log instance
182
+         * @return Log
183
+         */
184
+        public function getLogger(){
185
+            return $this->logger;
186
+        }
187
+
188
+        /**
189
+         * Set the log instance
190
+         * @param Log $logger the log object
191
+         * @return object
192
+         */
193
+        public function setLogger($logger){
194
+            $this->logger = $logger;
195
+            return $this;
196
+        }
197
+
198
+        /**
199
+         * Get the route URI
200
+         * @return string
201
+         */
202
+        public function getRouteUri(){
203
+            return $this->uri;
204
+        }
205
+
206
+        /**
207
+         * Add the URI and callback to the list of URIs to validate
208
+         *
209
+         * @param string $uri the request URI
210
+         * @param object $callback the callback function
211
+         *
212
+         * @return object the current instance
213
+         */
214
+        public function add($uri, $callback) {
215
+            $uri = trim($uri, $this->uriTrim);
216
+            if(in_array($uri, $this->pattern)){
217
+                $this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
218
+            }
219
+            $this->pattern[] = $uri;
220
+            $this->callback[] = $callback;
221
+            return $this;
222
+        }
223
+
224
+        /**
225
+         * Remove the route configuration
226
+         *
227
+         * @param string $uri the URI
228
+         *
229
+         * @return object the current instance
230
+         */
231
+        public function removeRoute($uri) {
232
+            $index  = array_search($uri, $this->pattern, true);
233
+            if($index !== false){
234
+                $this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
235
+                unset($this->pattern[$index]);
236
+                unset($this->callback[$index]);
237
+            }
238
+            return $this;
239
+        }
240
+
241
+
242
+        /**
243
+         * Remove all the routes from the configuration
244
+         *
245
+         * @return object the current instance
246
+         */
247
+        public function removeAllRoute() {
248
+            $this->logger->info('Remove all routes from the configuration');
249
+            $this->pattern  = array();
250
+            $this->callback = array();
251
+            $this->routes = array();
252
+            return $this;
253
+        }
254
+
255
+
256
+        /**
257
+         * Set the route URI to use later
258
+         * @param string $uri the route URI, if is empty will determine automatically
259
+         * @return object
260
+         */
261
+        public function setRouteUri($uri = ''){
262
+            $routeUri = '';
263
+            if(! empty($uri)){
264
+                $routeUri = $uri;
265
+            }
266
+            //if the application is running in CLI mode use the first argument
267
+            else if(IS_CLI){
268
+                if(isset($_SERVER['argv'][1])){
269
+                    $routeUri = $_SERVER['argv'][1];
270
+                }
271
+            }
272
+            else if(isset($_SERVER['REQUEST_URI'])){
273
+                $routeUri = $_SERVER['REQUEST_URI'];
274
+            }
275
+            $this->logger->debug('Check if URL suffix is enabled in the configuration');
276
+            //remove url suffix from the request URI
277
+            $suffix = get_config('url_suffix');
278
+            if ($suffix) {
279
+                $this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
280
+                $routeUri = str_ireplace($suffix, '', $routeUri);
281
+            } 
282
+            if (strpos($routeUri, '?') !== false){
283
+                $routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
284
+            }
285
+            $this->uri = trim($routeUri, $this->uriTrim);
286
+            return $this;
287
+        }
288
+
289
+            /**
290
+             * Set the route segments informations
291
+             * @param array $segements the route segments information
292
+             * 
293
+             * @return object
294
+             */
295
+        public function setRouteSegments(array $segments = array()){
296
+            if(! empty($segments)){
297
+                $this->segments = $segments;
298
+            } else if (!empty($this->uri)) {
299
+                $this->segments = explode('/', $this->uri);
300
+            }
301
+            $segment = $this->segments;
302
+            $baseUrl = get_config('base_url');
303
+            //check if the app is not in DOCUMENT_ROOT
304
+            if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
305
+                array_shift($segment);
306
+                $this->segments = $segment;
307
+            }
308
+            $this->logger->debug('Check if the request URI contains the front controller');
309
+            if(isset($segment[0]) && $segment[0] == SELF){
310
+                $this->logger->info('The request URI contains the front controller');
311
+                array_shift($segment);
312
+                $this->segments = $segment;
313
+            }
314
+            return $this;
315
+        }
316
+
317
+        /**
318
+         * Setting the route parameters like module, controller, method, argument
319
+         * @return object the current instance
320
+         */
321
+        public function determineRouteParamsInformation() {
322
+            $this->logger->debug('Routing process start ...');
323 323
 			
324
-			//determine route parameters using the config
325
-			$this->determineRouteParamsFromConfig();
324
+            //determine route parameters using the config
325
+            $this->determineRouteParamsFromConfig();
326 326
 			
327
-			//if can not determine the module/controller/method via the defined routes configuration we will use
328
-			//the URL like http://domain.com/module/controller/method/arg1/arg2
329
-			if(! $this->controller){
330
-				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
331
-				//determine route parameters using the REQUEST_URI param
332
-				$this->determineRouteParamsFromRequestUri();
333
-			}
334
-			//Set the controller file path if not yet set
335
-			$this->setControllerFilePath();
336
-			$this->logger->debug('Routing process end.');
337
-
338
-			return $this;
339
-		}
327
+            //if can not determine the module/controller/method via the defined routes configuration we will use
328
+            //the URL like http://domain.com/module/controller/method/arg1/arg2
329
+            if(! $this->controller){
330
+                $this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
331
+                //determine route parameters using the REQUEST_URI param
332
+                $this->determineRouteParamsFromRequestUri();
333
+            }
334
+            //Set the controller file path if not yet set
335
+            $this->setControllerFilePath();
336
+            $this->logger->debug('Routing process end.');
337
+
338
+            return $this;
339
+        }
340 340
 	
341
-		 /**
342
-		 * Routing the request to the correspondant module/controller/method if exists
343
-		 * otherwise send 404 error.
344
-		 */
345
-	    public function processRequest(){
346
-	    	//Setting the route URI
347
-			$this->setRouteUri();
348
-
349
-			//setting route segments
350
-			$this->setRouteSegments();
351
-
352
-			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
353
-
354
-	    	//determine the route parameters information
355
-	    	$this->determineRouteParamsInformation();
356
-
357
-	    	$e404 = false;
358
-	    	$classFilePath = $this->controllerPath;
359
-	    	$controller = ucfirst($this->controller);
360
-	    	$this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
361
-	    	$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
341
+            /**
342
+             * Routing the request to the correspondant module/controller/method if exists
343
+             * otherwise send 404 error.
344
+             */
345
+        public function processRequest(){
346
+            //Setting the route URI
347
+            $this->setRouteUri();
348
+
349
+            //setting route segments
350
+            $this->setRouteSegments();
351
+
352
+            $this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
353
+
354
+            //determine the route parameters information
355
+            $this->determineRouteParamsInformation();
356
+
357
+            $e404 = false;
358
+            $classFilePath = $this->controllerPath;
359
+            $controller = ucfirst($this->controller);
360
+            $this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
361
+            $this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
362 362
 	    	
363
-			if(file_exists($classFilePath)){
364
-				require_once $classFilePath;
365
-				if(! class_exists($controller, false)){
366
-					$e404 = true;
367
-					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
368
-				}
369
-				else{
370
-					$controllerInstance = new $controller();
371
-					$controllerMethod = $this->getMethod();
372
-					if(! method_exists($controllerInstance, $controllerMethod)){
373
-						$e404 = true;
374
-						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
375
-					}
376
-					else{
377
-						$this->logger->info('Routing data is set correctly now GO!');
378
-						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
379
-						//render the final page to user
380
-						$this->logger->info('Render the final output to the browser');
381
-						get_instance()->response->renderFinalPage();
382
-					}
383
-				}
384
-			}
385
-			else{
386
-				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
387
-				$e404 = true;
388
-			}
389
-			if($e404){
390
-				if(IS_CLI){
391
-					set_http_status_header(404);
392
-					echo 'Error 404: page not found.';
393
-				} else {
394
-					$response =& class_loader('Response', 'classes');
395
-					$response->send404();
396
-				}
397
-			}
398
-	    }
399
-
400
-
401
-	    /**
402
-	    * Setting the route configuration using the configuration file and additional configuration from param
403
-	    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
404
-	    * @param boolean $useConfigFile whether to use route configuration file
405
-		* @return object
406
-	    */
407
-	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
408
-	        $route = array();
409
-	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
410
-	            require_once CONFIG_PATH . 'routes.php';
411
-	        }
412
-	        $route = array_merge($route, $overwriteConfig);
413
-	        $this->routes = $route;
414
-	        //if route is empty remove all configuration
415
-	        if(empty($route)){
416
-	        	$this->removeAllRoute();
417
-	        }
418
-			return $this;
419
-	    }
420
-
421
-	     /**
422
-		 * Get the route configuration
423
-		 * @return array
424
-		 */
425
-		public function getRouteConfiguration(){
426
-			return $this->routes;
427
-		}
363
+            if(file_exists($classFilePath)){
364
+                require_once $classFilePath;
365
+                if(! class_exists($controller, false)){
366
+                    $e404 = true;
367
+                    $this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
368
+                }
369
+                else{
370
+                    $controllerInstance = new $controller();
371
+                    $controllerMethod = $this->getMethod();
372
+                    if(! method_exists($controllerInstance, $controllerMethod)){
373
+                        $e404 = true;
374
+                        $this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
375
+                    }
376
+                    else{
377
+                        $this->logger->info('Routing data is set correctly now GO!');
378
+                        call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
379
+                        //render the final page to user
380
+                        $this->logger->info('Render the final output to the browser');
381
+                        get_instance()->response->renderFinalPage();
382
+                    }
383
+                }
384
+            }
385
+            else{
386
+                $this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
387
+                $e404 = true;
388
+            }
389
+            if($e404){
390
+                if(IS_CLI){
391
+                    set_http_status_header(404);
392
+                    echo 'Error 404: page not found.';
393
+                } else {
394
+                    $response =& class_loader('Response', 'classes');
395
+                    $response->send404();
396
+                }
397
+            }
398
+        }
399
+
400
+
401
+        /**
402
+         * Setting the route configuration using the configuration file and additional configuration from param
403
+         * @param array $overwriteConfig the additional configuration to overwrite with the existing one
404
+         * @param boolean $useConfigFile whether to use route configuration file
405
+         * @return object
406
+         */
407
+        public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
408
+            $route = array();
409
+            if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
410
+                require_once CONFIG_PATH . 'routes.php';
411
+            }
412
+            $route = array_merge($route, $overwriteConfig);
413
+            $this->routes = $route;
414
+            //if route is empty remove all configuration
415
+            if(empty($route)){
416
+                $this->removeAllRoute();
417
+            }
418
+            return $this;
419
+        }
420
+
421
+            /**
422
+             * Get the route configuration
423
+             * @return array
424
+             */
425
+        public function getRouteConfiguration(){
426
+            return $this->routes;
427
+        }
428 428
 
429 429
 	    
430
-	    /**
431
-	     * Set the controller file path if is not set
432
-	     * @param string $path the file path if is null will using the route 
433
-	     * information
434
-	     *
435
-	     * @return object the current instance
436
-	     */
437
-	    public function setControllerFilePath($path = null){
438
-	    	if($path !== null){
439
-	    		$this->controllerPath = $path;
440
-	    		return $this;
441
-	    	}
442
-	    	//did we set the controller, so set the controller path
443
-			if($this->controller && ! $this->controllerPath){
444
-				$this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
445
-				$this->controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
446
-				//if the controller is in module
447
-				if($this->module){
448
-					$this->controllerPath = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
449
-				}
450
-			}
451
-			return $this;
452
-	    }
453
-
454
-	    /**
455
-	     * Determine the route parameters from route configuration
456
-	     * @return void
457
-	     */
458
-	    protected function determineRouteParamsFromConfig(){
459
-	    	$uri = implode('/', $this->segments);
460
-	    	/*
430
+        /**
431
+         * Set the controller file path if is not set
432
+         * @param string $path the file path if is null will using the route 
433
+         * information
434
+         *
435
+         * @return object the current instance
436
+         */
437
+        public function setControllerFilePath($path = null){
438
+            if($path !== null){
439
+                $this->controllerPath = $path;
440
+                return $this;
441
+            }
442
+            //did we set the controller, so set the controller path
443
+            if($this->controller && ! $this->controllerPath){
444
+                $this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
445
+                $this->controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
446
+                //if the controller is in module
447
+                if($this->module){
448
+                    $this->controllerPath = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
449
+                }
450
+            }
451
+            return $this;
452
+        }
453
+
454
+        /**
455
+         * Determine the route parameters from route configuration
456
+         * @return void
457
+         */
458
+        protected function determineRouteParamsFromConfig(){
459
+            $uri = implode('/', $this->segments);
460
+            /*
461 461
 	   		* Generics routes patterns
462 462
 	    	*/
463
-			$pattern = array(':num', ':alpha', ':alnum', ':any');
464
-			$replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
465
-
466
-			$this->logger->debug(
467
-									'Begin to loop in the predefined routes configuration ' 
468
-									. 'to check if the current request match'
469
-									);
470
-
471
-			// Cycle through the URIs stored in the array
472
-			foreach ($this->pattern as $index => $uriList) {
473
-				$uriList = str_ireplace($pattern, $replace, $uriList);
474
-				// Check for an existant matching URI
475
-				if (preg_match("#^$uriList$#", $uri, $args)) {
476
-					$this->logger->info(
477
-										'Route found for request URI [' . $uri . '] using the predefined configuration '
478
-										. ' [' . $this->pattern[$index] . '] --> [' . $this->callback[$index] . ']'
479
-									);
480
-					array_shift($args);
481
-					//check if this contains an module
482
-					$moduleControllerMethod = explode('#', $this->callback[$index]);
483
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
484
-						$this->logger->info('The current request use the module [' .$moduleControllerMethod[0]. ']');
485
-						$this->module = $moduleControllerMethod[0];
486
-						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
487
-					}
488
-					else{
489
-						$this->logger->info('The current request does not use the module');
490
-						$moduleControllerMethod = explode('@', $this->callback[$index]);
491
-					}
492
-					if(is_array($moduleControllerMethod)){
493
-						if(isset($moduleControllerMethod[0])){
494
-							$this->controller = $moduleControllerMethod[0];	
495
-						}
496
-						if(isset($moduleControllerMethod[1])){
497
-							$this->method = $moduleControllerMethod[1];
498
-						}
499
-						$this->args = $args;
500
-					}
501
-					// stop here
502
-					break;
503
-				}
504
-			}
505
-
506
-			//first if the controller is not set and the module is set use the module name as the controller
507
-			if(! $this->controller && $this->module){
508
-				$this->logger->info(
509
-									'After loop in predefined routes configuration, 
463
+            $pattern = array(':num', ':alpha', ':alnum', ':any');
464
+            $replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
465
+
466
+            $this->logger->debug(
467
+                                    'Begin to loop in the predefined routes configuration ' 
468
+                                    . 'to check if the current request match'
469
+                                    );
470
+
471
+            // Cycle through the URIs stored in the array
472
+            foreach ($this->pattern as $index => $uriList) {
473
+                $uriList = str_ireplace($pattern, $replace, $uriList);
474
+                // Check for an existant matching URI
475
+                if (preg_match("#^$uriList$#", $uri, $args)) {
476
+                    $this->logger->info(
477
+                                        'Route found for request URI [' . $uri . '] using the predefined configuration '
478
+                                        . ' [' . $this->pattern[$index] . '] --> [' . $this->callback[$index] . ']'
479
+                                    );
480
+                    array_shift($args);
481
+                    //check if this contains an module
482
+                    $moduleControllerMethod = explode('#', $this->callback[$index]);
483
+                    if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
484
+                        $this->logger->info('The current request use the module [' .$moduleControllerMethod[0]. ']');
485
+                        $this->module = $moduleControllerMethod[0];
486
+                        $moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
487
+                    }
488
+                    else{
489
+                        $this->logger->info('The current request does not use the module');
490
+                        $moduleControllerMethod = explode('@', $this->callback[$index]);
491
+                    }
492
+                    if(is_array($moduleControllerMethod)){
493
+                        if(isset($moduleControllerMethod[0])){
494
+                            $this->controller = $moduleControllerMethod[0];	
495
+                        }
496
+                        if(isset($moduleControllerMethod[1])){
497
+                            $this->method = $moduleControllerMethod[1];
498
+                        }
499
+                        $this->args = $args;
500
+                    }
501
+                    // stop here
502
+                    break;
503
+                }
504
+            }
505
+
506
+            //first if the controller is not set and the module is set use the module name as the controller
507
+            if(! $this->controller && $this->module){
508
+                $this->logger->info(
509
+                                    'After loop in predefined routes configuration, 
510 510
 									the module name is set but the controller is not set, 
511 511
 									so we will use module as the controller'
512
-								);
513
-				$this->controller = $this->module;
514
-			}
515
-	    }
516
-
517
-	    /**
518
-	     * Determine the route parameters using the server variable "REQUEST_URI"
519
-	     * @return void
520
-	     */
521
-	    protected function determineRouteParamsFromRequestUri(){
522
-	    	$segment = $this->segments;
523
-	    	$nbSegment = count($segment);
524
-			//if segment is null so means no need to perform
525
-			if($nbSegment > 0){
526
-				//get the module list
527
-				$modules = Module::getModuleList();
528
-				//first check if no module
529
-				if(empty($modules)){
530
-					$this->logger->info('No module was loaded will skip the module checking');
531
-					//the application don't use module
532
-					//controller
533
-					if(isset($segment[0])){
534
-						$this->controller = $segment[0];
535
-						array_shift($segment);
536
-					}
537
-					//method
538
-					if(isset($segment[0])){
539
-						$this->method = $segment[0];
540
-						array_shift($segment);
541
-					}
542
-					//args
543
-					$this->args = $segment;
544
-				}
545
-				else{
546
-					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
547
-					if(in_array($segment[0], $modules)){
548
-						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
549
-						$this->module = $segment[0];
550
-						array_shift($segment);
551
-						//check if the second arg is the controller from module
552
-						if(isset($segment[0])){
553
-							$this->controller = $segment[0];
554
-							//check if the request use the same module name and controller
555
-							$path = Module::findControllerFullPath(ucfirst($this->getController()), $this->getModule());
556
-							if(! $path){
557
-								$this->logger->info('The controller [' . $this->getController() . '] not found in the module, may be will use the module [' . $this->getModule() . '] as controller');
558
-								$this->controller = $this->getModule();
559
-							}
560
-							else{
561
-								$this->controllerPath = $path;
562
-								array_shift($segment);
563
-							}
564
-						}
565
-						//check for method
566
-						if(isset($segment[0])){
567
-							$this->method = $segment[0];
568
-							array_shift($segment);
569
-						}
570
-						//the remaining is for args
571
-						$this->args = $segment;
572
-					}
573
-					else{
574
-						$this->logger->info('The current request information is not found in the module list');
575
-						//controller
576
-						if(isset($segment[0])){
577
-							$this->controller = $segment[0];
578
-							array_shift($segment);
579
-						}
580
-						//method
581
-						if(isset($segment[0])){
582
-							$this->method = $segment[0];
583
-							array_shift($segment);
584
-						}
585
-						//args
586
-						$this->args = $segment;
587
-					}
588
-				}
589
-				if(! $this->controller && $this->module){
590
-					$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');
591
-					$this->controller = $this->module;
592
-				}
593
-			}
594
-	    }
595
-
596
-	    /**
597
-	     * Set the route informations using the configuration
598
-	     *
599
-	     * @return object the current instance
600
-	     */
601
-	    protected function setRouteConfigurationInfos(){
602
-	    	//adding route
603
-			foreach($this->routes as $pattern => $callback){
604
-				$this->add($pattern, $callback);
605
-			}
606
-			return $this;
607
-		}
608
-
609
-		/**
610
-	     * Set the Log instance using argument or create new instance
611
-	     * @param object $logger the Log instance if not null
612
-	     */
613
-	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
614
-	      if ($logger !== null){
615
-	        $this->logger = $logger;
616
-	      }
617
-	      else{
618
-	          $this->logger =& class_loader('Log', 'classes');
619
-	          $this->logger->setLogger('Library::Router');
620
-	      }
621
-	    }
622
-	}
512
+                                );
513
+                $this->controller = $this->module;
514
+            }
515
+        }
516
+
517
+        /**
518
+         * Determine the route parameters using the server variable "REQUEST_URI"
519
+         * @return void
520
+         */
521
+        protected function determineRouteParamsFromRequestUri(){
522
+            $segment = $this->segments;
523
+            $nbSegment = count($segment);
524
+            //if segment is null so means no need to perform
525
+            if($nbSegment > 0){
526
+                //get the module list
527
+                $modules = Module::getModuleList();
528
+                //first check if no module
529
+                if(empty($modules)){
530
+                    $this->logger->info('No module was loaded will skip the module checking');
531
+                    //the application don't use module
532
+                    //controller
533
+                    if(isset($segment[0])){
534
+                        $this->controller = $segment[0];
535
+                        array_shift($segment);
536
+                    }
537
+                    //method
538
+                    if(isset($segment[0])){
539
+                        $this->method = $segment[0];
540
+                        array_shift($segment);
541
+                    }
542
+                    //args
543
+                    $this->args = $segment;
544
+                }
545
+                else{
546
+                    $this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
547
+                    if(in_array($segment[0], $modules)){
548
+                        $this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
549
+                        $this->module = $segment[0];
550
+                        array_shift($segment);
551
+                        //check if the second arg is the controller from module
552
+                        if(isset($segment[0])){
553
+                            $this->controller = $segment[0];
554
+                            //check if the request use the same module name and controller
555
+                            $path = Module::findControllerFullPath(ucfirst($this->getController()), $this->getModule());
556
+                            if(! $path){
557
+                                $this->logger->info('The controller [' . $this->getController() . '] not found in the module, may be will use the module [' . $this->getModule() . '] as controller');
558
+                                $this->controller = $this->getModule();
559
+                            }
560
+                            else{
561
+                                $this->controllerPath = $path;
562
+                                array_shift($segment);
563
+                            }
564
+                        }
565
+                        //check for method
566
+                        if(isset($segment[0])){
567
+                            $this->method = $segment[0];
568
+                            array_shift($segment);
569
+                        }
570
+                        //the remaining is for args
571
+                        $this->args = $segment;
572
+                    }
573
+                    else{
574
+                        $this->logger->info('The current request information is not found in the module list');
575
+                        //controller
576
+                        if(isset($segment[0])){
577
+                            $this->controller = $segment[0];
578
+                            array_shift($segment);
579
+                        }
580
+                        //method
581
+                        if(isset($segment[0])){
582
+                            $this->method = $segment[0];
583
+                            array_shift($segment);
584
+                        }
585
+                        //args
586
+                        $this->args = $segment;
587
+                    }
588
+                }
589
+                if(! $this->controller && $this->module){
590
+                    $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');
591
+                    $this->controller = $this->module;
592
+                }
593
+            }
594
+        }
595
+
596
+        /**
597
+         * Set the route informations using the configuration
598
+         *
599
+         * @return object the current instance
600
+         */
601
+        protected function setRouteConfigurationInfos(){
602
+            //adding route
603
+            foreach($this->routes as $pattern => $callback){
604
+                $this->add($pattern, $callback);
605
+            }
606
+            return $this;
607
+        }
608
+
609
+        /**
610
+         * Set the Log instance using argument or create new instance
611
+         * @param object $logger the Log instance if not null
612
+         */
613
+        protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
614
+            if ($logger !== null){
615
+            $this->logger = $logger;
616
+            }
617
+            else{
618
+                $this->logger =& class_loader('Log', 'classes');
619
+                $this->logger->setLogger('Library::Router');
620
+            }
621
+        }
622
+    }
Please login to merge, or discard this patch.
Spacing   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
 		/**
97 97
 		 * Construct the new Router instance
98 98
 		 */
99
-		public function __construct(){
99
+		public function __construct() {
100 100
 			$this->setLoggerFromParamOrCreateNewInstance(null);
101 101
 			
102 102
 			//loading routes for module
103 103
 			$moduleRouteList = array();
104 104
 			$modulesRoutes = Module::getModulesRoutes();
105
-			if($modulesRoutes && is_array($modulesRoutes)){
105
+			if ($modulesRoutes && is_array($modulesRoutes)) {
106 106
 				$moduleRouteList = $modulesRoutes;
107 107
 				unset($modulesRoutes);
108 108
 			}
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 		 * Get the route patterns
118 118
 		 * @return array
119 119
 		 */
120
-		public function getPattern(){
120
+		public function getPattern() {
121 121
 			return $this->pattern;
122 122
 		}
123 123
 
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		 * Get the route callbacks
126 126
 		 * @return array
127 127
 		 */
128
-		public function getCallback(){
128
+		public function getCallback() {
129 129
 			return $this->callback;
130 130
 		}
131 131
 
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		 * Get the module name
134 134
 		 * @return string
135 135
 		 */
136
-		public function getModule(){
136
+		public function getModule() {
137 137
 			return $this->module;
138 138
 		}
139 139
 		
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 		 * Get the controller name
142 142
 		 * @return string
143 143
 		 */
144
-		public function getController(){
144
+		public function getController() {
145 145
 			return $this->controller;
146 146
 		}
147 147
 
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 		 * Get the controller file path
150 150
 		 * @return string
151 151
 		 */
152
-		public function getControllerPath(){
152
+		public function getControllerPath() {
153 153
 			return $this->controllerPath;
154 154
 		}
155 155
 
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 		 * Get the controller method
158 158
 		 * @return string
159 159
 		 */
160
-		public function getMethod(){
160
+		public function getMethod() {
161 161
 			return $this->method;
162 162
 		}
163 163
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		 * Get the request arguments
166 166
 		 * @return array
167 167
 		 */
168
-		public function getArgs(){
168
+		public function getArgs() {
169 169
 			return $this->args;
170 170
 		}
171 171
 
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 		 * Get the URL segments array
174 174
 		 * @return array
175 175
 		 */
176
-		public function getSegments(){
176
+		public function getSegments() {
177 177
 			return $this->segments;
178 178
 		}
179 179
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 	     * Return the Log instance
182 182
 	     * @return Log
183 183
 	     */
184
-	    public function getLogger(){
184
+	    public function getLogger() {
185 185
 	      return $this->logger;
186 186
 	    }
187 187
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 	     * @param Log $logger the log object
191 191
 		 * @return object
192 192
 	     */
193
-	    public function setLogger($logger){
193
+	    public function setLogger($logger) {
194 194
 	      $this->logger = $logger;
195 195
 	      return $this;
196 196
 	    }
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 		 * Get the route URI
200 200
 		 * @return string
201 201
 		 */
202
-		public function getRouteUri(){
202
+		public function getRouteUri() {
203 203
 			return $this->uri;
204 204
 		}
205 205
 
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		*/
214 214
 		public function add($uri, $callback) {
215 215
 			$uri = trim($uri, $this->uriTrim);
216
-			if(in_array($uri, $this->pattern)){
216
+			if (in_array($uri, $this->pattern)) {
217 217
 				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
218 218
 			}
219 219
 			$this->pattern[] = $uri;
@@ -229,8 +229,8 @@  discard block
 block discarded – undo
229 229
 		* @return object the current instance
230 230
 		*/
231 231
 		public function removeRoute($uri) {
232
-			$index  = array_search($uri, $this->pattern, true);
233
-			if($index !== false){
232
+			$index = array_search($uri, $this->pattern, true);
233
+			if ($index !== false) {
234 234
 				$this->logger->info('Remove route for uri [' . $uri . '] from the configuration');
235 235
 				unset($this->pattern[$index]);
236 236
 				unset($this->callback[$index]);
@@ -258,28 +258,28 @@  discard block
 block discarded – undo
258 258
 	     * @param string $uri the route URI, if is empty will determine automatically
259 259
 	     * @return object
260 260
 	     */
261
-	    public function setRouteUri($uri = ''){
261
+	    public function setRouteUri($uri = '') {
262 262
 	    	$routeUri = '';
263
-	    	if(! empty($uri)){
263
+	    	if (!empty($uri)) {
264 264
 	    		$routeUri = $uri;
265 265
 	    	}
266 266
 	    	//if the application is running in CLI mode use the first argument
267
-			else if(IS_CLI){
268
-				if(isset($_SERVER['argv'][1])){
267
+			else if (IS_CLI) {
268
+				if (isset($_SERVER['argv'][1])) {
269 269
 					$routeUri = $_SERVER['argv'][1];
270 270
 				}
271 271
 			}
272
-			else if(isset($_SERVER['REQUEST_URI'])){
272
+			else if (isset($_SERVER['REQUEST_URI'])) {
273 273
 				$routeUri = $_SERVER['REQUEST_URI'];
274 274
 			}
275 275
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
276 276
 			//remove url suffix from the request URI
277 277
 			$suffix = get_config('url_suffix');
278 278
 			if ($suffix) {
279
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
279
+				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']');
280 280
 				$routeUri = str_ireplace($suffix, '', $routeUri);
281 281
 			} 
282
-			if (strpos($routeUri, '?') !== false){
282
+			if (strpos($routeUri, '?') !== false) {
283 283
 				$routeUri = substr($routeUri, 0, strpos($routeUri, '?'));
284 284
 			}
285 285
 			$this->uri = trim($routeUri, $this->uriTrim);
@@ -292,8 +292,8 @@  discard block
 block discarded – undo
292 292
 		 * 
293 293
 		 * @return object
294 294
 		 */
295
-		public function setRouteSegments(array $segments = array()){
296
-			if(! empty($segments)){
295
+		public function setRouteSegments(array $segments = array()) {
296
+			if (!empty($segments)) {
297 297
 				$this->segments = $segments;
298 298
 			} else if (!empty($this->uri)) {
299 299
 				$this->segments = explode('/', $this->uri);
@@ -301,12 +301,12 @@  discard block
 block discarded – undo
301 301
 			$segment = $this->segments;
302 302
 			$baseUrl = get_config('base_url');
303 303
 			//check if the app is not in DOCUMENT_ROOT
304
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false){
304
+			if (isset($segment[0]) && stripos($baseUrl, $segment[0]) !== false) {
305 305
 				array_shift($segment);
306 306
 				$this->segments = $segment;
307 307
 			}
308 308
 			$this->logger->debug('Check if the request URI contains the front controller');
309
-			if(isset($segment[0]) && $segment[0] == SELF){
309
+			if (isset($segment[0]) && $segment[0] == SELF) {
310 310
 				$this->logger->info('The request URI contains the front controller');
311 311
 				array_shift($segment);
312 312
 				$this->segments = $segment;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 			
327 327
 			//if can not determine the module/controller/method via the defined routes configuration we will use
328 328
 			//the URL like http://domain.com/module/controller/method/arg1/arg2
329
-			if(! $this->controller){
329
+			if (!$this->controller) {
330 330
 				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
331 331
 				//determine route parameters using the REQUEST_URI param
332 332
 				$this->determineRouteParamsFromRequestUri();
@@ -342,14 +342,14 @@  discard block
 block discarded – undo
342 342
 		 * Routing the request to the correspondant module/controller/method if exists
343 343
 		 * otherwise send 404 error.
344 344
 		 */
345
-	    public function processRequest(){
345
+	    public function processRequest() {
346 346
 	    	//Setting the route URI
347 347
 			$this->setRouteUri();
348 348
 
349 349
 			//setting route segments
350 350
 			$this->setRouteSegments();
351 351
 
352
-			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']' );
352
+			$this->logger->info('The final Request URI is [' . implode('/', $this->segments) . ']');
353 353
 
354 354
 	    	//determine the route parameters information
355 355
 	    	$this->determineRouteParamsInformation();
@@ -360,20 +360,20 @@  discard block
 block discarded – undo
360 360
 	    	$this->logger->info('The routing information are: module [' . $this->module . '], controller [' . $controller . '], method [' . $this->method . '], args [' . stringfy_vars($this->args) . ']');
361 361
 	    	$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
362 362
 	    	
363
-			if(file_exists($classFilePath)){
363
+			if (file_exists($classFilePath)) {
364 364
 				require_once $classFilePath;
365
-				if(! class_exists($controller, false)){
365
+				if (!class_exists($controller, false)) {
366 366
 					$e404 = true;
367
-					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
367
+					$this->logger->warning('The controller file [' . $classFilePath . '] exists but does not contain the class [' . $controller . ']');
368 368
 				}
369
-				else{
369
+				else {
370 370
 					$controllerInstance = new $controller();
371 371
 					$controllerMethod = $this->getMethod();
372
-					if(! method_exists($controllerInstance, $controllerMethod)){
372
+					if (!method_exists($controllerInstance, $controllerMethod)) {
373 373
 						$e404 = true;
374 374
 						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
375 375
 					}
376
-					else{
376
+					else {
377 377
 						$this->logger->info('Routing data is set correctly now GO!');
378 378
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
379 379
 						//render the final page to user
@@ -382,16 +382,16 @@  discard block
 block discarded – undo
382 382
 					}
383 383
 				}
384 384
 			}
385
-			else{
385
+			else {
386 386
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
387 387
 				$e404 = true;
388 388
 			}
389
-			if($e404){
390
-				if(IS_CLI){
389
+			if ($e404) {
390
+				if (IS_CLI) {
391 391
 					set_http_status_header(404);
392 392
 					echo 'Error 404: page not found.';
393 393
 				} else {
394
-					$response =& class_loader('Response', 'classes');
394
+					$response = & class_loader('Response', 'classes');
395 395
 					$response->send404();
396 396
 				}
397 397
 			}
@@ -404,15 +404,15 @@  discard block
 block discarded – undo
404 404
 	    * @param boolean $useConfigFile whether to use route configuration file
405 405
 		* @return object
406 406
 	    */
407
-	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
407
+	    public function setRouteConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
408 408
 	        $route = array();
409
-	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')){
409
+	        if ($useConfigFile && file_exists(CONFIG_PATH . 'routes.php')) {
410 410
 	            require_once CONFIG_PATH . 'routes.php';
411 411
 	        }
412 412
 	        $route = array_merge($route, $overwriteConfig);
413 413
 	        $this->routes = $route;
414 414
 	        //if route is empty remove all configuration
415
-	        if(empty($route)){
415
+	        if (empty($route)) {
416 416
 	        	$this->removeAllRoute();
417 417
 	        }
418 418
 			return $this;
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 		 * Get the route configuration
423 423
 		 * @return array
424 424
 		 */
425
-		public function getRouteConfiguration(){
425
+		public function getRouteConfiguration() {
426 426
 			return $this->routes;
427 427
 		}
428 428
 
@@ -434,17 +434,17 @@  discard block
 block discarded – undo
434 434
 	     *
435 435
 	     * @return object the current instance
436 436
 	     */
437
-	    public function setControllerFilePath($path = null){
438
-	    	if($path !== null){
437
+	    public function setControllerFilePath($path = null) {
438
+	    	if ($path !== null) {
439 439
 	    		$this->controllerPath = $path;
440 440
 	    		return $this;
441 441
 	    	}
442 442
 	    	//did we set the controller, so set the controller path
443
-			if($this->controller && ! $this->controllerPath){
443
+			if ($this->controller && !$this->controllerPath) {
444 444
 				$this->logger->debug('Setting the file path for the controller [' . $this->controller . ']');
445 445
 				$this->controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->controller) . '.php';
446 446
 				//if the controller is in module
447
-				if($this->module){
447
+				if ($this->module) {
448 448
 					$this->controllerPath = Module::findControllerFullPath(ucfirst($this->controller), $this->module);
449 449
 				}
450 450
 			}
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
 	     * Determine the route parameters from route configuration
456 456
 	     * @return void
457 457
 	     */
458
-	    protected function determineRouteParamsFromConfig(){
458
+	    protected function determineRouteParamsFromConfig() {
459 459
 	    	$uri = implode('/', $this->segments);
460 460
 	    	/*
461 461
 	   		* Generics routes patterns
@@ -480,20 +480,20 @@  discard block
 block discarded – undo
480 480
 					array_shift($args);
481 481
 					//check if this contains an module
482 482
 					$moduleControllerMethod = explode('#', $this->callback[$index]);
483
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
484
-						$this->logger->info('The current request use the module [' .$moduleControllerMethod[0]. ']');
483
+					if (is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2) {
484
+						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
485 485
 						$this->module = $moduleControllerMethod[0];
486 486
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
487 487
 					}
488
-					else{
488
+					else {
489 489
 						$this->logger->info('The current request does not use the module');
490 490
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
491 491
 					}
492
-					if(is_array($moduleControllerMethod)){
493
-						if(isset($moduleControllerMethod[0])){
492
+					if (is_array($moduleControllerMethod)) {
493
+						if (isset($moduleControllerMethod[0])) {
494 494
 							$this->controller = $moduleControllerMethod[0];	
495 495
 						}
496
-						if(isset($moduleControllerMethod[1])){
496
+						if (isset($moduleControllerMethod[1])) {
497 497
 							$this->method = $moduleControllerMethod[1];
498 498
 						}
499 499
 						$this->args = $args;
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 			}
505 505
 
506 506
 			//first if the controller is not set and the module is set use the module name as the controller
507
-			if(! $this->controller && $this->module){
507
+			if (!$this->controller && $this->module) {
508 508
 				$this->logger->info(
509 509
 									'After loop in predefined routes configuration, 
510 510
 									the module name is set but the controller is not set, 
@@ -518,67 +518,67 @@  discard block
 block discarded – undo
518 518
 	     * Determine the route parameters using the server variable "REQUEST_URI"
519 519
 	     * @return void
520 520
 	     */
521
-	    protected function determineRouteParamsFromRequestUri(){
521
+	    protected function determineRouteParamsFromRequestUri() {
522 522
 	    	$segment = $this->segments;
523 523
 	    	$nbSegment = count($segment);
524 524
 			//if segment is null so means no need to perform
525
-			if($nbSegment > 0){
525
+			if ($nbSegment > 0) {
526 526
 				//get the module list
527 527
 				$modules = Module::getModuleList();
528 528
 				//first check if no module
529
-				if(empty($modules)){
529
+				if (empty($modules)) {
530 530
 					$this->logger->info('No module was loaded will skip the module checking');
531 531
 					//the application don't use module
532 532
 					//controller
533
-					if(isset($segment[0])){
533
+					if (isset($segment[0])) {
534 534
 						$this->controller = $segment[0];
535 535
 						array_shift($segment);
536 536
 					}
537 537
 					//method
538
-					if(isset($segment[0])){
538
+					if (isset($segment[0])) {
539 539
 						$this->method = $segment[0];
540 540
 						array_shift($segment);
541 541
 					}
542 542
 					//args
543 543
 					$this->args = $segment;
544 544
 				}
545
-				else{
545
+				else {
546 546
 					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
547
-					if(in_array($segment[0], $modules)){
547
+					if (in_array($segment[0], $modules)) {
548 548
 						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
549 549
 						$this->module = $segment[0];
550 550
 						array_shift($segment);
551 551
 						//check if the second arg is the controller from module
552
-						if(isset($segment[0])){
552
+						if (isset($segment[0])) {
553 553
 							$this->controller = $segment[0];
554 554
 							//check if the request use the same module name and controller
555 555
 							$path = Module::findControllerFullPath(ucfirst($this->getController()), $this->getModule());
556
-							if(! $path){
556
+							if (!$path) {
557 557
 								$this->logger->info('The controller [' . $this->getController() . '] not found in the module, may be will use the module [' . $this->getModule() . '] as controller');
558 558
 								$this->controller = $this->getModule();
559 559
 							}
560
-							else{
560
+							else {
561 561
 								$this->controllerPath = $path;
562 562
 								array_shift($segment);
563 563
 							}
564 564
 						}
565 565
 						//check for method
566
-						if(isset($segment[0])){
566
+						if (isset($segment[0])) {
567 567
 							$this->method = $segment[0];
568 568
 							array_shift($segment);
569 569
 						}
570 570
 						//the remaining is for args
571 571
 						$this->args = $segment;
572 572
 					}
573
-					else{
573
+					else {
574 574
 						$this->logger->info('The current request information is not found in the module list');
575 575
 						//controller
576
-						if(isset($segment[0])){
576
+						if (isset($segment[0])) {
577 577
 							$this->controller = $segment[0];
578 578
 							array_shift($segment);
579 579
 						}
580 580
 						//method
581
-						if(isset($segment[0])){
581
+						if (isset($segment[0])) {
582 582
 							$this->method = $segment[0];
583 583
 							array_shift($segment);
584 584
 						}
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 						$this->args = $segment;
587 587
 					}
588 588
 				}
589
-				if(! $this->controller && $this->module){
589
+				if (!$this->controller && $this->module) {
590 590
 					$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');
591 591
 					$this->controller = $this->module;
592 592
 				}
@@ -598,9 +598,9 @@  discard block
 block discarded – undo
598 598
 	     *
599 599
 	     * @return object the current instance
600 600
 	     */
601
-	    protected function setRouteConfigurationInfos(){
601
+	    protected function setRouteConfigurationInfos() {
602 602
 	    	//adding route
603
-			foreach($this->routes as $pattern => $callback){
603
+			foreach ($this->routes as $pattern => $callback) {
604 604
 				$this->add($pattern, $callback);
605 605
 			}
606 606
 			return $this;
@@ -610,12 +610,12 @@  discard block
 block discarded – undo
610 610
 	     * Set the Log instance using argument or create new instance
611 611
 	     * @param object $logger the Log instance if not null
612 612
 	     */
613
-	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
614
-	      if ($logger !== null){
613
+	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
614
+	      if ($logger !== null) {
615 615
 	        $this->logger = $logger;
616 616
 	      }
617
-	      else{
618
-	          $this->logger =& class_loader('Log', 'classes');
617
+	      else {
618
+	          $this->logger = & class_loader('Log', 'classes');
619 619
 	          $this->logger->setLogger('Library::Router');
620 620
 	      }
621 621
 	    }
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -268,8 +268,7 @@  discard block
 block discarded – undo
268 268
 				if(isset($_SERVER['argv'][1])){
269 269
 					$routeUri = $_SERVER['argv'][1];
270 270
 				}
271
-			}
272
-			else if(isset($_SERVER['REQUEST_URI'])){
271
+			} else if(isset($_SERVER['REQUEST_URI'])){
273 272
 				$routeUri = $_SERVER['REQUEST_URI'];
274 273
 			}
275 274
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
@@ -365,15 +364,13 @@  discard block
 block discarded – undo
365 364
 				if(! class_exists($controller, false)){
366 365
 					$e404 = true;
367 366
 					$this->logger->warning('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
368
-				}
369
-				else{
367
+				} else{
370 368
 					$controllerInstance = new $controller();
371 369
 					$controllerMethod = $this->getMethod();
372 370
 					if(! method_exists($controllerInstance, $controllerMethod)){
373 371
 						$e404 = true;
374 372
 						$this->logger->warning('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
375
-					}
376
-					else{
373
+					} else{
377 374
 						$this->logger->info('Routing data is set correctly now GO!');
378 375
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->args);
379 376
 						//render the final page to user
@@ -381,8 +378,7 @@  discard block
 block discarded – undo
381 378
 						get_instance()->response->renderFinalPage();
382 379
 					}
383 380
 				}
384
-			}
385
-			else{
381
+			} else{
386 382
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
387 383
 				$e404 = true;
388 384
 			}
@@ -484,8 +480,7 @@  discard block
 block discarded – undo
484 480
 						$this->logger->info('The current request use the module [' .$moduleControllerMethod[0]. ']');
485 481
 						$this->module = $moduleControllerMethod[0];
486 482
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
487
-					}
488
-					else{
483
+					} else{
489 484
 						$this->logger->info('The current request does not use the module');
490 485
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
491 486
 					}
@@ -541,8 +536,7 @@  discard block
 block discarded – undo
541 536
 					}
542 537
 					//args
543 538
 					$this->args = $segment;
544
-				}
545
-				else{
539
+				} else{
546 540
 					$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
547 541
 					if(in_array($segment[0], $modules)){
548 542
 						$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
@@ -556,8 +550,7 @@  discard block
 block discarded – undo
556 550
 							if(! $path){
557 551
 								$this->logger->info('The controller [' . $this->getController() . '] not found in the module, may be will use the module [' . $this->getModule() . '] as controller');
558 552
 								$this->controller = $this->getModule();
559
-							}
560
-							else{
553
+							} else{
561 554
 								$this->controllerPath = $path;
562 555
 								array_shift($segment);
563 556
 							}
@@ -569,8 +562,7 @@  discard block
 block discarded – undo
569 562
 						}
570 563
 						//the remaining is for args
571 564
 						$this->args = $segment;
572
-					}
573
-					else{
565
+					} else{
574 566
 						$this->logger->info('The current request information is not found in the module list');
575 567
 						//controller
576 568
 						if(isset($segment[0])){
@@ -613,8 +605,7 @@  discard block
 block discarded – undo
613 605
 	    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
614 606
 	      if ($logger !== null){
615 607
 	        $this->logger = $logger;
616
-	      }
617
-	      else{
608
+	      } else{
618 609
 	          $this->logger =& class_loader('Log', 'classes');
619 610
 	          $this->logger->setLogger('Library::Router');
620 611
 	      }
Please login to merge, or discard this patch.
core/classes/Config.php 3 patches
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -1,191 +1,191 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Config{
27
+    class Config{
28 28
 		
29
-		/**
30
-		 * The list of loaded configuration
31
-		 * @var array
32
-		 */
33
-		private static $config = array();
29
+        /**
30
+         * The list of loaded configuration
31
+         * @var array
32
+         */
33
+        private static $config = array();
34 34
 
35
-		/**
36
-		 * The logger instance
37
-		 * @var Log
38
-		 */
39
-		private static $logger;
35
+        /**
36
+         * The logger instance
37
+         * @var Log
38
+         */
39
+        private static $logger;
40 40
 
41
-		/**
42
-		 * The signleton of the logger
43
-		 * @return Object the Log instance
44
-		 */
45
-		private static function getLogger(){
46
-			if(self::$logger == null){
47
-				$logger = array();
48
-				$logger[0] =& class_loader('Log', 'classes');
49
-				$logger[0]->setLogger('Library::Config');
50
-				self::$logger = $logger[0];
51
-			}
52
-			return self::$logger;			
53
-		}
41
+        /**
42
+         * The signleton of the logger
43
+         * @return Object the Log instance
44
+         */
45
+        private static function getLogger(){
46
+            if(self::$logger == null){
47
+                $logger = array();
48
+                $logger[0] =& class_loader('Log', 'classes');
49
+                $logger[0]->setLogger('Library::Config');
50
+                self::$logger = $logger[0];
51
+            }
52
+            return self::$logger;			
53
+        }
54 54
 
55
-		/**
56
-		 * Set the log instance for future use
57
-		 * @param Log $logger the log object
58
-		 * @return Log the log instance
59
-		 */
60
-		public static function setLogger($logger){
61
-			self::$logger = $logger;
62
-			return self::$logger;
63
-		}
55
+        /**
56
+         * Set the log instance for future use
57
+         * @param Log $logger the log object
58
+         * @return Log the log instance
59
+         */
60
+        public static function setLogger($logger){
61
+            self::$logger = $logger;
62
+            return self::$logger;
63
+        }
64 64
 
65
-		/**
66
-		 * Initialize the configuration by loading all the configuration from config file
67
-		 */
68
-		public static function init(){
69
-			$logger = static::getLogger();
70
-			$logger->debug('Initialization of the configuration');
71
-			self::$config = & load_configurations();
72
-			self::setBaseUrlUsingServerVar();
73
-			if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
74
-				$logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75
-			}
76
-			$logger->info('Configuration initialized successfully');
77
-			$logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
78
-		}
65
+        /**
66
+         * Initialize the configuration by loading all the configuration from config file
67
+         */
68
+        public static function init(){
69
+            $logger = static::getLogger();
70
+            $logger->debug('Initialization of the configuration');
71
+            self::$config = & load_configurations();
72
+            self::setBaseUrlUsingServerVar();
73
+            if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
74
+                $logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75
+            }
76
+            $logger->info('Configuration initialized successfully');
77
+            $logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
78
+        }
79 79
 
80
-		/**
81
-		 * Get the configuration item value
82
-		 * @param  string $item    the configuration item name to get
83
-		 * @param  mixed $default the default value to use if can not find the config item in the list
84
-		 * @return mixed          the config value if exist or the default value
85
-		 */
86
-		public static function get($item, $default = null){
87
-			$logger = static::getLogger();
88
-			if(array_key_exists($item, self::$config)){
89
-				return self::$config[$item];
90
-			}
91
-			$logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
92
-			return $default;
93
-		}
80
+        /**
81
+         * Get the configuration item value
82
+         * @param  string $item    the configuration item name to get
83
+         * @param  mixed $default the default value to use if can not find the config item in the list
84
+         * @return mixed          the config value if exist or the default value
85
+         */
86
+        public static function get($item, $default = null){
87
+            $logger = static::getLogger();
88
+            if(array_key_exists($item, self::$config)){
89
+                return self::$config[$item];
90
+            }
91
+            $logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
92
+            return $default;
93
+        }
94 94
 
95
-		/**
96
-		 * Set the configuration item value
97
-		 * @param string $item  the config item name to set
98
-		 * @param mixed $value the config item value
99
-		 */
100
-		public static function set($item, $value){
101
-			self::$config[$item] = $value;
102
-		}
95
+        /**
96
+         * Set the configuration item value
97
+         * @param string $item  the config item name to set
98
+         * @param mixed $value the config item value
99
+         */
100
+        public static function set($item, $value){
101
+            self::$config[$item] = $value;
102
+        }
103 103
 
104
-		/**
105
-		 * Get all the configuration values
106
-		 * @return array the config values
107
-		 */
108
-		public static function getAll(){
109
-			return self::$config;
110
-		}
104
+        /**
105
+         * Get all the configuration values
106
+         * @return array the config values
107
+         */
108
+        public static function getAll(){
109
+            return self::$config;
110
+        }
111 111
 
112
-		/**
113
-		 * Set the configuration values bu merged with the existing configuration
114
-		 * @param array $config the config values to add in the configuration list
115
-		 */
116
-		public static function setAll(array $config = array()){
117
-			self::$config = array_merge(self::$config, $config);
118
-		}
112
+        /**
113
+         * Set the configuration values bu merged with the existing configuration
114
+         * @param array $config the config values to add in the configuration list
115
+         */
116
+        public static function setAll(array $config = array()){
117
+            self::$config = array_merge(self::$config, $config);
118
+        }
119 119
 
120
-		/**
121
-		 * Delete the configuration item in the list
122
-		 * @param  string $item the config item name to be deleted
123
-		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124
-		 */
125
-		public static function delete($item){
126
-			$logger = static::getLogger();
127
-			if(array_key_exists($item, self::$config)){
128
-				$logger->info('Delete config item ['.$item.']');
129
-				unset(self::$config[$item]);
130
-				return true;
131
-			}
132
-			else{
133
-				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
134
-				return false;
135
-			}
136
-		}
120
+        /**
121
+         * Delete the configuration item in the list
122
+         * @param  string $item the config item name to be deleted
123
+         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124
+         */
125
+        public static function delete($item){
126
+            $logger = static::getLogger();
127
+            if(array_key_exists($item, self::$config)){
128
+                $logger->info('Delete config item ['.$item.']');
129
+                unset(self::$config[$item]);
130
+                return true;
131
+            }
132
+            else{
133
+                $logger->warning('Config item ['.$item.'] to be deleted does not exists');
134
+                return false;
135
+            }
136
+        }
137 137
 
138
-		/**
139
-		 * Load the configuration file. This an alias to Loader::config()
140
-		 * @param  string $config the config name to be loaded
141
-		 */
142
-		public static function load($config){
143
-			Loader::config($config);
144
-		}
138
+        /**
139
+         * Load the configuration file. This an alias to Loader::config()
140
+         * @param  string $config the config name to be loaded
141
+         */
142
+        public static function load($config){
143
+            Loader::config($config);
144
+        }
145 145
 
146
-		/**
147
-		 * Set the configuration for "base_url" if is not set in the configuration
148
-		 */
149
-		private static function setBaseUrlUsingServerVar(){
150
-			$logger = static::getLogger();
151
-			if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
-				if(ENVIRONMENT == 'production'){
153
-					$logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154
-				}
155
-				$baseUrl = null;
156
-				$protocol = 'http';
157
-				if(is_https()){
158
-					$protocol = 'https';
159
-				}
160
-				$protocol .='://';
146
+        /**
147
+         * Set the configuration for "base_url" if is not set in the configuration
148
+         */
149
+        private static function setBaseUrlUsingServerVar(){
150
+            $logger = static::getLogger();
151
+            if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
+                if(ENVIRONMENT == 'production'){
153
+                    $logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154
+                }
155
+                $baseUrl = null;
156
+                $protocol = 'http';
157
+                if(is_https()){
158
+                    $protocol = 'https';
159
+                }
160
+                $protocol .='://';
161 161
 
162
-				if (isset($_SERVER['SERVER_ADDR'])){
163
-					$baseUrl = $_SERVER['SERVER_ADDR'];
164
-					//check if the server is running under IPv6
165
-					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
-						$baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
167
-					}
168
-					$serverPort = 80;
169
-					if (isset($_SERVER['SERVER_PORT'])) {
170
-						$serverPort = $_SERVER['SERVER_PORT'];
171
-					}
172
-					$port = '';
173
-					if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
-						$port = ':'.$serverPort;
175
-					}
176
-					$port = ((($serverPort != '80' && ! is_https()) || ($serverPort != '443' && is_https())) ? ':' . $serverPort : '');
177
-					$baseUrl = $protocol . $baseUrl . $port . substr(
178
-																		$_SERVER['SCRIPT_NAME'], 
179
-																		0, 
180
-																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
181
-																	);
182
-				}
183
-				else{
184
-					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
185
-					$baseUrl = 'http://localhost/';
186
-				}
187
-				self::set('base_url', $baseUrl);
188
-			}
189
-			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
190
-		}
191
-	}
162
+                if (isset($_SERVER['SERVER_ADDR'])){
163
+                    $baseUrl = $_SERVER['SERVER_ADDR'];
164
+                    //check if the server is running under IPv6
165
+                    if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
+                        $baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
167
+                    }
168
+                    $serverPort = 80;
169
+                    if (isset($_SERVER['SERVER_PORT'])) {
170
+                        $serverPort = $_SERVER['SERVER_PORT'];
171
+                    }
172
+                    $port = '';
173
+                    if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
+                        $port = ':'.$serverPort;
175
+                    }
176
+                    $port = ((($serverPort != '80' && ! is_https()) || ($serverPort != '443' && is_https())) ? ':' . $serverPort : '');
177
+                    $baseUrl = $protocol . $baseUrl . $port . substr(
178
+                                                                        $_SERVER['SCRIPT_NAME'], 
179
+                                                                        0, 
180
+                                                                        strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
181
+                                                                    );
182
+                }
183
+                else{
184
+                    $logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
185
+                    $baseUrl = 'http://localhost/';
186
+                }
187
+                self::set('base_url', $baseUrl);
188
+            }
189
+            self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
190
+        }
191
+    }
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Config{
27
+	class Config {
28 28
 		
29 29
 		/**
30 30
 		 * The list of loaded configuration
@@ -42,10 +42,10 @@  discard block
 block discarded – undo
42 42
 		 * The signleton of the logger
43 43
 		 * @return Object the Log instance
44 44
 		 */
45
-		private static function getLogger(){
46
-			if(self::$logger == null){
45
+		private static function getLogger() {
46
+			if (self::$logger == null) {
47 47
 				$logger = array();
48
-				$logger[0] =& class_loader('Log', 'classes');
48
+				$logger[0] = & class_loader('Log', 'classes');
49 49
 				$logger[0]->setLogger('Library::Config');
50 50
 				self::$logger = $logger[0];
51 51
 			}
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 		 * @param Log $logger the log object
58 58
 		 * @return Log the log instance
59 59
 		 */
60
-		public static function setLogger($logger){
60
+		public static function setLogger($logger) {
61 61
 			self::$logger = $logger;
62 62
 			return self::$logger;
63 63
 		}
@@ -65,12 +65,12 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Initialize the configuration by loading all the configuration from config file
67 67
 		 */
68
-		public static function init(){
68
+		public static function init() {
69 69
 			$logger = static::getLogger();
70 70
 			$logger->debug('Initialization of the configuration');
71 71
 			self::$config = & load_configurations();
72 72
 			self::setBaseUrlUsingServerVar();
73
-			if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
73
+			if (ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info', 'all'))) {
74 74
 				$logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
75 75
 			}
76 76
 			$logger->info('Configuration initialized successfully');
@@ -83,12 +83,12 @@  discard block
 block discarded – undo
83 83
 		 * @param  mixed $default the default value to use if can not find the config item in the list
84 84
 		 * @return mixed          the config value if exist or the default value
85 85
 		 */
86
-		public static function get($item, $default = null){
86
+		public static function get($item, $default = null) {
87 87
 			$logger = static::getLogger();
88
-			if(array_key_exists($item, self::$config)){
88
+			if (array_key_exists($item, self::$config)) {
89 89
 				return self::$config[$item];
90 90
 			}
91
-			$logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
91
+			$logger->warning('Cannot find config item [' . $item . '] using the default value [' . $default . ']');
92 92
 			return $default;
93 93
 		}
94 94
 
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 		 * @param string $item  the config item name to set
98 98
 		 * @param mixed $value the config item value
99 99
 		 */
100
-		public static function set($item, $value){
100
+		public static function set($item, $value) {
101 101
 			self::$config[$item] = $value;
102 102
 		}
103 103
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 		 * Get all the configuration values
106 106
 		 * @return array the config values
107 107
 		 */
108
-		public static function getAll(){
108
+		public static function getAll() {
109 109
 			return self::$config;
110 110
 		}
111 111
 
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 		 * Set the configuration values bu merged with the existing configuration
114 114
 		 * @param array $config the config values to add in the configuration list
115 115
 		 */
116
-		public static function setAll(array $config = array()){
116
+		public static function setAll(array $config = array()) {
117 117
 			self::$config = array_merge(self::$config, $config);
118 118
 		}
119 119
 
@@ -122,15 +122,15 @@  discard block
 block discarded – undo
122 122
 		 * @param  string $item the config item name to be deleted
123 123
 		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
124 124
 		 */
125
-		public static function delete($item){
125
+		public static function delete($item) {
126 126
 			$logger = static::getLogger();
127
-			if(array_key_exists($item, self::$config)){
128
-				$logger->info('Delete config item ['.$item.']');
127
+			if (array_key_exists($item, self::$config)) {
128
+				$logger->info('Delete config item [' . $item . ']');
129 129
 				unset(self::$config[$item]);
130 130
 				return true;
131 131
 			}
132
-			else{
133
-				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
132
+			else {
133
+				$logger->warning('Config item [' . $item . '] to be deleted does not exists');
134 134
 				return false;
135 135
 			}
136 136
 		}
@@ -139,53 +139,53 @@  discard block
 block discarded – undo
139 139
 		 * Load the configuration file. This an alias to Loader::config()
140 140
 		 * @param  string $config the config name to be loaded
141 141
 		 */
142
-		public static function load($config){
142
+		public static function load($config) {
143 143
 			Loader::config($config);
144 144
 		}
145 145
 
146 146
 		/**
147 147
 		 * Set the configuration for "base_url" if is not set in the configuration
148 148
 		 */
149
-		private static function setBaseUrlUsingServerVar(){
149
+		private static function setBaseUrlUsingServerVar() {
150 150
 			$logger = static::getLogger();
151
-			if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
152
-				if(ENVIRONMENT == 'production'){
151
+			if (!isset(self::$config['base_url']) || !is_url(self::$config['base_url'])) {
152
+				if (ENVIRONMENT == 'production') {
153 153
 					$logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
154 154
 				}
155 155
 				$baseUrl = null;
156 156
 				$protocol = 'http';
157
-				if(is_https()){
157
+				if (is_https()) {
158 158
 					$protocol = 'https';
159 159
 				}
160
-				$protocol .='://';
160
+				$protocol .= '://';
161 161
 
162
-				if (isset($_SERVER['SERVER_ADDR'])){
162
+				if (isset($_SERVER['SERVER_ADDR'])) {
163 163
 					$baseUrl = $_SERVER['SERVER_ADDR'];
164 164
 					//check if the server is running under IPv6
165
-					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
166
-						$baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
165
+					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE) {
166
+						$baseUrl = '[' . $_SERVER['SERVER_ADDR'] . ']';
167 167
 					}
168 168
 					$serverPort = 80;
169 169
 					if (isset($_SERVER['SERVER_PORT'])) {
170 170
 						$serverPort = $_SERVER['SERVER_PORT'];
171 171
 					}
172 172
 					$port = '';
173
-					if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
174
-						$port = ':'.$serverPort;
173
+					if ($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))) {
174
+						$port = ':' . $serverPort;
175 175
 					}
176
-					$port = ((($serverPort != '80' && ! is_https()) || ($serverPort != '443' && is_https())) ? ':' . $serverPort : '');
176
+					$port = ((($serverPort != '80' && !is_https()) || ($serverPort != '443' && is_https())) ? ':' . $serverPort : '');
177 177
 					$baseUrl = $protocol . $baseUrl . $port . substr(
178 178
 																		$_SERVER['SCRIPT_NAME'], 
179 179
 																		0, 
180 180
 																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
181 181
 																	);
182 182
 				}
183
-				else{
183
+				else {
184 184
 					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
185 185
 					$baseUrl = 'http://localhost/';
186 186
 				}
187 187
 				self::set('base_url', $baseUrl);
188 188
 			}
189
-			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
189
+			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') . '/';
190 190
 		}
191 191
 	}
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -128,8 +128,7 @@  discard block
 block discarded – undo
128 128
 				$logger->info('Delete config item ['.$item.']');
129 129
 				unset(self::$config[$item]);
130 130
 				return true;
131
-			}
132
-			else{
131
+			} else{
133 132
 				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
134 133
 				return false;
135 134
 			}
@@ -179,8 +178,7 @@  discard block
 block discarded – undo
179 178
 																		0, 
180 179
 																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
181 180
 																	);
182
-				}
183
-				else{
181
+				} else{
184 182
 					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
185 183
 					$baseUrl = 'http://localhost/';
186 184
 				}
Please login to merge, or discard this patch.
core/libraries/FormValidation.php 3 patches
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -22,10 +22,10 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
 
27 27
 
28
-     class FormValidation{
28
+        class FormValidation{
29 29
 		 
30 30
         /**
31 31
          * The form validation status
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
          */
61 61
         protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
62 62
         
63
-		/**
63
+        /**
64 64
          * Indicated if need force the validation to be failed
65 65
          * @var boolean
66 66
          */
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
             $this->logger =& class_loader('Log', 'classes');
101 101
             $this->logger->setLogger('Library::FormValidation');
102 102
            
103
-		   //Load form validation language message
103
+            //Load form validation language message
104 104
             Loader::lang('form_validation');
105 105
             $obj = & get_instance();
106 106
             $this->_errorsMessages  = array(
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
         /**
163 163
          * Set the form validation data
164 164
          * @param array $data the values to be validated
165
-		 *
165
+         *
166 166
          * @return FormValidation Current instance of object.
167 167
          */
168 168
         public function setData(array $data){
169 169
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
170 170
             $this->data = $data;
171
-			return $this;
171
+            return $this;
172 172
         }
173 173
 
174 174
         /**
@@ -179,11 +179,11 @@  discard block
 block discarded – undo
179 179
             return $this->data;
180 180
         }
181 181
 
182
-		/**
183
-		* Get the validation function name to validate a rule
184
-		*
185
-		* @return string the function name
186
-		*/
182
+        /**
183
+         * Get the validation function name to validate a rule
184
+         *
185
+         * @return string the function name
186
+         */
187 187
         protected function _toCallCase($funcName, $prefix='_validate') {
188 188
             $funcName = strtolower($funcName);
189 189
             $finalFuncName = $prefix;
@@ -253,12 +253,12 @@  discard block
 block discarded – undo
253 253
             $this->_forceFail = false;
254 254
 
255 255
             foreach ($this->getData() as $inputName => $inputVal) {
256
-    			if(is_array($this->data[$inputName])){
257
-    				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
-    			}
259
-    			else{
260
-    				$this->data[$inputName] = trim($this->data[$inputName]);
261
-    			}
256
+                if(is_array($this->data[$inputName])){
257
+                    $this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
+                }
259
+                else{
260
+                    $this->data[$inputName] = trim($this->data[$inputName]);
261
+                }
262 262
 
263 263
                 if (array_key_exists($inputName, $this->_rules)) {
264 264
                     foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
          *
278 278
          * @param string $inputField Name of the field or the data key to add a rule to
279 279
          * @param string $ruleSets PIPE seperated string of rules
280
-		 *
280
+         *
281 281
          * @return FormValidation Current instance of object.
282 282
          */
283 283
         public function setRule($inputField, $inputLabel, $ruleSets) {
@@ -291,8 +291,8 @@  discard block
 block discarded – undo
291 291
          * Takes an array of rules and uses setRule() to set them, accepts an array
292 292
          * of rule names rather than a pipe-delimited string as well.
293 293
          * @param array $ruleSets
294
-		 *
295
-		 * @return FormValidation Current instance of object.
294
+         *
295
+         * @return FormValidation Current instance of object.
296 296
          */
297 297
         public function setRules(array $ruleSets) {
298 298
             foreach ($ruleSets as $ruleSet) {
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
          * @param string $start Before block of errors gets displayed, HTML allowed.
315 315
          * @param string $end After the block of errors gets displayed, HTML allowed.
316 316
          *
317
-		 * @return FormValidation Current instance of object.
317
+         * @return FormValidation Current instance of object.
318 318
          */
319 319
         public function setErrorsDelimiter($start, $end) {
320 320
             $this->_allErrorsDelimiter[0] = $start;
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
          * @param string $start Displayed before each error.
330 330
          * @param string $end Displayed after each error.
331 331
          * 
332
-		 * @return FormValidation Current instance of object.
332
+         * @return FormValidation Current instance of object.
333 333
          */
334 334
         public function setErrorDelimiter($start, $end) {
335 335
             $this->_eachErrorDelimiter[0] = $start;
@@ -337,21 +337,21 @@  discard block
 block discarded – undo
337 337
             return $this;
338 338
         }
339 339
 
340
-		/**
341
-		* Get the each errors delimiters
342
-		*
343
-		* @return array
344
-		*/
345
-    	public function getErrorDelimiter() {
340
+        /**
341
+         * Get the each errors delimiters
342
+         *
343
+         * @return array
344
+         */
345
+        public function getErrorDelimiter() {
346 346
             return $this->_eachErrorDelimiter;
347 347
         }
348 348
 
349
-		/**
350
-		* Get the all errors delimiters
351
-		*
352
-		* @return array
353
-		*/
354
-    	public function getErrorsDelimiter() {
349
+        /**
350
+         * Get the all errors delimiters
351
+         *
352
+         * @return array
353
+         */
354
+        public function getErrorsDelimiter() {
355 355
             return $this->_allErrorsDelimiter;
356 356
         }
357 357
 
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
          *
390 390
          * @param string $inputName The form input name or data key
391 391
          * @param string $errorMessage Error to display
392
-		 *
392
+         *
393 393
          * @return formValidation Current instance of the object
394 394
          */
395 395
         public function setCustomError($inputName, $errorMessage) {
@@ -426,17 +426,17 @@  discard block
 block discarded – undo
426 426
          *
427 427
          * @param boolean $limit number of error to display or return
428 428
          * @param boolean $echo Whether or not the values are to be returned or displayed
429
-		 *
429
+         *
430 430
          * @return string Errors formatted for output
431 431
          */
432 432
         public function displayErrors($limit = null, $echo = true) {
433 433
             list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
434 434
             list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
435 435
             $errorOutput = $errorsStart;
436
-    		$i = 0;
436
+            $i = 0;
437 437
             if (!empty($this->_errors)) {
438 438
                 foreach ($this->_errors as $fieldName => $error) {
439
-        	    	if ($i === $limit) { 
439
+                    if ($i === $limit) { 
440 440
                         break; 
441 441
                     }
442 442
                     $errorOutput .= $errorStart;
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
          * Breaks up a PIPE seperated string of rules, and puts them into an array.
465 465
          *
466 466
          * @param string $ruleString String to be parsed.
467
-		 *
467
+         *
468 468
          * @return array Array of each value in original string.
469 469
          */
470 470
         protected function _parseRuleString($ruleString) {
@@ -477,10 +477,10 @@  discard block
 block discarded – undo
477 477
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
478 478
                 preg_match($rule, $ruleString, $regexRule);
479 479
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
480
-                 if(!empty($regexRule[0])){
481
-                     $ruleSets[] = $regexRule[0];
482
-                 }
483
-                 $ruleStringRegex = explode('|', $ruleStringTemp);
480
+                    if(!empty($regexRule[0])){
481
+                        $ruleSets[] = $regexRule[0];
482
+                    }
483
+                    $ruleStringRegex = explode('|', $ruleStringTemp);
484 484
                 foreach ($ruleStringRegex as $rule) {
485 485
                     $rule = trim($rule);
486 486
                     if($rule){
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
                 } else {
497 497
                     $ruleSets[] = $ruleString;
498 498
                 }
499
-             }
499
+                }
500 500
             return $ruleSets;
501 501
         }
502 502
 
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
          * Returns whether or not a field obtains the rule "required".
505 505
          *
506 506
          * @param string $fieldName Field to check if required.
507
-		 *
507
+         *
508 508
          * @return boolean Whether or not the field is required.
509 509
          */
510 510
         protected function _fieldIsRequired($fieldName) {
@@ -539,13 +539,13 @@  discard block
 block discarded – undo
539 539
             return;
540 540
         }
541 541
 
542
-		/**
543
-		* Set error for the given field or key
544
-		*
545
-		* @param string $inputName the input or key name
546
-		* @param string $ruleName the rule name
547
-		* @param array|string $replacements
548
-		*/
542
+        /**
543
+         * Set error for the given field or key
544
+         *
545
+         * @param string $inputName the input or key name
546
+         * @param string $ruleName the rule name
547
+         * @param array|string $replacements
548
+         */
549 549
         protected function _setError($inputName, $ruleName, $replacements = array()) {
550 550
             $rulePhraseKeyParts = explode(',', $ruleName);
551 551
             $rulePhrase = null;
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
             }
563 563
             // Type cast to array in case it's a string
564 564
             $replacements = (array) $replacements;
565
-			$replacementCount = count($replacements);
565
+            $replacementCount = count($replacements);
566 566
             for ($i = 1; $i <= $replacementCount; $i++) {
567 567
                 $key = $i - 1;
568 568
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
@@ -580,11 +580,11 @@  discard block
 block discarded – undo
580 580
          *
581 581
          * @param type $inputArg
582 582
          * @param string $callbackFunc
583
-		 *
583
+         *
584 584
          * @return mixed
585 585
          */
586 586
         protected function _runCallback($inputArg, $callbackFunc) {
587
-			return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
587
+            return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
588 588
         }
589 589
 
590 590
         /**
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
          * arguments.
594 594
          *
595 595
          * @param string $callbackFunc
596
-		 *
596
+         *
597 597
          * @return mixed
598 598
          */
599 599
         protected function _runEmptyCallback($callbackFunc) {
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
          * Gets a specific label of a specific field input name.
605 605
          *
606 606
          * @param string $inputName
607
-		 *
607
+         *
608 608
          * @return string
609 609
          */
610 610
         protected function _getLabel($inputName) {
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
          * @param  string $ruleName  the rule name for this validation ("required")
618 618
          * @param  array  $ruleArgs  the rules argument
619 619
          */
620
-		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
620
+        protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
621 621
             $inputVal = $this->post($inputName);
622 622
             if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
623 623
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
@@ -625,8 +625,8 @@  discard block
 block discarded – undo
625 625
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
626 626
                 }
627 627
             } 
628
-			else if($inputVal == '') {
629
-				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
628
+            else if($inputVal == '') {
629
+                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
630 630
             }
631 631
         }
632 632
 
@@ -650,10 +650,10 @@  discard block
 block discarded – undo
650 650
          */
651 651
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
652 652
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
653
-				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
654
-				if(! $result){
655
-					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
656
-				}
653
+                $result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
654
+                if(! $result){
655
+                    $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
656
+                }
657 657
             }
658 658
         }
659 659
 
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
                         continue;
686 686
                     }
687 687
                 } 
688
-				else{
688
+                else{
689 689
                     if ($inputVal == $doNotEqual) {
690 690
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
691 691
                         continue;
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
          * @param  string $ruleName  the rule name for this validation ("less_than")
778 778
          * @param  array  $ruleArgs  the rules argument
779 779
          */
780
-    	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
780
+        protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
781 781
             $inputVal = $this->post($inputName);
782 782
             if ($inputVal >= $ruleArgs[1]) { 
783 783
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
          * @param  string $ruleName  the rule name for this validation ("greater_than")
794 794
          * @param  array  $ruleArgs  the rules argument
795 795
          */
796
-    	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
796
+        protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
797 797
             $inputVal = $this->post($inputName);
798 798
             if ($inputVal <= $ruleArgs[1]) {
799 799
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
          * @param  string $ruleName  the rule name for this validation ("numeric")
810 810
          * @param  array  $ruleArgs  the rules argument
811 811
          */
812
-    	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
812
+        protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
813 813
             $inputVal = $this->post($inputName);
814 814
             if (! is_numeric($inputVal)) {
815 815
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -825,17 +825,17 @@  discard block
 block discarded – undo
825 825
          * @param  string $ruleName  the rule name for this validation ("exists")
826 826
          * @param  array  $ruleArgs  the rules argument
827 827
          */
828
-		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
828
+        protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
829 829
             $inputVal = $this->post($inputName);
830
-    		$obj = & get_instance();
831
-    		if(! isset($obj->database)){
832
-    			return;
833
-    		}
834
-    		list($table, $column) = explode('.', $ruleArgs[1]);
835
-    		$obj->database->from($table)
836
-    			          ->where($column, $inputVal)
837
-    			          ->get();
838
-    		$nb = $obj->database->numRows();
830
+            $obj = & get_instance();
831
+            if(! isset($obj->database)){
832
+                return;
833
+            }
834
+            list($table, $column) = explode('.', $ruleArgs[1]);
835
+            $obj->database->from($table)
836
+                            ->where($column, $inputVal)
837
+                            ->get();
838
+            $nb = $obj->database->numRows();
839 839
             if ($nb == 0) {
840 840
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
841 841
                     return;
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
          * @param  string $ruleName  the rule name for this validation ("is_unique")
851 851
          * @param  array  $ruleArgs  the rules argument
852 852
          */
853
-    	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
853
+        protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
854 854
             $inputVal = $this->post($inputName);
855 855
             if (! is_object($this->databaseInstance)){
856 856
                 $obj = & get_instance();
@@ -860,11 +860,11 @@  discard block
 block discarded – undo
860 860
                     return;
861 861
                 }
862 862
             }
863
-    		list($table, $column) = explode('.', $ruleArgs[1]);
864
-    		$this->databaseInstance->getQueryBuilder()->from($table)
865
-    			                                      ->where($column, $inputVal);
866
-    		$this->databaseInstance->get();
867
-    		if ($this->databaseInstance->numRows() != 0) {
863
+            list($table, $column) = explode('.', $ruleArgs[1]);
864
+            $this->databaseInstance->getQueryBuilder()->from($table)
865
+                                                        ->where($column, $inputVal);
866
+            $this->databaseInstance->get();
867
+            if ($this->databaseInstance->numRows() != 0) {
868 868
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
869 869
                     return;
870 870
                 }
@@ -878,9 +878,9 @@  discard block
 block discarded – undo
878 878
          * @param  string $ruleName  the rule name for this validation ("is_unique_update")
879 879
          * @param  array  $ruleArgs  the rules argument
880 880
          */
881
-    	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
881
+        protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
882 882
             $inputVal = $this->post($inputName);
883
-    		if (! is_object($this->databaseInstance)){
883
+            if (! is_object($this->databaseInstance)){
884 884
                 $obj = & get_instance();
885 885
                 if(isset($obj->database)){
886 886
                     $this->databaseInstance = $obj->database;
@@ -888,17 +888,17 @@  discard block
 block discarded – undo
888 888
                     return;
889 889
                 }
890 890
             }
891
-    		$data = explode(',', $ruleArgs[1]);
892
-    		if(count($data) < 2){
893
-    			return;
894
-    		}
895
-    		list($table, $column) = explode('.', $data[0]);
896
-    		list($field, $val) = explode('=', $data[1]);
897
-    		$this->databaseInstance->getQueryBuilder()->from($table)
898
-                                			          ->where($column, $inputVal)
899
-                                            		  ->where($field, '!=', trim($val));
891
+            $data = explode(',', $ruleArgs[1]);
892
+            if(count($data) < 2){
893
+                return;
894
+            }
895
+            list($table, $column) = explode('.', $data[0]);
896
+            list($field, $val) = explode('=', $data[1]);
897
+            $this->databaseInstance->getQueryBuilder()->from($table)
898
+                                                        ->where($column, $inputVal)
899
+                                                        ->where($field, '!=', trim($val));
900 900
             $this->databaseInstance->get();
901
-    		if ($this->databaseInstance->numRows() != 0) {
901
+            if ($this->databaseInstance->numRows() != 0) {
902 902
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
903 903
                     return;
904 904
                 }
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
          */
915 915
         protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
916 916
             $inputVal = $this->post($inputName);
917
-    		$list = explode(',', $ruleArgs[1]);
917
+            $list = explode(',', $ruleArgs[1]);
918 918
             $list = array_map('trim', $list);
919 919
             if (! in_array($inputVal, $list)) {
920 920
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -932,7 +932,7 @@  discard block
 block discarded – undo
932 932
          */
933 933
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
934 934
             $inputVal = $this->post($inputName);
935
-    		$regex = $ruleArgs[1];
935
+            $regex = $ruleArgs[1];
936 936
             if (! preg_match($regex, $inputVal)) {
937 937
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
938 938
                     return;
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -25,13 +25,13 @@  discard block
 block discarded – undo
25 25
     */
26 26
 
27 27
 
28
-     class FormValidation{
28
+     class FormValidation {
29 29
 		 
30 30
         /**
31 31
          * The form validation status
32 32
          * @var boolean
33 33
          */
34
-        protected $_success  = false;
34
+        protected $_success = false;
35 35
 
36 36
         /**
37 37
          * The list of errors messages
@@ -40,31 +40,31 @@  discard block
 block discarded – undo
40 40
         protected $_errorsMessages = array();
41 41
         
42 42
         // Array of rule sets, fieldName => PIPE seperated ruleString
43
-        protected $_rules             = array();
43
+        protected $_rules = array();
44 44
         
45 45
         // Array of errors, niceName => Error Message
46
-        protected $_errors             = array();
46
+        protected $_errors = array();
47 47
         
48 48
         // Array of post Key => Nice name labels
49
-        protected $_labels          = array();
49
+        protected $_labels = array();
50 50
         
51 51
         /**
52 52
          * The errors delimiters
53 53
          * @var array
54 54
          */
55
-        protected $_allErrorsDelimiter   = array('<div class="error">', '</div>');
55
+        protected $_allErrorsDelimiter = array('<div class="error">', '</div>');
56 56
 
57 57
         /**
58 58
          * The each error delimiter
59 59
          * @var array
60 60
          */
61
-        protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
61
+        protected $_eachErrorDelimiter = array('<p class="error">', '</p>');
62 62
         
63 63
 		/**
64 64
          * Indicated if need force the validation to be failed
65 65
          * @var boolean
66 66
          */
67
-        protected $_forceFail            = false;
67
+        protected $_forceFail = false;
68 68
 
69 69
         /**
70 70
          * The list of the error messages overrides by the original
@@ -97,13 +97,13 @@  discard block
 block discarded – undo
97 97
          * @return void
98 98
          */
99 99
         public function __construct() {
100
-            $this->logger =& class_loader('Log', 'classes');
100
+            $this->logger = & class_loader('Log', 'classes');
101 101
             $this->logger->setLogger('Library::FormValidation');
102 102
            
103 103
 		   //Load form validation language message
104 104
             Loader::lang('form_validation');
105 105
             $obj = & get_instance();
106
-            $this->_errorsMessages  = array(
106
+            $this->_errorsMessages = array(
107 107
                         'required'         => $obj->lang->get('fv_required'),
108 108
                         'min_length'       => $obj->lang->get('fv_min_length'),
109 109
                         'max_length'       => $obj->lang->get('fv_max_length'),
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
          * Set the database instance
134 134
          * @param object $database the database instance
135 135
          */
136
-        public function setDatabase(Database $database){
136
+        public function setDatabase(Database $database) {
137 137
             $this->databaseInstance = $database;
138 138
             return $this;
139 139
         }
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
          * Get the database instance
143 143
          * @return object the database instance
144 144
          */
145
-        public function getDatabase(){
145
+        public function getDatabase() {
146 146
             return $this->databaseInstance;
147 147
         }
148 148
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		 *
166 166
          * @return FormValidation Current instance of object.
167 167
          */
168
-        public function setData(array $data){
168
+        public function setData(array $data) {
169 169
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
170 170
             $this->data = $data;
171 171
 			return $this;
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
          * Get the form validation data
176 176
          * @return array the form validation data to be validated
177 177
          */
178
-        public function getData(){
178
+        public function getData() {
179 179
             return $this->data;
180 180
         }
181 181
 
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 		*
185 185
 		* @return string the function name
186 186
 		*/
187
-        protected function _toCallCase($funcName, $prefix='_validate') {
187
+        protected function _toCallCase($funcName, $prefix = '_validate') {
188 188
             $funcName = strtolower($funcName);
189 189
             $finalFuncName = $prefix;
190 190
             foreach (explode('_', $funcName) as $funcNamePart) {
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
          * @return boolean Whether or not the form has been submitted or the data is available for validation.
209 209
          */
210 210
         public function canDoValidation() {
211
-            return get_instance()->request->method() === 'POST' || ! empty($this->data);
211
+            return get_instance()->request->method() === 'POST' || !empty($this->data);
212 212
         }
213 213
 
214 214
         /**
@@ -228,14 +228,14 @@  discard block
 block discarded – undo
228 228
          * Validate the CSRF 
229 229
          * @return void 
230 230
          */
231
-        protected function validateCSRF(){
232
-            if(get_instance()->request->method() == 'POST'){
231
+        protected function validateCSRF() {
232
+            if (get_instance()->request->method() == 'POST') {
233 233
                 $this->logger->debug('Check if CSRF is enabled in configuration');
234 234
                 //first check for CSRF
235
-                if (get_config('csrf_enable', false) && ! Security::validateCSRF()){
235
+                if (get_config('csrf_enable', false) && !Security::validateCSRF()) {
236 236
                     show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
237 237
                 }
238
-                else{
238
+                else {
239 239
                     $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
240 240
                 }
241 241
             }
@@ -253,10 +253,10 @@  discard block
 block discarded – undo
253 253
             $this->_forceFail = false;
254 254
 
255 255
             foreach ($this->getData() as $inputName => $inputVal) {
256
-    			if(is_array($this->data[$inputName])){
256
+    			if (is_array($this->data[$inputName])) {
257 257
     				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258 258
     			}
259
-    			else{
259
+    			else {
260 260
     				$this->data[$inputName] = trim($this->data[$inputName]);
261 261
     			}
262 262
 
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
         public function setRule($inputField, $inputLabel, $ruleSets) {
284 284
             $this->_rules[$inputField] = $ruleSets;
285 285
             $this->_labels[$inputField] = $inputLabel;
286
-            $this->logger->info('Set the field rule: name [' .$inputField. '], label [' .$inputLabel. '], rules [' .$ruleSets. ']');
286
+            $this->logger->info('Set the field rule: name [' . $inputField . '], label [' . $inputLabel . '], rules [' . $ruleSets . ']');
287 287
             return $this;
288 288
         }
289 289
 
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
             }
448 448
             $errorOutput .= $errorsEnd;
449 449
             echo ($echo) ? $errorOutput : '';
450
-            return (! $echo) ? $errorOutput : null;
450
+            return (!$echo) ? $errorOutput : null;
451 451
         }
452 452
 
453 453
         /**
@@ -472,25 +472,25 @@  discard block
 block discarded – undo
472 472
             /*
473 473
             //////////////// hack for regex rule that can contain "|"
474 474
             */
475
-            if(strpos($ruleString, 'regex') !== false){
475
+            if (strpos($ruleString, 'regex') !== false) {
476 476
                 $regexRule = array();
477 477
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
478 478
                 preg_match($rule, $ruleString, $regexRule);
479 479
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
480
-                 if(!empty($regexRule[0])){
480
+                 if (!empty($regexRule[0])) {
481 481
                      $ruleSets[] = $regexRule[0];
482 482
                  }
483 483
                  $ruleStringRegex = explode('|', $ruleStringTemp);
484 484
                 foreach ($ruleStringRegex as $rule) {
485 485
                     $rule = trim($rule);
486
-                    if($rule){
486
+                    if ($rule) {
487 487
                         $ruleSets[] = $rule;
488 488
                     }
489 489
                 }
490 490
                  
491 491
             }
492 492
             /***********************************/
493
-            else{
493
+            else {
494 494
                 if (strpos($ruleString, '|') !== FALSE) {
495 495
                     $ruleSets = explode('|', $ruleString);
496 496
                 } else {
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
          * @return void
523 523
          */
524 524
         protected function _validateRule($inputName, $inputVal, $ruleName) {
525
-            $this->logger->debug('Rule validation of field [' .$inputName. '], value [' .$inputVal. '], rule [' .$ruleName. ']');
525
+            $this->logger->debug('Rule validation of field [' . $inputName . '], value [' . $inputVal . '], rule [' . $ruleName . ']');
526 526
             // Array to store args
527 527
             $ruleArgs = array();
528 528
 
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
                 $key = $i - 1;
568 568
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
569 569
             }
570
-            if (! array_key_exists($inputName, $this->_errors)) {
570
+            if (!array_key_exists($inputName, $this->_errors)) {
571 571
                 $this->_errors[$inputName] = $rulePhrase;
572 572
             }
573 573
         }
@@ -619,13 +619,13 @@  discard block
 block discarded – undo
619 619
          */
620 620
 		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
621 621
             $inputVal = $this->post($inputName);
622
-            if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
622
+            if (array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
623 623
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
624 624
                 if ($inputVal == '' && $callbackReturn == true) {
625 625
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
626 626
                 }
627 627
             } 
628
-			else if($inputVal == '') {
628
+			else if ($inputVal == '') {
629 629
 				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
630 630
             }
631 631
         }
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
652 652
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
653 653
 				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
654
-				if(! $result){
654
+				if (!$result) {
655 655
 					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
656 656
 				}
657 657
             }
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
                         continue;
686 686
                     }
687 687
                 } 
688
-				else{
688
+				else {
689 689
                     if ($inputVal == $doNotEqual) {
690 690
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
691 691
                         continue;
@@ -715,8 +715,8 @@  discard block
 block discarded – undo
715 715
          */
716 716
         protected function _validateValidEmail($inputName, $ruleName, array $ruleArgs) {
717 717
             $inputVal = $this->post($inputName);
718
-            if (! preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
719
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
718
+            if (!preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
719
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
720 720
                     return;
721 721
                 }
722 722
                 $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
@@ -732,7 +732,7 @@  discard block
 block discarded – undo
732 732
         protected function _validateExactLength($inputName, $ruleName, array $ruleArgs) {
733 733
             $inputVal = $this->post($inputName);
734 734
             if (strlen($inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
735
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
735
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
736 736
                     return;
737 737
                 }
738 738
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
         protected function _validateMaxLength($inputName, $ruleName, array $ruleArgs) {
749 749
             $inputVal = $this->post($inputName);
750 750
             if (strlen($inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
751
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
751
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
752 752
                     return;
753 753
                 }
754 754
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
         protected function _validateMinLength($inputName, $ruleName, array $ruleArgs) {
765 765
             $inputVal = $this->post($inputName);
766 766
             if (strlen($inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
767
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
767
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
768 768
                     return;
769 769
                 }
770 770
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
     	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
781 781
             $inputVal = $this->post($inputName);
782 782
             if ($inputVal >= $ruleArgs[1]) { 
783
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
783
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
784 784
                     return;
785 785
                 }
786 786
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -796,7 +796,7 @@  discard block
 block discarded – undo
796 796
     	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
797 797
             $inputVal = $this->post($inputName);
798 798
             if ($inputVal <= $ruleArgs[1]) {
799
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
799
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
800 800
                     return;
801 801
                 }
802 802
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -811,8 +811,8 @@  discard block
 block discarded – undo
811 811
          */
812 812
     	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
813 813
             $inputVal = $this->post($inputName);
814
-            if (! is_numeric($inputVal)) {
815
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
814
+            if (!is_numeric($inputVal)) {
815
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
816 816
                     return;
817 817
                 }
818 818
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
829 829
             $inputVal = $this->post($inputName);
830 830
     		$obj = & get_instance();
831
-    		if(! isset($obj->database)){
831
+    		if (!isset($obj->database)) {
832 832
     			return;
833 833
     		}
834 834
     		list($table, $column) = explode('.', $ruleArgs[1]);
@@ -837,7 +837,7 @@  discard block
 block discarded – undo
837 837
     			          ->get();
838 838
     		$nb = $obj->database->numRows();
839 839
             if ($nb == 0) {
840
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
840
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
841 841
                     return;
842 842
                 }
843 843
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -852,9 +852,9 @@  discard block
 block discarded – undo
852 852
          */
853 853
     	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
854 854
             $inputVal = $this->post($inputName);
855
-            if (! is_object($this->databaseInstance)){
855
+            if (!is_object($this->databaseInstance)) {
856 856
                 $obj = & get_instance();
857
-                if(isset($obj->database)){
857
+                if (isset($obj->database)) {
858 858
                     $this->databaseInstance = $obj->database;
859 859
                 } else {
860 860
                     return;
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
     			                                      ->where($column, $inputVal);
866 866
     		$this->databaseInstance->get();
867 867
     		if ($this->databaseInstance->numRows() != 0) {
868
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
868
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
869 869
                     return;
870 870
                 }
871 871
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -880,16 +880,16 @@  discard block
 block discarded – undo
880 880
          */
881 881
     	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
882 882
             $inputVal = $this->post($inputName);
883
-    		if (! is_object($this->databaseInstance)){
883
+    		if (!is_object($this->databaseInstance)) {
884 884
                 $obj = & get_instance();
885
-                if(isset($obj->database)){
885
+                if (isset($obj->database)) {
886 886
                     $this->databaseInstance = $obj->database;
887 887
                 } else {
888 888
                     return;
889 889
                 }
890 890
             }
891 891
     		$data = explode(',', $ruleArgs[1]);
892
-    		if(count($data) < 2){
892
+    		if (count($data) < 2) {
893 893
     			return;
894 894
     		}
895 895
     		list($table, $column) = explode('.', $data[0]);
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
                                             		  ->where($field, '!=', trim($val));
900 900
             $this->databaseInstance->get();
901 901
     		if ($this->databaseInstance->numRows() != 0) {
902
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
902
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
903 903
                     return;
904 904
                 }
905 905
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -916,8 +916,8 @@  discard block
 block discarded – undo
916 916
             $inputVal = $this->post($inputName);
917 917
     		$list = explode(',', $ruleArgs[1]);
918 918
             $list = array_map('trim', $list);
919
-            if (! in_array($inputVal, $list)) {
920
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
919
+            if (!in_array($inputVal, $list)) {
920
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
921 921
                     return;
922 922
                 }
923 923
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -933,8 +933,8 @@  discard block
 block discarded – undo
933 933
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
934 934
             $inputVal = $this->post($inputName);
935 935
     		$regex = $ruleArgs[1];
936
-            if (! preg_match($regex, $inputVal)) {
937
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
936
+            if (!preg_match($regex, $inputVal)) {
937
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
938 938
                     return;
939 939
                 }
940 940
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
Please login to merge, or discard this patch.
Braces   +4 added lines, -8 removed lines patch added patch discarded remove patch
@@ -234,8 +234,7 @@  discard block
 block discarded – undo
234 234
                 //first check for CSRF
235 235
                 if (get_config('csrf_enable', false) && ! Security::validateCSRF()){
236 236
                     show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
237
-                }
238
-                else{
237
+                } else{
239 238
                     $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
240 239
                 }
241 240
             }
@@ -255,8 +254,7 @@  discard block
 block discarded – undo
255 254
             foreach ($this->getData() as $inputName => $inputVal) {
256 255
     			if(is_array($this->data[$inputName])){
257 256
     				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
258
-    			}
259
-    			else{
257
+    			} else{
260 258
     				$this->data[$inputName] = trim($this->data[$inputName]);
261 259
     			}
262 260
 
@@ -624,8 +622,7 @@  discard block
 block discarded – undo
624 622
                 if ($inputVal == '' && $callbackReturn == true) {
625 623
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
626 624
                 }
627
-            } 
628
-			else if($inputVal == '') {
625
+            } else if($inputVal == '') {
629 626
 				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
630 627
             }
631 628
         }
@@ -684,8 +681,7 @@  discard block
 block discarded – undo
684 681
                         $this->_setError($inputName, $ruleName . ',post:key', array($this->_getLabel($inputName), $this->_getLabel(str_replace('post:', '', $doNotEqual))));
685 682
                         continue;
686 683
                     }
687
-                } 
688
-				else{
684
+                } else{
689 685
                     if ($inputVal == $doNotEqual) {
690 686
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
691 687
                         continue;
Please login to merge, or discard this patch.
core/libraries/Form.php 2 patches
Indentation   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -1,320 +1,320 @@
 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
-				$error =  isset($errors[$name]) ? $errors[$name] : null;
114
-				if($error){
115
-					list($errorStart, $errorEnd) = $obj->formvalidation->getErrorDelimiter();
116
-					$return = $errorStart . $error . $errorEnd;
117
-				}
118
-			}
119
-			return $return;
120
-		}
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
+                $error =  isset($errors[$name]) ? $errors[$name] : null;
114
+                if($error){
115
+                    list($errorStart, $errorEnd) = $obj->formvalidation->getErrorDelimiter();
116
+                    $return = $errorStart . $error . $errorEnd;
117
+                }
118
+            }
119
+            return $return;
120
+        }
121 121
 
122
-		/**
123
-		 * Get the form field value
124
-		 * @param  string $name    the form field name
125
-		 * @param  mixed $default the default value if can not found the given form field name
126
-		 * @return mixed the form field value if is set, otherwise return the default value.
127
-		 */
128
-		public static function value($name, $default = null){
129
-			$value = get_instance()->request->query($name);
130
-			return $value ? $value : $default;
131
-		}
122
+        /**
123
+         * Get the form field value
124
+         * @param  string $name    the form field name
125
+         * @param  mixed $default the default value if can not found the given form field name
126
+         * @return mixed the form field value if is set, otherwise return the default value.
127
+         */
128
+        public static function value($name, $default = null){
129
+            $value = get_instance()->request->query($name);
130
+            return $value ? $value : $default;
131
+        }
132 132
 
133
-		/**
134
-		 * Generate the form label html content
135
-		 * @param  string $label      the title of the label
136
-		 * @param  string $for        the value of the label "for" attribute
137
-		 * @param  array  $attributes the additional attributes to be added
138
-		 * @return string the generated label html content
139
-		 */
140
-		public static function label($label, $for = '', array $attributes = array()){
141
-			$str = '<label';
142
-			if($for){
143
-				$str .= ' for = "'.$for.'"';
144
-			}
145
-			$str .= attributes_to_string($attributes);
146
-			$str .= '>';
147
-			$str .= $label.'</label>';
148
-			return $str;
149
-		}
133
+        /**
134
+         * Generate the form label html content
135
+         * @param  string $label      the title of the label
136
+         * @param  string $for        the value of the label "for" attribute
137
+         * @param  array  $attributes the additional attributes to be added
138
+         * @return string the generated label html content
139
+         */
140
+        public static function label($label, $for = '', array $attributes = array()){
141
+            $str = '<label';
142
+            if($for){
143
+                $str .= ' for = "'.$for.'"';
144
+            }
145
+            $str .= attributes_to_string($attributes);
146
+            $str .= '>';
147
+            $str .= $label.'</label>';
148
+            return $str;
149
+        }
150 150
 
151
-		/**
152
-		 * Generate the form field for input like "text", "email", "password", etc.
153
-		 * @param  string $name       the form field name
154
-		 * @param  mixed $value      the form field value to be set
155
-		 * @param  array  $attributes the additional attributes to be added in the form input
156
-		 * @param  string $type       the type of the form field (password, text, submit, button, etc.)
157
-		 * @return string             the generated form field html content for the input
158
-		 */
159
-		public static function input($name, $value = null, array $attributes = array(), $type = 'text'){
160
-			$str = null;
161
-			$str .= '<input name = "'.$name.'" value = "'.$value.'" type = "'.$type.'"';
162
-			$str .= attributes_to_string($attributes);
163
-			$str .= '/>';
164
-			return $str;
165
-		}
151
+        /**
152
+         * Generate the form field for input like "text", "email", "password", etc.
153
+         * @param  string $name       the form field name
154
+         * @param  mixed $value      the form field value to be set
155
+         * @param  array  $attributes the additional attributes to be added in the form input
156
+         * @param  string $type       the type of the form field (password, text, submit, button, etc.)
157
+         * @return string             the generated form field html content for the input
158
+         */
159
+        public static function input($name, $value = null, array $attributes = array(), $type = 'text'){
160
+            $str = null;
161
+            $str .= '<input name = "'.$name.'" value = "'.$value.'" type = "'.$type.'"';
162
+            $str .= attributes_to_string($attributes);
163
+            $str .= '/>';
164
+            return $str;
165
+        }
166 166
 		
167
-		/**
168
-		 * Generate the form field for "text"
169
-		 * @see Form::input() for more details
170
-		 */
171
-		public static function text($name, $value = null, array $attributes = array()){
172
-			return self::input($name, $value, $attributes, 'text');
173
-		}
167
+        /**
168
+         * Generate the form field for "text"
169
+         * @see Form::input() for more details
170
+         */
171
+        public static function text($name, $value = null, array $attributes = array()){
172
+            return self::input($name, $value, $attributes, 'text');
173
+        }
174 174
 
175
-		/**
176
-		 * Generate the form field for "password"
177
-		 * @see Form::input() for more details
178
-		 */
179
-		public static function password($name, $value = null, array $attributes = array()){
180
-			return self::input($name, $value, $attributes, 'password');
181
-		}
175
+        /**
176
+         * Generate the form field for "password"
177
+         * @see Form::input() for more details
178
+         */
179
+        public static function password($name, $value = null, array $attributes = array()){
180
+            return self::input($name, $value, $attributes, 'password');
181
+        }
182 182
 
183
-		/**
184
-		 * Generate the form field for "radio"
185
-		 * @see Form::input() for more details
186
-		 */
187
-		public static function radio($name, $value = null,  $checked = false, array $attributes = array()){
188
-			if($checked){
189
-				$attributes['checked'] = true;
190
-			}
191
-			return self::input($name, $value, $attributes, 'radio');
192
-		}
183
+        /**
184
+         * Generate the form field for "radio"
185
+         * @see Form::input() for more details
186
+         */
187
+        public static function radio($name, $value = null,  $checked = false, array $attributes = array()){
188
+            if($checked){
189
+                $attributes['checked'] = true;
190
+            }
191
+            return self::input($name, $value, $attributes, 'radio');
192
+        }
193 193
 
194
-		/**
195
-		 * Generate the form field for "checkbox"
196
-		 * @see Form::input() for more details
197
-		 */
198
-		public static function checkbox($name, $value = null, $checked = false, array $attributes = array()){
199
-			if($checked){
200
-				$attributes['checked'] = true;
201
-			}
202
-			return self::input($name, $value, $attributes, 'checkbox');
203
-		}
194
+        /**
195
+         * Generate the form field for "checkbox"
196
+         * @see Form::input() for more details
197
+         */
198
+        public static function checkbox($name, $value = null, $checked = false, array $attributes = array()){
199
+            if($checked){
200
+                $attributes['checked'] = true;
201
+            }
202
+            return self::input($name, $value, $attributes, 'checkbox');
203
+        }
204 204
 
205
-		/**
206
-		 * Generate the form field for "number"
207
-		 * @see Form::input() for more details
208
-		 */
209
-		public static function number($name, $value = null, array $attributes = array()){
210
-			return self::input($name, $value, $attributes, 'number');
211
-		}
205
+        /**
206
+         * Generate the form field for "number"
207
+         * @see Form::input() for more details
208
+         */
209
+        public static function number($name, $value = null, array $attributes = array()){
210
+            return self::input($name, $value, $attributes, 'number');
211
+        }
212 212
 
213
-		/**
214
-		 * Generate the form field for "phone"
215
-		 * @see Form::input() for more details
216
-		 */
217
-		public static function phone($name, $value = null, array $attributes = array()){
218
-			return self::input($name, $value, $attributes, 'phone');
219
-		}
213
+        /**
214
+         * Generate the form field for "phone"
215
+         * @see Form::input() for more details
216
+         */
217
+        public static function phone($name, $value = null, array $attributes = array()){
218
+            return self::input($name, $value, $attributes, 'phone');
219
+        }
220 220
 
221
-		/**
222
-		 * Generate the form field for "email"
223
-		 * @see Form::input() for more details
224
-		 */
225
-		public static function email($name, $value = null, array $attributes = array()){
226
-			return self::input($name, $value, $attributes, 'email');
227
-		}
221
+        /**
222
+         * Generate the form field for "email"
223
+         * @see Form::input() for more details
224
+         */
225
+        public static function email($name, $value = null, array $attributes = array()){
226
+            return self::input($name, $value, $attributes, 'email');
227
+        }
228 228
 		
229
-		/**
230
-		 * Generate the form field for "search"
231
-		 * @see Form::input() for more details
232
-		 */
233
-		public static function search($name, $value = null, array $attributes = array()){
234
-			return self::input($name, $value, $attributes, 'search');
235
-		}
229
+        /**
230
+         * Generate the form field for "search"
231
+         * @see Form::input() for more details
232
+         */
233
+        public static function search($name, $value = null, array $attributes = array()){
234
+            return self::input($name, $value, $attributes, 'search');
235
+        }
236 236
 		
237
-		/**
238
-		 * Generate the form field for "hidden"
239
-		 * @see Form::input() for more details
240
-		 */
241
-		public static function hidden($name, $value = null, array $attributes = array()){
242
-			return self::input($name, $value, $attributes, 'hidden');
243
-		}
237
+        /**
238
+         * Generate the form field for "hidden"
239
+         * @see Form::input() for more details
240
+         */
241
+        public static function hidden($name, $value = null, array $attributes = array()){
242
+            return self::input($name, $value, $attributes, 'hidden');
243
+        }
244 244
 		
245
-		/**
246
-		 * Generate the form field for "file"
247
-		 * @see Form::input() for more details
248
-		 */
249
-		public static function file($name, array $attributes = array()){
250
-			return self::input($name, null, $attributes, 'file');
251
-		}
245
+        /**
246
+         * Generate the form field for "file"
247
+         * @see Form::input() for more details
248
+         */
249
+        public static function file($name, array $attributes = array()){
250
+            return self::input($name, null, $attributes, 'file');
251
+        }
252 252
 		
253
-		/**
254
-		 * Generate the form field for "button"
255
-		 * @see Form::input() for more details
256
-		 */
257
-		public static function button($name, $value = null, array $attributes = array()){
258
-			return self::input($name, $value, $attributes, 'button');
259
-		}
253
+        /**
254
+         * Generate the form field for "button"
255
+         * @see Form::input() for more details
256
+         */
257
+        public static function button($name, $value = null, array $attributes = array()){
258
+            return self::input($name, $value, $attributes, 'button');
259
+        }
260 260
 		
261
-		/**
262
-		 * Generate the form field for "reset"
263
-		 * @see Form::input() for more details
264
-		 */
265
-		public static function reset($name, $value = null, array $attributes = array()){
266
-			return self::input($name, $value, $attributes, 'reset');
267
-		}
261
+        /**
262
+         * Generate the form field for "reset"
263
+         * @see Form::input() for more details
264
+         */
265
+        public static function reset($name, $value = null, array $attributes = array()){
266
+            return self::input($name, $value, $attributes, 'reset');
267
+        }
268 268
 		
269
-		/**
270
-		 * Generate the form field for "submit"
271
-		 * @see Form::input() for more details
272
-		 */
273
-		public static function submit($name, $value = null, array $attributes = array()){
274
-			return self::input($name, $value, $attributes, 'submit');
275
-		}
269
+        /**
270
+         * Generate the form field for "submit"
271
+         * @see Form::input() for more details
272
+         */
273
+        public static function submit($name, $value = null, array $attributes = array()){
274
+            return self::input($name, $value, $attributes, 'submit');
275
+        }
276 276
 
277
-		/**
278
-		 * Generate the form field for textarea
279
-		 * @param  string $name       the name of the textarea field
280
-		 * @param  string $value      the textarea field value
281
-		 * @param  array  $attributes the additional attributes to be added
282
-		 * @return string             the generated textarea form html content
283
-		 */
284
-		public static function textarea($name, $value = '', array $attributes = array()){
285
-			$str = null;
286
-			$str .= '<textarea name = "'.$name.'"';
287
-			$str .= attributes_to_string($attributes);
288
-			$str .= '>';
289
-			$str .= $value.'</textarea>';
290
-			return $str;
291
-		}
277
+        /**
278
+         * Generate the form field for textarea
279
+         * @param  string $name       the name of the textarea field
280
+         * @param  string $value      the textarea field value
281
+         * @param  array  $attributes the additional attributes to be added
282
+         * @return string             the generated textarea form html content
283
+         */
284
+        public static function textarea($name, $value = '', array $attributes = array()){
285
+            $str = null;
286
+            $str .= '<textarea name = "'.$name.'"';
287
+            $str .= attributes_to_string($attributes);
288
+            $str .= '>';
289
+            $str .= $value.'</textarea>';
290
+            return $str;
291
+        }
292 292
 		
293
-		/**
294
-		 * Generate the form field for select
295
-		 * @param  string $name       the name of the form field
296
-		 * @param  mixed|array $values      the values used to populate the "option" tags
297
-		 * @param  mixed $selected   the selected value in the option list
298
-		 * @param  array  $attributes the additional attribute to be added
299
-		 * @return string             the generated form field html content for select
300
-		 */
301
-		public static function select($name, $values = null, $selected = null, array $attributes = array()){
302
-			if(! is_array($values)){
303
-				$values = array('' => $values);
304
-			}
305
-			$str = null;
306
-			$str .= '<select name = "'.$name.'"';
307
-			$str .= attributes_to_string($attributes);
308
-			$str .= '>';
309
-			foreach($values as $key => $val){
310
-				$select = '';
311
-				if($key == $selected){
312
-					$select = 'selected';
313
-				}
314
-				$str .= '<option value = "'.$key.'" '.$select.'>'.$val.'</option>';
315
-			}
316
-			$str .= '</select>';
317
-			return $str;
318
-		}
293
+        /**
294
+         * Generate the form field for select
295
+         * @param  string $name       the name of the form field
296
+         * @param  mixed|array $values      the values used to populate the "option" tags
297
+         * @param  mixed $selected   the selected value in the option list
298
+         * @param  array  $attributes the additional attribute to be added
299
+         * @return string             the generated form field html content for select
300
+         */
301
+        public static function select($name, $values = null, $selected = null, array $attributes = array()){
302
+            if(! is_array($values)){
303
+                $values = array('' => $values);
304
+            }
305
+            $str = null;
306
+            $str .= '<select name = "'.$name.'"';
307
+            $str .= attributes_to_string($attributes);
308
+            $str .= '>';
309
+            foreach($values as $key => $val){
310
+                $select = '';
311
+                if($key == $selected){
312
+                    $select = 'selected';
313
+                }
314
+                $str .= '<option value = "'.$key.'" '.$select.'>'.$val.'</option>';
315
+            }
316
+            $str .= '</select>';
317
+            return $str;
318
+        }
319 319
 
320
-	}
320
+    }
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,13 +105,13 @@  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
-				$error =  isset($errors[$name]) ? $errors[$name] : null;
114
-				if($error){
113
+				$error = isset($errors[$name]) ? $errors[$name] : null;
114
+				if ($error) {
115 115
 					list($errorStart, $errorEnd) = $obj->formvalidation->getErrorDelimiter();
116 116
 					$return = $errorStart . $error . $errorEnd;
117 117
 				}
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		 * @param  mixed $default the default value if can not found the given form field name
126 126
 		 * @return mixed the form field value if is set, otherwise return the default value.
127 127
 		 */
128
-		public static function value($name, $default = null){
128
+		public static function value($name, $default = null) {
129 129
 			$value = get_instance()->request->query($name);
130 130
 			return $value ? $value : $default;
131 131
 		}
@@ -137,14 +137,14 @@  discard block
 block discarded – undo
137 137
 		 * @param  array  $attributes the additional attributes to be added
138 138
 		 * @return string the generated label html content
139 139
 		 */
140
-		public static function label($label, $for = '', array $attributes = array()){
140
+		public static function label($label, $for = '', array $attributes = array()) {
141 141
 			$str = '<label';
142
-			if($for){
143
-				$str .= ' for = "'.$for.'"';
142
+			if ($for) {
143
+				$str .= ' for = "' . $for . '"';
144 144
 			}
145 145
 			$str .= attributes_to_string($attributes);
146 146
 			$str .= '>';
147
-			$str .= $label.'</label>';
147
+			$str .= $label . '</label>';
148 148
 			return $str;
149 149
 		}
150 150
 
@@ -156,9 +156,9 @@  discard block
 block discarded – undo
156 156
 		 * @param  string $type       the type of the form field (password, text, submit, button, etc.)
157 157
 		 * @return string             the generated form field html content for the input
158 158
 		 */
159
-		public static function input($name, $value = null, array $attributes = array(), $type = 'text'){
159
+		public static function input($name, $value = null, array $attributes = array(), $type = 'text') {
160 160
 			$str = null;
161
-			$str .= '<input name = "'.$name.'" value = "'.$value.'" type = "'.$type.'"';
161
+			$str .= '<input name = "' . $name . '" value = "' . $value . '" type = "' . $type . '"';
162 162
 			$str .= attributes_to_string($attributes);
163 163
 			$str .= '/>';
164 164
 			return $str;
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 		 * Generate the form field for "text"
169 169
 		 * @see Form::input() for more details
170 170
 		 */
171
-		public static function text($name, $value = null, array $attributes = array()){
171
+		public static function text($name, $value = null, array $attributes = array()) {
172 172
 			return self::input($name, $value, $attributes, 'text');
173 173
 		}
174 174
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		 * Generate the form field for "password"
177 177
 		 * @see Form::input() for more details
178 178
 		 */
179
-		public static function password($name, $value = null, array $attributes = array()){
179
+		public static function password($name, $value = null, array $attributes = array()) {
180 180
 			return self::input($name, $value, $attributes, 'password');
181 181
 		}
182 182
 
@@ -184,8 +184,8 @@  discard block
 block discarded – undo
184 184
 		 * Generate the form field for "radio"
185 185
 		 * @see Form::input() for more details
186 186
 		 */
187
-		public static function radio($name, $value = null,  $checked = false, array $attributes = array()){
188
-			if($checked){
187
+		public static function radio($name, $value = null, $checked = false, array $attributes = array()) {
188
+			if ($checked) {
189 189
 				$attributes['checked'] = true;
190 190
 			}
191 191
 			return self::input($name, $value, $attributes, 'radio');
@@ -195,8 +195,8 @@  discard block
 block discarded – undo
195 195
 		 * Generate the form field for "checkbox"
196 196
 		 * @see Form::input() for more details
197 197
 		 */
198
-		public static function checkbox($name, $value = null, $checked = false, array $attributes = array()){
199
-			if($checked){
198
+		public static function checkbox($name, $value = null, $checked = false, array $attributes = array()) {
199
+			if ($checked) {
200 200
 				$attributes['checked'] = true;
201 201
 			}
202 202
 			return self::input($name, $value, $attributes, 'checkbox');
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 		 * Generate the form field for "number"
207 207
 		 * @see Form::input() for more details
208 208
 		 */
209
-		public static function number($name, $value = null, array $attributes = array()){
209
+		public static function number($name, $value = null, array $attributes = array()) {
210 210
 			return self::input($name, $value, $attributes, 'number');
211 211
 		}
212 212
 
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 		 * Generate the form field for "phone"
215 215
 		 * @see Form::input() for more details
216 216
 		 */
217
-		public static function phone($name, $value = null, array $attributes = array()){
217
+		public static function phone($name, $value = null, array $attributes = array()) {
218 218
 			return self::input($name, $value, $attributes, 'phone');
219 219
 		}
220 220
 
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		 * Generate the form field for "email"
223 223
 		 * @see Form::input() for more details
224 224
 		 */
225
-		public static function email($name, $value = null, array $attributes = array()){
225
+		public static function email($name, $value = null, array $attributes = array()) {
226 226
 			return self::input($name, $value, $attributes, 'email');
227 227
 		}
228 228
 		
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		 * Generate the form field for "search"
231 231
 		 * @see Form::input() for more details
232 232
 		 */
233
-		public static function search($name, $value = null, array $attributes = array()){
233
+		public static function search($name, $value = null, array $attributes = array()) {
234 234
 			return self::input($name, $value, $attributes, 'search');
235 235
 		}
236 236
 		
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 		 * Generate the form field for "hidden"
239 239
 		 * @see Form::input() for more details
240 240
 		 */
241
-		public static function hidden($name, $value = null, array $attributes = array()){
241
+		public static function hidden($name, $value = null, array $attributes = array()) {
242 242
 			return self::input($name, $value, $attributes, 'hidden');
243 243
 		}
244 244
 		
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		 * Generate the form field for "file"
247 247
 		 * @see Form::input() for more details
248 248
 		 */
249
-		public static function file($name, array $attributes = array()){
249
+		public static function file($name, array $attributes = array()) {
250 250
 			return self::input($name, null, $attributes, 'file');
251 251
 		}
252 252
 		
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 		 * Generate the form field for "button"
255 255
 		 * @see Form::input() for more details
256 256
 		 */
257
-		public static function button($name, $value = null, array $attributes = array()){
257
+		public static function button($name, $value = null, array $attributes = array()) {
258 258
 			return self::input($name, $value, $attributes, 'button');
259 259
 		}
260 260
 		
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 		 * Generate the form field for "reset"
263 263
 		 * @see Form::input() for more details
264 264
 		 */
265
-		public static function reset($name, $value = null, array $attributes = array()){
265
+		public static function reset($name, $value = null, array $attributes = array()) {
266 266
 			return self::input($name, $value, $attributes, 'reset');
267 267
 		}
268 268
 		
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
 		 * Generate the form field for "submit"
271 271
 		 * @see Form::input() for more details
272 272
 		 */
273
-		public static function submit($name, $value = null, array $attributes = array()){
273
+		public static function submit($name, $value = null, array $attributes = array()) {
274 274
 			return self::input($name, $value, $attributes, 'submit');
275 275
 		}
276 276
 
@@ -281,12 +281,12 @@  discard block
 block discarded – undo
281 281
 		 * @param  array  $attributes the additional attributes to be added
282 282
 		 * @return string             the generated textarea form html content
283 283
 		 */
284
-		public static function textarea($name, $value = '', array $attributes = array()){
284
+		public static function textarea($name, $value = '', array $attributes = array()) {
285 285
 			$str = null;
286
-			$str .= '<textarea name = "'.$name.'"';
286
+			$str .= '<textarea name = "' . $name . '"';
287 287
 			$str .= attributes_to_string($attributes);
288 288
 			$str .= '>';
289
-			$str .= $value.'</textarea>';
289
+			$str .= $value . '</textarea>';
290 290
 			return $str;
291 291
 		}
292 292
 		
@@ -298,20 +298,20 @@  discard block
 block discarded – undo
298 298
 		 * @param  array  $attributes the additional attribute to be added
299 299
 		 * @return string             the generated form field html content for select
300 300
 		 */
301
-		public static function select($name, $values = null, $selected = null, array $attributes = array()){
302
-			if(! is_array($values)){
301
+		public static function select($name, $values = null, $selected = null, array $attributes = array()) {
302
+			if (!is_array($values)) {
303 303
 				$values = array('' => $values);
304 304
 			}
305 305
 			$str = null;
306
-			$str .= '<select name = "'.$name.'"';
306
+			$str .= '<select name = "' . $name . '"';
307 307
 			$str .= attributes_to_string($attributes);
308 308
 			$str .= '>';
309
-			foreach($values as $key => $val){
309
+			foreach ($values as $key => $val) {
310 310
 				$select = '';
311
-				if($key == $selected){
311
+				if ($key == $selected) {
312 312
 					$select = 'selected';
313 313
 				}
314
-				$str .= '<option value = "'.$key.'" '.$select.'>'.$val.'</option>';
314
+				$str .= '<option value = "' . $key . '" ' . $select . '>' . $val . '</option>';
315 315
 			}
316 316
 			$str .= '</select>';
317 317
 			return $str;
Please login to merge, or discard this patch.
tests/tnhfw/classes/RouterTest.php 1 patch
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -1,151 +1,151 @@
 block discarded – undo
1 1
 <?php 
2 2
 
3
-	use PHPUnit\Framework\TestCase;
3
+    use PHPUnit\Framework\TestCase;
4 4
 
5
-	class RouterTest extends TestCase
6
-	{	
5
+    class RouterTest extends TestCase
6
+    {	
7 7
 	
8
-		public static function setUpBeforeClass()
9
-		{
8
+        public static function setUpBeforeClass()
9
+        {
10 10
 		
11
-		}
11
+        }
12 12
 		
13
-		public static function tearDownAfterClass()
14
-		{
13
+        public static function tearDownAfterClass()
14
+        {
15 15
 			
16
-		}
16
+        }
17 17
 		
18
-		protected function setUp()
19
-		{
20
-		}
18
+        protected function setUp()
19
+        {
20
+        }
21 21
 
22
-		protected function tearDown()
23
-		{
24
-		}
22
+        protected function tearDown()
23
+        {
24
+        }
25 25
 		
26
-		public function testAutoUri()
27
-		{
26
+        public function testAutoUri()
27
+        {
28 28
             //when application run in CLI the first argument will be used as route URI
29 29
             $_SERVER['argv'][1] = '';
30 30
             
31 31
             $r = new Router();
32 32
             //remove all all config
33 33
             $r->setRouteConfiguration(array(), false)
34
-              ->setRouteUri()
35
-              ->setRouteSegments()
36
-              ->determineRouteParamsInformation();
34
+                ->setRouteUri()
35
+                ->setRouteSegments()
36
+                ->determineRouteParamsInformation();
37 37
 
38 38
             $this->assertNull($r->getController());
39
-			$this->assertSame('index', $r->getMethod());
40
-			$this->assertSame(0, count($r->getArgs()));
41
-		}
39
+            $this->assertSame('index', $r->getMethod());
40
+            $this->assertSame(0, count($r->getArgs()));
41
+        }
42 42
         
43 43
         public function testCustomUri()
44
-		{
44
+        {
45 45
             $r = new Router();
46 46
             $r->setRouteUri('users/profile/34/54')
47
-              ->setRouteSegments()
48
-              ->determineRouteParamsInformation();
47
+                ->setRouteSegments()
48
+                ->determineRouteParamsInformation();
49 49
             $this->assertSame('users', $r->getController());
50
-			$this->assertSame('profile', $r->getMethod());
51
-			$this->assertSame(2, count($r->getArgs()));
52
-		}
50
+            $this->assertSame('profile', $r->getMethod());
51
+            $this->assertSame(2, count($r->getArgs()));
52
+        }
53 53
         
54 54
         public function testWithCustomConfigControllerMethod()
55
-		{
55
+        {
56 56
             $r = new Router();
57 57
             $r->add('/foo/bar', 'fooController@fooMethod')
58
-              ->setRouteUri('/foo/bar')
59
-              ->setRouteSegments()
60
-              ->determineRouteParamsInformation();
58
+                ->setRouteUri('/foo/bar')
59
+                ->setRouteSegments()
60
+                ->determineRouteParamsInformation();
61 61
             $this->assertSame('fooController', $r->getController());
62
-			$this->assertSame('fooMethod', $r->getMethod());
63
-			$this->assertSame(0, count($r->getArgs()));
64
-			$this->assertNull($r->getModule());
65
-		}
62
+            $this->assertSame('fooMethod', $r->getMethod());
63
+            $this->assertSame(0, count($r->getArgs()));
64
+            $this->assertNull($r->getModule());
65
+        }
66 66
         
67 67
         public function testWithCustomConfigModuleControllerMethod()
68
-		{
68
+        {
69 69
             $r = new Router();
70 70
             $r->add('/foo/bar', 'fooModule#fooController@fooMethod')
71
-              ->setRouteUri('/foo/bar')
72
-              ->setRouteSegments()
73
-              ->determineRouteParamsInformation();
71
+                ->setRouteUri('/foo/bar')
72
+                ->setRouteSegments()
73
+                ->determineRouteParamsInformation();
74 74
             $this->assertSame('fooController', $r->getController());
75
-			$this->assertSame('fooMethod', $r->getMethod());
76
-			$this->assertSame('fooModule', $r->getModule());
77
-			$this->assertSame(0, count($r->getArgs()));
78
-		}
75
+            $this->assertSame('fooMethod', $r->getMethod());
76
+            $this->assertSame('fooModule', $r->getModule());
77
+            $this->assertSame(0, count($r->getArgs()));
78
+        }
79 79
         
80 80
         public function testWithCustomConfigUsingAnyPattern()
81
-		{
81
+        {
82 82
             $r = new Router();
83 83
             $r->add('/foo/(:any)', 'fooController@fooMethod')
84
-              ->setRouteUri('/foo/bar123-baz')
85
-              ->setRouteSegments()
86
-              ->determineRouteParamsInformation();
84
+                ->setRouteUri('/foo/bar123-baz')
85
+                ->setRouteSegments()
86
+                ->determineRouteParamsInformation();
87 87
             $this->assertSame('fooController', $r->getController());
88
-			$this->assertSame('fooMethod', $r->getMethod());
89
-			$this->assertSame(1, count($r->getArgs()));
88
+            $this->assertSame('fooMethod', $r->getMethod());
89
+            $this->assertSame(1, count($r->getArgs()));
90 90
             $args = $r->getArgs();
91 91
             $this->assertSame('bar123-baz', $args[0]);
92
-		}
92
+        }
93 93
         
94
-         public function testWithCustomConfigUsingNumericPattern()
95
-		{
94
+            public function testWithCustomConfigUsingNumericPattern()
95
+        {
96 96
             $r = new Router();
97 97
             $r->add('/foo/(:num)', 'fooController@fooMethod')
98
-              ->setRouteUri('/foo/34')
99
-              ->setRouteSegments()
100
-              ->determineRouteParamsInformation();
98
+                ->setRouteUri('/foo/34')
99
+                ->setRouteSegments()
100
+                ->determineRouteParamsInformation();
101 101
             $this->assertSame('fooController', $r->getController());
102
-			$this->assertSame('fooMethod', $r->getMethod());
103
-			$this->assertSame(1, count($r->getArgs()));
102
+            $this->assertSame('fooMethod', $r->getMethod());
103
+            $this->assertSame(1, count($r->getArgs()));
104 104
             $args = $r->getArgs();
105 105
             $this->assertSame('34', $args[0]);
106
-		}
106
+        }
107 107
         
108 108
         public function testWithCustomConfigUsingAlphaPattern()
109
-		{
109
+        {
110 110
             $r = new Router();
111 111
             $r->add('/foo/(:alpha)', 'fooController@fooMethod')
112
-              ->setRouteUri('/foo/baz')
113
-              ->setRouteSegments()
114
-              ->determineRouteParamsInformation();
112
+                ->setRouteUri('/foo/baz')
113
+                ->setRouteSegments()
114
+                ->determineRouteParamsInformation();
115 115
             $this->assertSame('fooController', $r->getController());
116
-			$this->assertSame('fooMethod', $r->getMethod());
117
-			$this->assertSame(1, count($r->getArgs()));
116
+            $this->assertSame('fooMethod', $r->getMethod());
117
+            $this->assertSame(1, count($r->getArgs()));
118 118
             $args = $r->getArgs();
119 119
             $this->assertSame('baz', $args[0]);
120
-		}
120
+        }
121 121
         
122 122
         public function testWithCustomConfigUsingAlphaNumericPattern()
123
-		{
123
+        {
124 124
             $r = new Router();
125 125
             $r->add('/foo/(:alnum)', 'fooController@fooMethod')
126
-              ->setRouteUri('/foo/baz123')
127
-              ->setRouteSegments()
128
-              ->determineRouteParamsInformation();
126
+                ->setRouteUri('/foo/baz123')
127
+                ->setRouteSegments()
128
+                ->determineRouteParamsInformation();
129 129
             $this->assertSame('fooController', $r->getController());
130
-			$this->assertSame('fooMethod', $r->getMethod());
131
-			$this->assertSame(1, count($r->getArgs()));
130
+            $this->assertSame('fooMethod', $r->getMethod());
131
+            $this->assertSame(1, count($r->getArgs()));
132 132
             $args = $r->getArgs();
133 133
             $this->assertSame('baz123', $args[0]);
134
-		}
134
+        }
135 135
         
136 136
         public function testWithCustomConfigUsingMultiplePattern()
137
-		{
137
+        {
138 138
             $r = new Router();
139 139
             $r->add('/foo/(:alpha)/(:num)', 'fooController@fooMethod')
140
-              ->setRouteUri('/foo/baz/123')
141
-              ->setRouteSegments()
142
-              ->determineRouteParamsInformation();
140
+                ->setRouteUri('/foo/baz/123')
141
+                ->setRouteSegments()
142
+                ->determineRouteParamsInformation();
143 143
             $this->assertSame('fooController', $r->getController());
144
-			$this->assertSame('fooMethod', $r->getMethod());
145
-			$this->assertSame(2, count($r->getArgs()));
144
+            $this->assertSame('fooMethod', $r->getMethod());
145
+            $this->assertSame(2, count($r->getArgs()));
146 146
             $args = $r->getArgs();
147 147
             $this->assertSame('baz', $args[0]);
148 148
             $this->assertSame('123', $args[1]);
149
-		}
149
+        }
150 150
 
151
-	}
152 151
\ No newline at end of file
152
+    }
153 153
\ No newline at end of file
Please login to merge, or discard this patch.
tests/tnhfw/classes/database/DatabaseQueryBuilderTest.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -1,31 +1,31 @@
 block discarded – undo
1 1
 <?php 
2 2
 
3
-	use PHPUnit\Framework\TestCase;
3
+    use PHPUnit\Framework\TestCase;
4 4
 
5
-	class DatabaseQueryBuilderTest extends TestCase
6
-	{	
5
+    class DatabaseQueryBuilderTest extends TestCase
6
+    {	
7 7
 	
8
-		public static function setUpBeforeClass()
9
-		{
8
+        public static function setUpBeforeClass()
9
+        {
10 10
 		
11
-		}
11
+        }
12 12
 		
13
-		public static function tearDownAfterClass()
14
-		{
13
+        public static function tearDownAfterClass()
14
+        {
15 15
 			
16
-		}
16
+        }
17 17
 		
18
-		protected function setUp()
19
-		{
20
-		}
18
+        protected function setUp()
19
+        {
20
+        }
21 21
 
22
-		protected function tearDown()
23
-		{
24
-		}
22
+        protected function tearDown()
23
+        {
24
+        }
25 25
 		
26
-		public function testNotYet()
27
-		{
28
-			$this->markTestSkipped();
29
-		}
26
+        public function testNotYet()
27
+        {
28
+            $this->markTestSkipped();
29
+        }
30 30
 
31
-	}
32 31
\ No newline at end of file
32
+    }
33 33
\ No newline at end of file
Please login to merge, or discard this patch.