Passed
Push — 1.0.0-dev ( 407604...83bedf )
by nguereza
03:26
created
core/classes/database/Database.php 3 patches
Braces   +4 added lines, -8 removed lines patch added patch discarded remove patch
@@ -151,8 +151,7 @@  discard block
 block discarded – undo
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
+          } catch (PDOException $e){
156 155
             $this->logger->fatal($e->getMessage());
157 156
             show_error('Cannot connect to Database.');
158 157
             return false;
@@ -671,8 +670,7 @@  discard block
 block discarded – undo
671 670
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
672 671
       if ($logger !== null){
673 672
         $this->logger = $logger;
674
-      }
675
-      else{
673
+      } else{
676 674
           $this->logger =& class_loader('Log', 'classes');
677 675
           $this->logger->setLogger('Library::Database');
678 676
       }
@@ -685,8 +683,7 @@  discard block
 block discarded – undo
685 683
 	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
686 684
 	  if ($queryBuilder !== null){
687 685
         $this->queryBuilder = $queryBuilder;
688
-	  }
689
-	  else{
686
+	  } else{
690 687
 		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes/database');
691 688
 	  }
692 689
 	}
@@ -698,8 +695,7 @@  discard block
 block discarded – undo
698 695
   protected function setQueryRunnerFromParamOrCreateNewInstance(DatabaseQueryRunner $queryRunner = null){
699 696
     if ($queryRunner !== null){
700 697
         $this->queryRunner = $queryRunner;
701
-    }
702
-    else{
698
+    } else{
703 699
       $this->queryRunner =& class_loader('DatabaseQueryRunner', 'classes/database');
704 700
     }
705 701
   }
Please login to merge, or discard this patch.
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/Log.php 3 patches
Indentation   +236 added lines, -236 removed lines patch added patch discarded remove patch
@@ -1,265 +1,265 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Log{
27
+    class Log{
28 28
 		
29
-		/**
30
-		 * The defined constante for Log level
31
-		 */
32
-		const NONE = 99999999;
33
-		const FATAL = 500;
34
-		const ERROR = 400;
35
-		const WARNING = 300;
36
-		const INFO = 200;
37
-		const DEBUG = 100;
38
-		const ALL = -99999999;
29
+        /**
30
+         * The defined constante for Log level
31
+         */
32
+        const NONE = 99999999;
33
+        const FATAL = 500;
34
+        const ERROR = 400;
35
+        const WARNING = 300;
36
+        const INFO = 200;
37
+        const DEBUG = 100;
38
+        const ALL = -99999999;
39 39
 
40
-		/**
41
-		 * The logger name
42
-		 * @var string
43
-		 */
44
-		private $logger = 'ROOT_LOGGER';
40
+        /**
41
+         * The logger name
42
+         * @var string
43
+         */
44
+        private $logger = 'ROOT_LOGGER';
45 45
 		
46
-		/**
47
-		 * List of valid log level to be checked for the configuration
48
-		 * @var array
49
-		 */
50
-		private static $validConfigLevel = array('off', 'none', 'fatal', 'error', 'warning', 'warn', 'info', 'debug', 'all');
46
+        /**
47
+         * List of valid log level to be checked for the configuration
48
+         * @var array
49
+         */
50
+        private static $validConfigLevel = array('off', 'none', 'fatal', 'error', 'warning', 'warn', 'info', 'debug', 'all');
51 51
 
52
-		/**
53
-		 * Create new Log instance
54
-		 */
55
-		public function __construct(){
56
-		}
52
+        /**
53
+         * Create new Log instance
54
+         */
55
+        public function __construct(){
56
+        }
57 57
 
58
-		/**
59
-		 * Set the logger to identify each message in the log
60
-		 * @param string $logger the logger name
61
-		 */
62
-		public  function setLogger($logger){
63
-			$this->logger = $logger;
64
-		}
58
+        /**
59
+         * Set the logger to identify each message in the log
60
+         * @param string $logger the logger name
61
+         */
62
+        public  function setLogger($logger){
63
+            $this->logger = $logger;
64
+        }
65 65
 
66
-		/**
67
-		 * Save the fatal message in the log
68
-		 * @see Log::writeLog for more detail
69
-		 * @param  string $message the log message to save
70
-		 */
71
-		public function fatal($message){
72
-			$this->writeLog($message, self::FATAL);
73
-		} 
66
+        /**
67
+         * Save the fatal message in the log
68
+         * @see Log::writeLog for more detail
69
+         * @param  string $message the log message to save
70
+         */
71
+        public function fatal($message){
72
+            $this->writeLog($message, self::FATAL);
73
+        } 
74 74
 		
75
-		/**
76
-		 * Save the error message in the log
77
-		 * @see Log::writeLog for more detail
78
-		 * @param  string $message the log message to save
79
-		 */
80
-		public function error($message){
81
-			$this->writeLog($message, self::ERROR);
82
-		} 
75
+        /**
76
+         * Save the error message in the log
77
+         * @see Log::writeLog for more detail
78
+         * @param  string $message the log message to save
79
+         */
80
+        public function error($message){
81
+            $this->writeLog($message, self::ERROR);
82
+        } 
83 83
 
84
-		/**
85
-		 * Save the warning message in the log
86
-		 * @see Log::writeLog for more detail
87
-		 * @param  string $message the log message to save
88
-		 */
89
-		public function warning($message){
90
-			$this->writeLog($message, self::WARNING);
91
-		} 
84
+        /**
85
+         * Save the warning message in the log
86
+         * @see Log::writeLog for more detail
87
+         * @param  string $message the log message to save
88
+         */
89
+        public function warning($message){
90
+            $this->writeLog($message, self::WARNING);
91
+        } 
92 92
 		
93
-		/**
94
-		 * Save the info message in the log
95
-		 * @see Log::writeLog for more detail
96
-		 * @param  string $message the log message to save
97
-		 */
98
-		public function info($message){
99
-			$this->writeLog($message, self::INFO);
100
-		} 
93
+        /**
94
+         * Save the info message in the log
95
+         * @see Log::writeLog for more detail
96
+         * @param  string $message the log message to save
97
+         */
98
+        public function info($message){
99
+            $this->writeLog($message, self::INFO);
100
+        } 
101 101
 		
102
-		/**
103
-		 * Save the debug message in the log
104
-		 * @see Log::writeLog for more detail
105
-		 * @param  string $message the log message to save
106
-		 */
107
-		public function debug($message){
108
-			$this->writeLog($message, self::DEBUG);
109
-		} 
102
+        /**
103
+         * Save the debug message in the log
104
+         * @see Log::writeLog for more detail
105
+         * @param  string $message the log message to save
106
+         */
107
+        public function debug($message){
108
+            $this->writeLog($message, self::DEBUG);
109
+        } 
110 110
 		
111 111
 		
112
-		/**
113
-		 * Save the log message
114
-		 * @param  string $message the log message to be saved
115
-		 * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116
-		 * to allow check the log level threshold.
117
-		 */
118
-		public function writeLog($message, $level = self::INFO){
119
-			$configLogLevel = get_config('log_level');
120
-			if(! $configLogLevel){
121
-				//so means no need log just stop here
122
-				return;
123
-			}
124
-			//check config log level
125
-			if(! self::isValidConfigLevel($configLogLevel)){
126
-				//NOTE: here need put the show_error() "logging" to false to prevent loop
127
-				show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128
-			}
112
+        /**
113
+         * Save the log message
114
+         * @param  string $message the log message to be saved
115
+         * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116
+         * to allow check the log level threshold.
117
+         */
118
+        public function writeLog($message, $level = self::INFO){
119
+            $configLogLevel = get_config('log_level');
120
+            if(! $configLogLevel){
121
+                //so means no need log just stop here
122
+                return;
123
+            }
124
+            //check config log level
125
+            if(! self::isValidConfigLevel($configLogLevel)){
126
+                //NOTE: here need put the show_error() "logging" to false to prevent loop
127
+                show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128
+            }
129 129
 			
130
-			//check if config log_logger_name is set
131
-			if($this->logger){
132
-				$configLoggersName = get_config('log_logger_name', array());
133
-				if (!empty($configLoggersName)) {
134
-					//for best comparaison put all string to lowercase
135
-					$configLoggersName = array_map('strtolower', $configLoggersName);
136
-					if(! in_array(strtolower($this->logger), $configLoggersName)){
137
-						return;
138
-					}
139
-				}
140
-			}
130
+            //check if config log_logger_name is set
131
+            if($this->logger){
132
+                $configLoggersName = get_config('log_logger_name', array());
133
+                if (!empty($configLoggersName)) {
134
+                    //for best comparaison put all string to lowercase
135
+                    $configLoggersName = array_map('strtolower', $configLoggersName);
136
+                    if(! in_array(strtolower($this->logger), $configLoggersName)){
137
+                        return;
138
+                    }
139
+                }
140
+            }
141 141
 			
142
-			//if $level is not an integer
143
-			if(! is_numeric($level)){
144
-				$level = self::getLevelValue($level);
145
-			}
142
+            //if $level is not an integer
143
+            if(! is_numeric($level)){
144
+                $level = self::getLevelValue($level);
145
+            }
146 146
 			
147
-			//check if can logging regarding the log level config
148
-			$configLevel = self::getLevelValue($configLogLevel);
149
-			if($configLevel > $level){
150
-				//can't log
151
-				return;
152
-			}
147
+            //check if can logging regarding the log level config
148
+            $configLevel = self::getLevelValue($configLogLevel);
149
+            if($configLevel > $level){
150
+                //can't log
151
+                return;
152
+            }
153 153
 			
154
-			$logSavePath = get_config('log_save_path');
155
-			if(! $logSavePath){
156
-				$logSavePath = LOGS_PATH;
157
-			}
154
+            $logSavePath = get_config('log_save_path');
155
+            if(! $logSavePath){
156
+                $logSavePath = LOGS_PATH;
157
+            }
158 158
 			
159
-			if(! is_dir($logSavePath) || !is_writable($logSavePath)){
160
-				//NOTE: here need put the show_error() "logging" to false to prevent loop
161
-				show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
162
-			}
159
+            if(! is_dir($logSavePath) || !is_writable($logSavePath)){
160
+                //NOTE: here need put the show_error() "logging" to false to prevent loop
161
+                show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
162
+            }
163 163
 			
164
-			$path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
165
-			if(! file_exists($path)){
166
-				touch($path);
167
-			}
168
-			//may be at this time helper user_agent not yet included
169
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
164
+            $path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
165
+            if(! file_exists($path)){
166
+                touch($path);
167
+            }
168
+            //may be at this time helper user_agent not yet included
169
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
170 170
 			
171
-			///////////////////// date //////////////
172
-			$timestampWithMicro = microtime(true);
173
-			$microtime = sprintf('%06d', ($timestampWithMicro - floor($timestampWithMicro)) * 1000000);
174
-			$dateTime = new DateTime(date('Y-m-d H:i:s.' . $microtime, $timestampWithMicro));
175
-			$logDate = $dateTime->format('Y-m-d H:i:s.u'); 
176
-			//ip
177
-			$ip = get_ip();
178
-			//level name
179
-			$levelName = self::getLevelName($level);
171
+            ///////////////////// date //////////////
172
+            $timestampWithMicro = microtime(true);
173
+            $microtime = sprintf('%06d', ($timestampWithMicro - floor($timestampWithMicro)) * 1000000);
174
+            $dateTime = new DateTime(date('Y-m-d H:i:s.' . $microtime, $timestampWithMicro));
175
+            $logDate = $dateTime->format('Y-m-d H:i:s.u'); 
176
+            //ip
177
+            $ip = get_ip();
178
+            //level name
179
+            $levelName = self::getLevelName($level);
180 180
 			
181
-			//debug info
182
-			$dtrace = debug_backtrace();
183
-			$fileInfo = $dtrace[0]['file'] == __FILE__ ? $dtrace[1] : $dtrace[0];
181
+            //debug info
182
+            $dtrace = debug_backtrace();
183
+            $fileInfo = $dtrace[0]['file'] == __FILE__ ? $dtrace[1] : $dtrace[0];
184 184
 			
185
-			$str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
186
-			$fp = fopen($path, 'a+');
187
-			if(is_resource($fp)){
188
-				flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
189
-				fwrite($fp, $str);
190
-				fclose($fp);
191
-			}
192
-		}		
185
+            $str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
186
+            $fp = fopen($path, 'a+');
187
+            if(is_resource($fp)){
188
+                flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
189
+                fwrite($fp, $str);
190
+                fclose($fp);
191
+            }
192
+        }		
193 193
 		
194
-		/**
195
-		 * Check if the given log level is valid
196
-		 *
197
-		 * @param  string  $level the log level
198
-		 *
199
-		 * @return boolean        true if the given log level is valid, false if not
200
-		 */
201
-		private static function isValidConfigLevel($level){
202
-			$level = strtolower($level);
203
-			return in_array($level, self::$validConfigLevel);
204
-		}
194
+        /**
195
+         * Check if the given log level is valid
196
+         *
197
+         * @param  string  $level the log level
198
+         *
199
+         * @return boolean        true if the given log level is valid, false if not
200
+         */
201
+        private static function isValidConfigLevel($level){
202
+            $level = strtolower($level);
203
+            return in_array($level, self::$validConfigLevel);
204
+        }
205 205
 
206
-		/**
207
-		 * Get the log level number for the given level string
208
-		 * @param  string $level the log level in string format
209
-		 * @return int        the log level in integer format using the predefinied constants
210
-		 */
211
-		private static function getLevelValue($level){
212
-			$level = strtolower($level);
213
-			$value = self::NONE;
206
+        /**
207
+         * Get the log level number for the given level string
208
+         * @param  string $level the log level in string format
209
+         * @return int        the log level in integer format using the predefinied constants
210
+         */
211
+        private static function getLevelValue($level){
212
+            $level = strtolower($level);
213
+            $value = self::NONE;
214 214
 			
215
-			//the default value is NONE, so means no need test for NONE
216
-			if($level == 'fatal'){
217
-				$value = self::FATAL;
218
-			}
219
-			else if($level == 'error'){
220
-				$value = self::ERROR;
221
-			}
222
-			else if($level == 'warning' || $level == 'warn'){
223
-				$value = self::WARNING;
224
-			}
225
-			else if($level == 'info'){
226
-				$value = self::INFO;
227
-			}
228
-			else if($level == 'debug'){
229
-				$value = self::DEBUG;
230
-			}
231
-			else if($level == 'all'){
232
-				$value = self::ALL;
233
-			}
234
-			return $value;
235
-		}
215
+            //the default value is NONE, so means no need test for NONE
216
+            if($level == 'fatal'){
217
+                $value = self::FATAL;
218
+            }
219
+            else if($level == 'error'){
220
+                $value = self::ERROR;
221
+            }
222
+            else if($level == 'warning' || $level == 'warn'){
223
+                $value = self::WARNING;
224
+            }
225
+            else if($level == 'info'){
226
+                $value = self::INFO;
227
+            }
228
+            else if($level == 'debug'){
229
+                $value = self::DEBUG;
230
+            }
231
+            else if($level == 'all'){
232
+                $value = self::ALL;
233
+            }
234
+            return $value;
235
+        }
236 236
 
237
-		/**
238
-		 * Get the log level string for the given log level integer
239
-		 * @param  integer $level the log level in integer format
240
-		 * @return string        the log level in string format
241
-		 */
242
-		private static function getLevelName($level){
243
-			$value = '';
237
+        /**
238
+         * Get the log level string for the given log level integer
239
+         * @param  integer $level the log level in integer format
240
+         * @return string        the log level in string format
241
+         */
242
+        private static function getLevelName($level){
243
+            $value = '';
244 244
 			
245
-			//the default value is NONE, so means no need test for NONE
246
-			if($level == self::FATAL){
247
-				$value = 'FATAL';
248
-			}
249
-			else if($level == self::ERROR){
250
-				$value = 'ERROR';
251
-			}
252
-			else if($level == self::WARNING){
253
-				$value = 'WARNING';
254
-			}
255
-			else if($level == self::INFO){
256
-				$value = 'INFO';
257
-			}
258
-			else if($level == self::DEBUG){
259
-				$value = 'DEBUG';
260
-			}
261
-			//no need for ALL
262
-			return $value;
263
-		}
245
+            //the default value is NONE, so means no need test for NONE
246
+            if($level == self::FATAL){
247
+                $value = 'FATAL';
248
+            }
249
+            else if($level == self::ERROR){
250
+                $value = 'ERROR';
251
+            }
252
+            else if($level == self::WARNING){
253
+                $value = 'WARNING';
254
+            }
255
+            else if($level == self::INFO){
256
+                $value = 'INFO';
257
+            }
258
+            else if($level == self::DEBUG){
259
+                $value = 'DEBUG';
260
+            }
261
+            //no need for ALL
262
+            return $value;
263
+        }
264 264
 
265
-	}
265
+    }
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Log{
27
+	class Log {
28 28
 		
29 29
 		/**
30 30
 		 * The defined constante for Log level
@@ -52,14 +52,14 @@  discard block
 block discarded – undo
52 52
 		/**
53 53
 		 * Create new Log instance
54 54
 		 */
55
-		public function __construct(){
55
+		public function __construct() {
56 56
 		}
57 57
 
58 58
 		/**
59 59
 		 * Set the logger to identify each message in the log
60 60
 		 * @param string $logger the logger name
61 61
 		 */
62
-		public  function setLogger($logger){
62
+		public  function setLogger($logger) {
63 63
 			$this->logger = $logger;
64 64
 		}
65 65
 
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		 * @see Log::writeLog for more detail
69 69
 		 * @param  string $message the log message to save
70 70
 		 */
71
-		public function fatal($message){
71
+		public function fatal($message) {
72 72
 			$this->writeLog($message, self::FATAL);
73 73
 		} 
74 74
 		
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 		 * @see Log::writeLog for more detail
78 78
 		 * @param  string $message the log message to save
79 79
 		 */
80
-		public function error($message){
80
+		public function error($message) {
81 81
 			$this->writeLog($message, self::ERROR);
82 82
 		} 
83 83
 
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 		 * @see Log::writeLog for more detail
87 87
 		 * @param  string $message the log message to save
88 88
 		 */
89
-		public function warning($message){
89
+		public function warning($message) {
90 90
 			$this->writeLog($message, self::WARNING);
91 91
 		} 
92 92
 		
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		 * @see Log::writeLog for more detail
96 96
 		 * @param  string $message the log message to save
97 97
 		 */
98
-		public function info($message){
98
+		public function info($message) {
99 99
 			$this->writeLog($message, self::INFO);
100 100
 		} 
101 101
 		
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		 * @see Log::writeLog for more detail
105 105
 		 * @param  string $message the log message to save
106 106
 		 */
107
-		public function debug($message){
107
+		public function debug($message) {
108 108
 			$this->writeLog($message, self::DEBUG);
109 109
 		} 
110 110
 		
@@ -115,54 +115,54 @@  discard block
 block discarded – undo
115 115
 		 * @param  integer|string $level   the log level in integer or string format, if is string will convert into integer
116 116
 		 * to allow check the log level threshold.
117 117
 		 */
118
-		public function writeLog($message, $level = self::INFO){
118
+		public function writeLog($message, $level = self::INFO) {
119 119
 			$configLogLevel = get_config('log_level');
120
-			if(! $configLogLevel){
120
+			if (!$configLogLevel) {
121 121
 				//so means no need log just stop here
122 122
 				return;
123 123
 			}
124 124
 			//check config log level
125
-			if(! self::isValidConfigLevel($configLogLevel)){
125
+			if (!self::isValidConfigLevel($configLogLevel)) {
126 126
 				//NOTE: here need put the show_error() "logging" to false to prevent loop
127 127
 				show_error('Invalid config log level [' . $configLogLevel . '], the value must be one of the following: ' . implode(', ', array_map('strtoupper', self::$validConfigLevel)), $title = 'Log Config Error', $logging = false);	
128 128
 			}
129 129
 			
130 130
 			//check if config log_logger_name is set
131
-			if($this->logger){
131
+			if ($this->logger) {
132 132
 				$configLoggersName = get_config('log_logger_name', array());
133 133
 				if (!empty($configLoggersName)) {
134 134
 					//for best comparaison put all string to lowercase
135 135
 					$configLoggersName = array_map('strtolower', $configLoggersName);
136
-					if(! in_array(strtolower($this->logger), $configLoggersName)){
136
+					if (!in_array(strtolower($this->logger), $configLoggersName)) {
137 137
 						return;
138 138
 					}
139 139
 				}
140 140
 			}
141 141
 			
142 142
 			//if $level is not an integer
143
-			if(! is_numeric($level)){
143
+			if (!is_numeric($level)) {
144 144
 				$level = self::getLevelValue($level);
145 145
 			}
146 146
 			
147 147
 			//check if can logging regarding the log level config
148 148
 			$configLevel = self::getLevelValue($configLogLevel);
149
-			if($configLevel > $level){
149
+			if ($configLevel > $level) {
150 150
 				//can't log
151 151
 				return;
152 152
 			}
153 153
 			
154 154
 			$logSavePath = get_config('log_save_path');
155
-			if(! $logSavePath){
155
+			if (!$logSavePath) {
156 156
 				$logSavePath = LOGS_PATH;
157 157
 			}
158 158
 			
159
-			if(! is_dir($logSavePath) || !is_writable($logSavePath)){
159
+			if (!is_dir($logSavePath) || !is_writable($logSavePath)) {
160 160
 				//NOTE: here need put the show_error() "logging" to false to prevent loop
161 161
 				show_error('Error : the log dir does not exists or is not writable', $title = 'Log directory error', $logging = false);
162 162
 			}
163 163
 			
164 164
 			$path = $logSavePath . 'logs-' . date('Y-m-d') . '.log';
165
-			if(! file_exists($path)){
165
+			if (!file_exists($path)) {
166 166
 				touch($path);
167 167
 			}
168 168
 			//may be at this time helper user_agent not yet included
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 			
185 185
 			$str = $logDate . ' [' . str_pad($levelName, 7 /*warning len*/) . '] ' . ' [' . str_pad($ip, 15) . '] ' . $this->logger . ' : ' . $message . ' ' . '[' . $fileInfo['file'] . '::' . $fileInfo['line'] . ']' . "\n";
186 186
 			$fp = fopen($path, 'a+');
187
-			if(is_resource($fp)){
187
+			if (is_resource($fp)) {
188 188
 				flock($fp, LOCK_EX); // exclusive lock, will get released when the file is closed
189 189
 				fwrite($fp, $str);
190 190
 				fclose($fp);
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 		 *
199 199
 		 * @return boolean        true if the given log level is valid, false if not
200 200
 		 */
201
-		private static function isValidConfigLevel($level){
201
+		private static function isValidConfigLevel($level) {
202 202
 			$level = strtolower($level);
203 203
 			return in_array($level, self::$validConfigLevel);
204 204
 		}
@@ -208,27 +208,27 @@  discard block
 block discarded – undo
208 208
 		 * @param  string $level the log level in string format
209 209
 		 * @return int        the log level in integer format using the predefinied constants
210 210
 		 */
211
-		private static function getLevelValue($level){
211
+		private static function getLevelValue($level) {
212 212
 			$level = strtolower($level);
213 213
 			$value = self::NONE;
214 214
 			
215 215
 			//the default value is NONE, so means no need test for NONE
216
-			if($level == 'fatal'){
216
+			if ($level == 'fatal') {
217 217
 				$value = self::FATAL;
218 218
 			}
219
-			else if($level == 'error'){
219
+			else if ($level == 'error') {
220 220
 				$value = self::ERROR;
221 221
 			}
222
-			else if($level == 'warning' || $level == 'warn'){
222
+			else if ($level == 'warning' || $level == 'warn') {
223 223
 				$value = self::WARNING;
224 224
 			}
225
-			else if($level == 'info'){
225
+			else if ($level == 'info') {
226 226
 				$value = self::INFO;
227 227
 			}
228
-			else if($level == 'debug'){
228
+			else if ($level == 'debug') {
229 229
 				$value = self::DEBUG;
230 230
 			}
231
-			else if($level == 'all'){
231
+			else if ($level == 'all') {
232 232
 				$value = self::ALL;
233 233
 			}
234 234
 			return $value;
@@ -239,23 +239,23 @@  discard block
 block discarded – undo
239 239
 		 * @param  integer $level the log level in integer format
240 240
 		 * @return string        the log level in string format
241 241
 		 */
242
-		private static function getLevelName($level){
242
+		private static function getLevelName($level) {
243 243
 			$value = '';
244 244
 			
245 245
 			//the default value is NONE, so means no need test for NONE
246
-			if($level == self::FATAL){
246
+			if ($level == self::FATAL) {
247 247
 				$value = 'FATAL';
248 248
 			}
249
-			else if($level == self::ERROR){
249
+			else if ($level == self::ERROR) {
250 250
 				$value = 'ERROR';
251 251
 			}
252
-			else if($level == self::WARNING){
252
+			else if ($level == self::WARNING) {
253 253
 				$value = 'WARNING';
254 254
 			}
255
-			else if($level == self::INFO){
255
+			else if ($level == self::INFO) {
256 256
 				$value = 'INFO';
257 257
 			}
258
-			else if($level == self::DEBUG){
258
+			else if ($level == self::DEBUG) {
259 259
 				$value = 'DEBUG';
260 260
 			}
261 261
 			//no need for ALL
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -215,20 +215,15 @@  discard block
 block discarded – undo
215 215
 			//the default value is NONE, so means no need test for NONE
216 216
 			if($level == 'fatal'){
217 217
 				$value = self::FATAL;
218
-			}
219
-			else if($level == 'error'){
218
+			} else if($level == 'error'){
220 219
 				$value = self::ERROR;
221
-			}
222
-			else if($level == 'warning' || $level == 'warn'){
220
+			} else if($level == 'warning' || $level == 'warn'){
223 221
 				$value = self::WARNING;
224
-			}
225
-			else if($level == 'info'){
222
+			} else if($level == 'info'){
226 223
 				$value = self::INFO;
227
-			}
228
-			else if($level == 'debug'){
224
+			} else if($level == 'debug'){
229 225
 				$value = self::DEBUG;
230
-			}
231
-			else if($level == 'all'){
226
+			} else if($level == 'all'){
232 227
 				$value = self::ALL;
233 228
 			}
234 229
 			return $value;
@@ -245,17 +240,13 @@  discard block
 block discarded – undo
245 240
 			//the default value is NONE, so means no need test for NONE
246 241
 			if($level == self::FATAL){
247 242
 				$value = 'FATAL';
248
-			}
249
-			else if($level == self::ERROR){
243
+			} else if($level == self::ERROR){
250 244
 				$value = 'ERROR';
251
-			}
252
-			else if($level == self::WARNING){
245
+			} else if($level == self::WARNING){
253 246
 				$value = 'WARNING';
254
-			}
255
-			else if($level == self::INFO){
247
+			} else if($level == self::INFO){
256 248
 				$value = 'INFO';
257
-			}
258
-			else if($level == self::DEBUG){
249
+			} else if($level == self::DEBUG){
259 250
 				$value = 'DEBUG';
260 251
 			}
261 252
 			//no need for ALL
Please login to merge, or discard this patch.
core/constants.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -1,81 +1,81 @@
 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 constants.php
29
-	 *    
30
-	 *  This file contains the declaration of most of the constants used in the system, 
31
-	 *  for example: the version, the name of the framework, etc.
32
-	 *  
33
-	 *  @package	core	
34
-	 *  @author	Tony NGUEREZA
35
-	 *  @copyright	Copyright (c) 2017
36
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
37
-	 *  @link	http://www.iacademy.cf
38
-	 *  @version 1.0.0
39
-	 *  @filesource
40
-	 */
27
+    /**
28
+     *  @file constants.php
29
+     *    
30
+     *  This file contains the declaration of most of the constants used in the system, 
31
+     *  for example: the version, the name of the framework, etc.
32
+     *  
33
+     *  @package	core	
34
+     *  @author	Tony NGUEREZA
35
+     *  @copyright	Copyright (c) 2017
36
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
37
+     *  @link	http://www.iacademy.cf
38
+     *  @version 1.0.0
39
+     *  @filesource
40
+     */
41 41
 
42
-	/**
43
-	 *  The framework name
44
-	 */
45
-	define('TNH_NAME', 'TNH Framework');
42
+    /**
43
+     *  The framework name
44
+     */
45
+    define('TNH_NAME', 'TNH Framework');
46 46
 
47
-	/**
48
-	 *  The version of the framework in X.Y.Z format (Major, minor and bugs). 
49
-	 *  If there is the presence of the word "dev", it means that 
50
-	 *  it is a version under development.
51
-	 */
52
-	define('TNH_VERSION', '1.0.0-dev');
47
+    /**
48
+     *  The version of the framework in X.Y.Z format (Major, minor and bugs). 
49
+     *  If there is the presence of the word "dev", it means that 
50
+     *  it is a version under development.
51
+     */
52
+    define('TNH_VERSION', '1.0.0-dev');
53 53
 
54
-	/**
55
-	 *  The date of publication or release of the framework
56
-	 */
57
-	define('TNH_RELEASE_DATE', '2017/02/05');
54
+    /**
55
+     *  The date of publication or release of the framework
56
+     */
57
+    define('TNH_RELEASE_DATE', '2017/02/05');
58 58
 
59
-	/**
60
-	 *  The author of the framework, the person who developed the framework.
61
-	 */
62
-	define('TNH_AUTHOR', 'Tony NGUEREZA');
59
+    /**
60
+     *  The author of the framework, the person who developed the framework.
61
+     */
62
+    define('TNH_AUTHOR', 'Tony NGUEREZA');
63 63
 
64
-	/**
65
-	 *  Email address of the author of the framework.
66
-	 */
67
-	define('TNH_AUTHOR_EMAIL', '[email protected]');
64
+    /**
65
+     *  Email address of the author of the framework.
66
+     */
67
+    define('TNH_AUTHOR_EMAIL', '[email protected]');
68 68
 
69
-	/**
70
-	 *  The minimum PHP version required to use the framework. 
71
-	 *  If the version of PHP installed is lower, then the application will not work.
72
-	 *  Note: we use the PHP version_compare function to compare the required version with 
73
-	 *  the version installed on your system.
74
-	 */
75
-	define('TNH_REQUIRED_PHP_MIN_VERSION', '5.4');
69
+    /**
70
+     *  The minimum PHP version required to use the framework. 
71
+     *  If the version of PHP installed is lower, then the application will not work.
72
+     *  Note: we use the PHP version_compare function to compare the required version with 
73
+     *  the version installed on your system.
74
+     */
75
+    define('TNH_REQUIRED_PHP_MIN_VERSION', '5.4');
76 76
 
77
-	/**
78
-	 *  The maximum version of PHP required to use the framework. 
79
-	 *  If the version of PHP installed is higher than the required one, then the application will not work.
80
-	 */
81
-	define('TNH_REQUIRED_PHP_MAX_VERSION', '7.1');
82 77
\ No newline at end of file
78
+    /**
79
+     *  The maximum version of PHP required to use the framework. 
80
+     *  If the version of PHP installed is higher than the required one, then the application will not work.
81
+     */
82
+    define('TNH_REQUIRED_PHP_MAX_VERSION', '7.1');
83 83
\ No newline at end of file
Please login to merge, or discard this patch.
core/classes/Url.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -62,8 +62,7 @@
 block discarded – undo
62 62
 					$query[0] = rtrim($query[0], '/');
63 63
 					$query[0] .= $suffix;
64 64
 					$path = implode('?', $query);
65
-				}
66
-				else{
65
+				} else{
67 66
 					$path .= $suffix;
68 67
 				}
69 68
 			}
Please login to merge, or discard this patch.
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/functions/function_user_agent.php 2 patches
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -1,75 +1,75 @@
 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
-	/**
29
-	 *  @file function_user_agent.php
30
-	 *    
31
-	 *  Contains most of the utility functions for agent, platform, mobile, browser, and other management.
32
-	 *  
33
-	 *  @package	core
34
-	 *  @author	Tony NGUEREZA
35
-	 *  @copyright	Copyright (c) 2017
36
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
37
-	 *  @link	http://www.iacademy.cf
38
-	 *  @version 1.0.0
39
-	 *  @since 1.0.0
40
-	 *  @filesource
41
-	 */
28
+    /**
29
+     *  @file function_user_agent.php
30
+     *    
31
+     *  Contains most of the utility functions for agent, platform, mobile, browser, and other management.
32
+     *  
33
+     *  @package	core
34
+     *  @author	Tony NGUEREZA
35
+     *  @copyright	Copyright (c) 2017
36
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
37
+     *  @link	http://www.iacademy.cf
38
+     *  @version 1.0.0
39
+     *  @since 1.0.0
40
+     *  @filesource
41
+     */
42 42
 	
43 43
 	 
44
-	if(! function_exists('get_ip')){
45
-		/**
46
-		 *  Retrieves the user's IP address
47
-		 *  
48
-		 *  This function allows to retrieve the IP address of the client
49
-		 *  even if it uses a proxy, the actual IP address is retrieved.
50
-		 *  
51
-		 *  @return string the IP address.
52
-		 */
53
-		function get_ip(){
54
-			$ip = '127.0.0.1';
55
-			$ipServerVars = array(
56
-								'REMOTE_ADDR',
57
-								'HTTP_CLIENT_IP',
58
-								'HTTP_X_FORWARDED_FOR',
59
-								'HTTP_X_FORWARDED',
60
-								'HTTP_FORWARDED_FOR',
61
-								'HTTP_FORWARDED'
62
-							);
63
-			foreach ($ipServerVars as $var) {
64
-				if(isset($_SERVER[$var])){
65
-					$ip = $_SERVER[$var];
66
-					break;
67
-				}
68
-			}
69
-			// Strip any secondary IP etc from the IP address
70
-			if (strpos($ip, ',') > 0) {
71
-				$ip = substr($ip, 0, strpos($ip, ','));
72
-			}
73
-			return $ip;
74
-		}
75
-	}
44
+    if(! function_exists('get_ip')){
45
+        /**
46
+         *  Retrieves the user's IP address
47
+         *  
48
+         *  This function allows to retrieve the IP address of the client
49
+         *  even if it uses a proxy, the actual IP address is retrieved.
50
+         *  
51
+         *  @return string the IP address.
52
+         */
53
+        function get_ip(){
54
+            $ip = '127.0.0.1';
55
+            $ipServerVars = array(
56
+                                'REMOTE_ADDR',
57
+                                'HTTP_CLIENT_IP',
58
+                                'HTTP_X_FORWARDED_FOR',
59
+                                'HTTP_X_FORWARDED',
60
+                                'HTTP_FORWARDED_FOR',
61
+                                'HTTP_FORWARDED'
62
+                            );
63
+            foreach ($ipServerVars as $var) {
64
+                if(isset($_SERVER[$var])){
65
+                    $ip = $_SERVER[$var];
66
+                    break;
67
+                }
68
+            }
69
+            // Strip any secondary IP etc from the IP address
70
+            if (strpos($ip, ',') > 0) {
71
+                $ip = substr($ip, 0, strpos($ip, ','));
72
+            }
73
+            return $ip;
74
+        }
75
+    }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 	 */
42 42
 	
43 43
 	 
44
-	if(! function_exists('get_ip')){
44
+	if (!function_exists('get_ip')) {
45 45
 		/**
46 46
 		 *  Retrieves the user's IP address
47 47
 		 *  
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 		 *  
51 51
 		 *  @return string the IP address.
52 52
 		 */
53
-		function get_ip(){
53
+		function get_ip() {
54 54
 			$ip = '127.0.0.1';
55 55
 			$ipServerVars = array(
56 56
 								'REMOTE_ADDR',
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
 								'HTTP_FORWARDED'
62 62
 							);
63 63
 			foreach ($ipServerVars as $var) {
64
-				if(isset($_SERVER[$var])){
64
+				if (isset($_SERVER[$var])) {
65 65
 					$ip = $_SERVER[$var];
66 66
 					break;
67 67
 				}
Please login to merge, or discard this patch.
core/libraries/Assets.php 2 patches
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -1,168 +1,168 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	/**
28
-	 *  @file Assets.php
29
-	 *    
30
-	 *  This class contains static methods for generating static content links (images, Javascript, CSS, etc.).
31
-	 *  
32
-	 *  @package	core	
33
-	 *  @author	Tony NGUEREZA
34
-	 *  @copyright	Copyright (c) 2017
35
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
-	 *  @link	http://www.iacademy.cf
37
-	 *  @version 1.0.0
38
-	 *  @since 1.0.0
39
-	 *  @filesource
40
-	 */
41
-	class Assets{
27
+    /**
28
+     *  @file Assets.php
29
+     *    
30
+     *  This class contains static methods for generating static content links (images, Javascript, CSS, etc.).
31
+     *  
32
+     *  @package	core	
33
+     *  @author	Tony NGUEREZA
34
+     *  @copyright	Copyright (c) 2017
35
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
+     *  @link	http://www.iacademy.cf
37
+     *  @version 1.0.0
38
+     *  @since 1.0.0
39
+     *  @filesource
40
+     */
41
+    class Assets{
42 42
 		
43
-		/**
44
-		 * The logger instance
45
-		 * @var object
46
-		 */
47
-		private static $logger;
43
+        /**
44
+         * The logger instance
45
+         * @var object
46
+         */
47
+        private static $logger;
48 48
 
49
-		/**
50
-		 * The signleton of the logger
51
-		 * @return Object the Log instance
52
-		 */
53
-		private static function getLogger(){
54
-			if(self::$logger == null){
55
-				//can't assign reference to static variable
56
-				self::$logger[0] =& class_loader('Log', 'classes');
57
-				self::$logger[0]->setLogger('Library::Assets');
58
-			}
59
-			return self::$logger[0];
60
-		}
49
+        /**
50
+         * The signleton of the logger
51
+         * @return Object the Log instance
52
+         */
53
+        private static function getLogger(){
54
+            if(self::$logger == null){
55
+                //can't assign reference to static variable
56
+                self::$logger[0] =& class_loader('Log', 'classes');
57
+                self::$logger[0]->setLogger('Library::Assets');
58
+            }
59
+            return self::$logger[0];
60
+        }
61 61
 
62 62
 
63
-		/**
64
-		 *  Generate the link of the assets file.
65
-		 *  
66
-		 *  Generates the absolute link of a file inside ASSETS_PATH folder.
67
-		 *  For example :
68
-		 *  	echo Assets::path('foo/bar/css/style.css'); => http://mysite.com/assets/foo/bar/css/style.css
69
-		 *  Note:
70
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
71
-		 *  
72
-		 *  @param string $asset the name of the assets file path with the extension.
73
-		 *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
74
-		 */
75
-		public static function path($asset){
76
-			$logger = self::getLogger();	
77
-			$path = ASSETS_PATH . $asset;
63
+        /**
64
+         *  Generate the link of the assets file.
65
+         *  
66
+         *  Generates the absolute link of a file inside ASSETS_PATH folder.
67
+         *  For example :
68
+         *  	echo Assets::path('foo/bar/css/style.css'); => http://mysite.com/assets/foo/bar/css/style.css
69
+         *  Note:
70
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
71
+         *  
72
+         *  @param string $asset the name of the assets file path with the extension.
73
+         *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
74
+         */
75
+        public static function path($asset){
76
+            $logger = self::getLogger();	
77
+            $path = ASSETS_PATH . $asset;
78 78
 			
79
-			$logger->debug('Including the Assets file [' . $path . ']');
80
-			//Check if the file exists
81
-			if(file_exists($path)){
82
-				$logger->info('Assets file [' . $path . '] included successfully');
83
-				return Url::base_url($path);
84
-			}
85
-			$logger->warning('Assets file [' . $path . '] does not exist');
86
-			return null;
87
-		}
79
+            $logger->debug('Including the Assets file [' . $path . ']');
80
+            //Check if the file exists
81
+            if(file_exists($path)){
82
+                $logger->info('Assets file [' . $path . '] included successfully');
83
+                return Url::base_url($path);
84
+            }
85
+            $logger->warning('Assets file [' . $path . '] does not exist');
86
+            return null;
87
+        }
88 88
 		
89
-		/**
90
-		 *  Generate the link of the css file.
91
-		 *  
92
-		 *  Generates the absolute link of a file containing the CSS style.
93
-		 *  For example :
94
-		 *  	echo Assets::css('mystyle'); => http://mysite.com/assets/css/mystyle.css
95
-		 *  Note:
96
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
97
-		 *  
98
-		 *  @param string $path the name of the css file without the extension.
99
-		 *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
100
-		 */
101
-		public static function css($path){
102
-			$logger = self::getLogger();
103
-			/*
89
+        /**
90
+         *  Generate the link of the css file.
91
+         *  
92
+         *  Generates the absolute link of a file containing the CSS style.
93
+         *  For example :
94
+         *  	echo Assets::css('mystyle'); => http://mysite.com/assets/css/mystyle.css
95
+         *  Note:
96
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
97
+         *  
98
+         *  @param string $path the name of the css file without the extension.
99
+         *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
100
+         */
101
+        public static function css($path){
102
+            $logger = self::getLogger();
103
+            /*
104 104
 			* if the file name contains the ".css" extension, replace it with 
105 105
 			* an empty string for better processing.
106 106
 			*/
107
-			$path = str_ireplace('.css', '', $path);
108
-			$path = ASSETS_PATH . 'css/' . $path . '.css';
107
+            $path = str_ireplace('.css', '', $path);
108
+            $path = ASSETS_PATH . 'css/' . $path . '.css';
109 109
 			
110
-			$logger->debug('Including the Assets file [' . $path . '] for CSS');
111
-			//Check if the file exists
112
-			if(file_exists($path)){
113
-				$logger->info('Assets file [' . $path . '] for CSS included successfully');
114
-				return Url::base_url($path);
115
-			}
116
-			$logger->warning('Assets file [' . $path . '] for CSS does not exist');
117
-			return null;
118
-		}
110
+            $logger->debug('Including the Assets file [' . $path . '] for CSS');
111
+            //Check if the file exists
112
+            if(file_exists($path)){
113
+                $logger->info('Assets file [' . $path . '] for CSS included successfully');
114
+                return Url::base_url($path);
115
+            }
116
+            $logger->warning('Assets file [' . $path . '] for CSS does not exist');
117
+            return null;
118
+        }
119 119
 
120
-		/**
121
-		 *  Generate the link of the javascript file.
122
-		 *  
123
-		 *  Generates the absolute link of a file containing the javascript.
124
-		 *  For example :
125
-		 *  	echo Assets::js('myscript'); => http://mysite.com/assets/js/myscript.js
126
-		 *  Note:
127
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
128
-		 *  
129
-		 *  @param string $path the name of the javascript file without the extension.
130
-		 *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
131
-		 */
132
-		public static function js($path){
133
-			$logger = self::getLogger();
134
-			$path = str_ireplace('.js', '', $path);
135
-			$path = ASSETS_PATH . 'js/' . $path . '.js';
136
-			$logger->debug('Including the Assets file [' . $path . '] for javascript');
137
-			if(file_exists($path)){
138
-				$logger->info('Assets file [' . $path . '] for Javascript included successfully');
139
-				return Url::base_url($path);
140
-			}
141
-			$logger->warning('Assets file [' . $path . '] for Javascript does not exist');
142
-			return null;
143
-		}
120
+        /**
121
+         *  Generate the link of the javascript file.
122
+         *  
123
+         *  Generates the absolute link of a file containing the javascript.
124
+         *  For example :
125
+         *  	echo Assets::js('myscript'); => http://mysite.com/assets/js/myscript.js
126
+         *  Note:
127
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
128
+         *  
129
+         *  @param string $path the name of the javascript file without the extension.
130
+         *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
131
+         */
132
+        public static function js($path){
133
+            $logger = self::getLogger();
134
+            $path = str_ireplace('.js', '', $path);
135
+            $path = ASSETS_PATH . 'js/' . $path . '.js';
136
+            $logger->debug('Including the Assets file [' . $path . '] for javascript');
137
+            if(file_exists($path)){
138
+                $logger->info('Assets file [' . $path . '] for Javascript included successfully');
139
+                return Url::base_url($path);
140
+            }
141
+            $logger->warning('Assets file [' . $path . '] for Javascript does not exist');
142
+            return null;
143
+        }
144 144
 
145
-		/**
146
-		 *  Generate the link of the image file.
147
-		 *  
148
-		 *  Generates the absolute link of a file containing the image.
149
-		 *  For example :
150
-		 *  	echo Assets::img('myimage.png'); => http://mysite.com/assets/images/myimage.png
151
-		 *  Note:
152
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
153
-		 *  
154
-		 *  @param string $path the name of the image file with the extension.
155
-		 *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
156
-		 */
157
-		public static function img($path){
158
-			$logger = self::getLogger();
159
-			$path = ASSETS_PATH . 'images/' . $path;
160
-			$logger->debug('Including the Assets file [' . $path . '] for image');
161
-			if(file_exists($path)){
162
-				$logger->info('Assets file [' . $path . '] for image included successfully');
163
-				return Url::base_url($path);
164
-			}
165
-			$logger->warning('Assets file [' . $path . '] for image does not exist');
166
-			return null;
167
-		}
168
-	}
145
+        /**
146
+         *  Generate the link of the image file.
147
+         *  
148
+         *  Generates the absolute link of a file containing the image.
149
+         *  For example :
150
+         *  	echo Assets::img('myimage.png'); => http://mysite.com/assets/images/myimage.png
151
+         *  Note:
152
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
153
+         *  
154
+         *  @param string $path the name of the image file with the extension.
155
+         *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
156
+         */
157
+        public static function img($path){
158
+            $logger = self::getLogger();
159
+            $path = ASSETS_PATH . 'images/' . $path;
160
+            $logger->debug('Including the Assets file [' . $path . '] for image');
161
+            if(file_exists($path)){
162
+                $logger->info('Assets file [' . $path . '] for image included successfully');
163
+                return Url::base_url($path);
164
+            }
165
+            $logger->warning('Assets file [' . $path . '] for image does not exist');
166
+            return null;
167
+        }
168
+    }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 	 *  @since 1.0.0
39 39
 	 *  @filesource
40 40
 	 */
41
-	class Assets{
41
+	class Assets {
42 42
 		
43 43
 		/**
44 44
 		 * The logger instance
@@ -50,10 +50,10 @@  discard block
 block discarded – undo
50 50
 		 * The signleton of the logger
51 51
 		 * @return Object the Log instance
52 52
 		 */
53
-		private static function getLogger(){
54
-			if(self::$logger == null){
53
+		private static function getLogger() {
54
+			if (self::$logger == null) {
55 55
 				//can't assign reference to static variable
56
-				self::$logger[0] =& class_loader('Log', 'classes');
56
+				self::$logger[0] = & class_loader('Log', 'classes');
57 57
 				self::$logger[0]->setLogger('Library::Assets');
58 58
 			}
59 59
 			return self::$logger[0];
@@ -72,13 +72,13 @@  discard block
 block discarded – undo
72 72
 		 *  @param string $asset the name of the assets file path with the extension.
73 73
 		 *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
74 74
 		 */
75
-		public static function path($asset){
75
+		public static function path($asset) {
76 76
 			$logger = self::getLogger();	
77 77
 			$path = ASSETS_PATH . $asset;
78 78
 			
79 79
 			$logger->debug('Including the Assets file [' . $path . ']');
80 80
 			//Check if the file exists
81
-			if(file_exists($path)){
81
+			if (file_exists($path)) {
82 82
 				$logger->info('Assets file [' . $path . '] included successfully');
83 83
 				return Url::base_url($path);
84 84
 			}
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 		 *  @param string $path the name of the css file without the extension.
99 99
 		 *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
100 100
 		 */
101
-		public static function css($path){
101
+		public static function css($path) {
102 102
 			$logger = self::getLogger();
103 103
 			/*
104 104
 			* if the file name contains the ".css" extension, replace it with 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 			
110 110
 			$logger->debug('Including the Assets file [' . $path . '] for CSS');
111 111
 			//Check if the file exists
112
-			if(file_exists($path)){
112
+			if (file_exists($path)) {
113 113
 				$logger->info('Assets file [' . $path . '] for CSS included successfully');
114 114
 				return Url::base_url($path);
115 115
 			}
@@ -129,12 +129,12 @@  discard block
 block discarded – undo
129 129
 		 *  @param string $path the name of the javascript file without the extension.
130 130
 		 *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
131 131
 		 */
132
-		public static function js($path){
132
+		public static function js($path) {
133 133
 			$logger = self::getLogger();
134 134
 			$path = str_ireplace('.js', '', $path);
135 135
 			$path = ASSETS_PATH . 'js/' . $path . '.js';
136 136
 			$logger->debug('Including the Assets file [' . $path . '] for javascript');
137
-			if(file_exists($path)){
137
+			if (file_exists($path)) {
138 138
 				$logger->info('Assets file [' . $path . '] for Javascript included successfully');
139 139
 				return Url::base_url($path);
140 140
 			}
@@ -154,11 +154,11 @@  discard block
 block discarded – undo
154 154
 		 *  @param string $path the name of the image file with the extension.
155 155
 		 *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
156 156
 		 */
157
-		public static function img($path){
157
+		public static function img($path) {
158 158
 			$logger = self::getLogger();
159 159
 			$path = ASSETS_PATH . 'images/' . $path;
160 160
 			$logger->debug('Including the Assets file [' . $path . '] for image');
161
-			if(file_exists($path)){
161
+			if (file_exists($path)) {
162 162
 				$logger->info('Assets file [' . $path . '] for image included successfully');
163 163
 				return Url::base_url($path);
164 164
 			}
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.