Passed
Push — 1.0.0-dev ( 93958a...e1c8ef )
by nguereza
02:26
created
core/libraries/PDF.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -1,80 +1,80 @@
 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
-	/**
28
-	 * PDF library to generate PDF document using the library DOMPDF
29
-	 */
30
-	class PDF extends BaseClass{
27
+    /**
28
+     * PDF library to generate PDF document using the library DOMPDF
29
+     */
30
+    class PDF extends BaseClass{
31 31
 		
32
-		/**
33
-		 * The dompdf instance
34
-		 * @var Dompdf
35
-		 */
36
-		private $dompdf = null;
32
+        /**
33
+         * The dompdf instance
34
+         * @var Dompdf
35
+         */
36
+        private $dompdf = null;
37 37
 		
38
-		/**
39
-		 * Create PDF library instance
40
-		 */
41
-		public function __construct(){
42
-			parent::__construct();
38
+        /**
39
+         * Create PDF library instance
40
+         */
41
+        public function __construct(){
42
+            parent::__construct();
43 43
 
44
-			require_once VENDOR_PATH.'dompdf/dompdf_config.inc.php';
45
-			$this->dompdf = new Dompdf();
46
-		}
44
+            require_once VENDOR_PATH.'dompdf/dompdf_config.inc.php';
45
+            $this->dompdf = new Dompdf();
46
+        }
47 47
 
48
-		/**
49
-		 * Generate PDF document
50
-		 * @param  string  $html        the HTML content to use for generation
51
-		 * @param  string  $filename    the generated PDF document filename
52
-		 * @param  boolean $stream      if need send the generated PDF to browser for download
53
-		 * @param  string  $paper       the PDF document paper type like 'A4', 'A5', 'letter', etc.
54
-		 * @param  string  $orientation the PDF document orientation like 'portrait', 'landscape'
55
-		 * @return string|void               if $stream is true send PDF document to browser for download, else return the generated PDF
56
-		 * content like to join in Email attachment of for other purpose use.
57
-		 */
58
-		public function generate($html, $filename = 'output.pdf', $stream = true, $paper = 'A4', $orientation = 'portrait'){
59
-			$this->logger->info('Generating of PDF document: filename [' .$filename. '], stream [' .($stream ? 'TRUE':'FALSE'). '], paper [' .$paper. '], orientation [' .$orientation. ']');
60
-			$this->dompdf->load_html($html);
61
-			$this->dompdf->set_paper($paper, $orientation);
62
-			$this->dompdf->render();
63
-			if($stream){
64
-				$this->dompdf->stream($filename);
65
-			}
66
-			else{
67
-				return $this->dompdf->output();
68
-			}
69
-		}
48
+        /**
49
+         * Generate PDF document
50
+         * @param  string  $html        the HTML content to use for generation
51
+         * @param  string  $filename    the generated PDF document filename
52
+         * @param  boolean $stream      if need send the generated PDF to browser for download
53
+         * @param  string  $paper       the PDF document paper type like 'A4', 'A5', 'letter', etc.
54
+         * @param  string  $orientation the PDF document orientation like 'portrait', 'landscape'
55
+         * @return string|void               if $stream is true send PDF document to browser for download, else return the generated PDF
56
+         * content like to join in Email attachment of for other purpose use.
57
+         */
58
+        public function generate($html, $filename = 'output.pdf', $stream = true, $paper = 'A4', $orientation = 'portrait'){
59
+            $this->logger->info('Generating of PDF document: filename [' .$filename. '], stream [' .($stream ? 'TRUE':'FALSE'). '], paper [' .$paper. '], orientation [' .$orientation. ']');
60
+            $this->dompdf->load_html($html);
61
+            $this->dompdf->set_paper($paper, $orientation);
62
+            $this->dompdf->render();
63
+            if($stream){
64
+                $this->dompdf->stream($filename);
65
+            }
66
+            else{
67
+                return $this->dompdf->output();
68
+            }
69
+        }
70 70
 		
71
-		/**
72
-		* Return the instance of Dompdf
73
-		*
74
-		* @return object the dompdf instance
75
-		*/
76
-		public function getDompdf(){
77
-			return $this->dompdf;
78
-		}
71
+        /**
72
+         * Return the instance of Dompdf
73
+         *
74
+         * @return object the dompdf instance
75
+         */
76
+        public function getDompdf(){
77
+            return $this->dompdf;
78
+        }
79 79
 		
80
-	}
80
+    }
Please login to merge, or discard this patch.
core/libraries/FormValidation.php 1 patch
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -22,10 +22,10 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
 
27 27
 
28
-     class FormValidation extends BaseClass{
28
+        class FormValidation extends BaseClass{
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
          */
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
         public function __construct() {
94 94
             parent::__construct();
95 95
            
96
-		   //Load form validation language message
96
+            //Load form validation language message
97 97
             Loader::lang('form_validation');
98 98
             $obj = & get_instance();
99 99
             $this->_errorsMessages  = array(
@@ -155,13 +155,13 @@  discard block
 block discarded – undo
155 155
         /**
156 156
          * Set the form validation data
157 157
          * @param array $data the values to be validated
158
-		 *
158
+         *
159 159
          * @return FormValidation Current instance of object.
160 160
          */
161 161
         public function setData(array $data){
162 162
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
163 163
             $this->data = $data;
164
-			return $this;
164
+            return $this;
165 165
         }
166 166
 
167 167
         /**
@@ -172,11 +172,11 @@  discard block
 block discarded – undo
172 172
             return $this->data;
173 173
         }
174 174
 
175
-		/**
176
-		* Get the validation function name to validate a rule
177
-		*
178
-		* @return string the function name
179
-		*/
175
+        /**
176
+         * Get the validation function name to validate a rule
177
+         *
178
+         * @return string the function name
179
+         */
180 180
         protected function _toCallCase($funcName, $prefix='_validate') {
181 181
             $funcName = strtolower($funcName);
182 182
             $finalFuncName = $prefix;
@@ -246,12 +246,12 @@  discard block
 block discarded – undo
246 246
             $this->_forceFail = false;
247 247
 
248 248
             foreach ($this->getData() as $inputName => $inputVal) {
249
-    			if(is_array($this->data[$inputName])){
250
-    				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
251
-    			}
252
-    			else{
253
-    				$this->data[$inputName] = trim($this->data[$inputName]);
254
-    			}
249
+                if(is_array($this->data[$inputName])){
250
+                    $this->data[$inputName] = array_map('trim', $this->data[$inputName]);
251
+                }
252
+                else{
253
+                    $this->data[$inputName] = trim($this->data[$inputName]);
254
+                }
255 255
 
256 256
                 if (array_key_exists($inputName, $this->_rules)) {
257 257
                     foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
          *
268 268
          * @param string $inputField Name of the field or the data key to add a rule to
269 269
          * @param string $ruleSets PIPE seperated string of rules
270
-		 *
270
+         *
271 271
          * @return FormValidation Current instance of object.
272 272
          */
273 273
         public function setRule($inputField, $inputLabel, $ruleSets) {
@@ -281,8 +281,8 @@  discard block
 block discarded – undo
281 281
          * Takes an array of rules and uses setRule() to set them, accepts an array
282 282
          * of rule names rather than a pipe-delimited string as well.
283 283
          * @param array $ruleSets
284
-		 *
285
-		 * @return FormValidation Current instance of object.
284
+         *
285
+         * @return FormValidation Current instance of object.
286 286
          */
287 287
         public function setRules(array $ruleSets) {
288 288
             foreach ($ruleSets as $ruleSet) {
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
          * @param string $start Before block of errors gets displayed, HTML allowed.
305 305
          * @param string $end After the block of errors gets displayed, HTML allowed.
306 306
          *
307
-		 * @return FormValidation Current instance of object.
307
+         * @return FormValidation Current instance of object.
308 308
          */
309 309
         public function setErrorsDelimiter($start, $end) {
310 310
             $this->_allErrorsDelimiter[0] = $start;
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
          * @param string $start Displayed before each error.
320 320
          * @param string $end Displayed after each error.
321 321
          * 
322
-		 * @return FormValidation Current instance of object.
322
+         * @return FormValidation Current instance of object.
323 323
          */
324 324
         public function setErrorDelimiter($start, $end) {
325 325
             $this->_eachErrorDelimiter[0] = $start;
@@ -327,21 +327,21 @@  discard block
 block discarded – undo
327 327
             return $this;
328 328
         }
329 329
 
330
-		/**
331
-		* Get the each errors delimiters
332
-		*
333
-		* @return array
334
-		*/
335
-    	public function getErrorDelimiter() {
330
+        /**
331
+         * Get the each errors delimiters
332
+         *
333
+         * @return array
334
+         */
335
+        public function getErrorDelimiter() {
336 336
             return $this->_eachErrorDelimiter;
337 337
         }
338 338
 
339
-		/**
340
-		* Get the all errors delimiters
341
-		*
342
-		* @return array
343
-		*/
344
-    	public function getErrorsDelimiter() {
339
+        /**
340
+         * Get the all errors delimiters
341
+         *
342
+         * @return array
343
+         */
344
+        public function getErrorsDelimiter() {
345 345
             return $this->_allErrorsDelimiter;
346 346
         }
347 347
 
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
          *
380 380
          * @param string $inputName The form input name or data key
381 381
          * @param string $errorMessage Error to display
382
-		 *
382
+         *
383 383
          * @return formValidation Current instance of the object
384 384
          */
385 385
         public function setCustomError($inputName, $errorMessage) {
@@ -416,17 +416,17 @@  discard block
 block discarded – undo
416 416
          *
417 417
          * @param boolean $limit number of error to display or return
418 418
          * @param boolean $echo Whether or not the values are to be returned or displayed
419
-		 *
419
+         *
420 420
          * @return string Errors formatted for output
421 421
          */
422 422
         public function displayErrors($limit = null, $echo = true) {
423 423
             list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
424 424
             list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
425 425
             $errorOutput = $errorsStart;
426
-    		$i = 0;
426
+            $i = 0;
427 427
             if (!empty($this->_errors)) {
428 428
                 foreach ($this->_errors as $fieldName => $error) {
429
-        	    	if ($i === $limit) { 
429
+                    if ($i === $limit) { 
430 430
                         break; 
431 431
                     }
432 432
                     $errorOutput .= $errorStart;
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
          * Breaks up a PIPE seperated string of rules, and puts them into an array.
455 455
          *
456 456
          * @param string $ruleString String to be parsed.
457
-		 *
457
+         *
458 458
          * @return array Array of each value in original string.
459 459
          */
460 460
         protected function _parseRuleString($ruleString) {
@@ -467,10 +467,10 @@  discard block
 block discarded – undo
467 467
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
468 468
                 preg_match($rule, $ruleString, $regexRule);
469 469
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
470
-                 if(!empty($regexRule[0])){
471
-                     $ruleSets[] = $regexRule[0];
472
-                 }
473
-                 $ruleStringRegex = explode('|', $ruleStringTemp);
470
+                    if(!empty($regexRule[0])){
471
+                        $ruleSets[] = $regexRule[0];
472
+                    }
473
+                    $ruleStringRegex = explode('|', $ruleStringTemp);
474 474
                 foreach ($ruleStringRegex as $rule) {
475 475
                     $rule = trim($rule);
476 476
                     if($rule){
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
                 } else {
487 487
                     $ruleSets[] = $ruleString;
488 488
                 }
489
-             }
489
+                }
490 490
             return $ruleSets;
491 491
         }
492 492
 
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
          * Returns whether or not a field obtains the rule "required".
495 495
          *
496 496
          * @param string $fieldName Field to check if required.
497
-		 *
497
+         *
498 498
          * @return boolean Whether or not the field is required.
499 499
          */
500 500
         protected function _fieldIsRequired($fieldName) {
@@ -529,13 +529,13 @@  discard block
 block discarded – undo
529 529
             return;
530 530
         }
531 531
 
532
-		/**
533
-		* Set error for the given field or key
534
-		*
535
-		* @param string $inputName the input or key name
536
-		* @param string $ruleName the rule name
537
-		* @param array|string $replacements
538
-		*/
532
+        /**
533
+         * Set error for the given field or key
534
+         *
535
+         * @param string $inputName the input or key name
536
+         * @param string $ruleName the rule name
537
+         * @param array|string $replacements
538
+         */
539 539
         protected function _setError($inputName, $ruleName, $replacements = array()) {
540 540
             $rulePhraseKeyParts = explode(',', $ruleName);
541 541
             $rulePhrase = null;
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
             }
553 553
             // Type cast to array in case it's a string
554 554
             $replacements = (array) $replacements;
555
-			$replacementCount = count($replacements);
555
+            $replacementCount = count($replacements);
556 556
             for ($i = 1; $i <= $replacementCount; $i++) {
557 557
                 $key = $i - 1;
558 558
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
@@ -570,11 +570,11 @@  discard block
 block discarded – undo
570 570
          *
571 571
          * @param type $inputArg
572 572
          * @param string $callbackFunc
573
-		 *
573
+         *
574 574
          * @return mixed
575 575
          */
576 576
         protected function _runCallback($inputArg, $callbackFunc) {
577
-			return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
577
+            return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
578 578
         }
579 579
 
580 580
         /**
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
          * arguments.
584 584
          *
585 585
          * @param string $callbackFunc
586
-		 *
586
+         *
587 587
          * @return mixed
588 588
          */
589 589
         protected function _runEmptyCallback($callbackFunc) {
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
          * Gets a specific label of a specific field input name.
595 595
          *
596 596
          * @param string $inputName
597
-		 *
597
+         *
598 598
          * @return string
599 599
          */
600 600
         protected function _getLabel($inputName) {
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
          * @param  string $ruleName  the rule name for this validation ("required")
608 608
          * @param  array  $ruleArgs  the rules argument
609 609
          */
610
-		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
610
+        protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
611 611
             $inputVal = $this->post($inputName);
612 612
             if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
613 613
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
@@ -615,8 +615,8 @@  discard block
 block discarded – undo
615 615
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
616 616
                 }
617 617
             } 
618
-			else if($inputVal == '') {
619
-				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
618
+            else if($inputVal == '') {
619
+                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
620 620
             }
621 621
         }
622 622
 
@@ -640,10 +640,10 @@  discard block
 block discarded – undo
640 640
          */
641 641
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
642 642
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
643
-				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
644
-				if(! $result){
645
-					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
646
-				}
643
+                $result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
644
+                if(! $result){
645
+                    $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
646
+                }
647 647
             }
648 648
         }
649 649
 
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
                         continue;
676 676
                     }
677 677
                 } 
678
-				else{
678
+                else{
679 679
                     if ($inputVal == $doNotEqual) {
680 680
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
681 681
                         continue;
@@ -767,7 +767,7 @@  discard block
 block discarded – undo
767 767
          * @param  string $ruleName  the rule name for this validation ("less_than")
768 768
          * @param  array  $ruleArgs  the rules argument
769 769
          */
770
-    	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
770
+        protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
771 771
             $inputVal = $this->post($inputName);
772 772
             if ($inputVal >= $ruleArgs[1]) { 
773 773
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
          * @param  string $ruleName  the rule name for this validation ("greater_than")
784 784
          * @param  array  $ruleArgs  the rules argument
785 785
          */
786
-    	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
786
+        protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
787 787
             $inputVal = $this->post($inputName);
788 788
             if ($inputVal <= $ruleArgs[1]) {
789 789
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -799,7 +799,7 @@  discard block
 block discarded – undo
799 799
          * @param  string $ruleName  the rule name for this validation ("numeric")
800 800
          * @param  array  $ruleArgs  the rules argument
801 801
          */
802
-    	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
802
+        protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
803 803
             $inputVal = $this->post($inputName);
804 804
             if (! is_numeric($inputVal)) {
805 805
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -815,18 +815,18 @@  discard block
 block discarded – undo
815 815
          * @param  string $ruleName  the rule name for this validation ("exists")
816 816
          * @param  array  $ruleArgs  the rules argument
817 817
          */
818
-		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
818
+        protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
819 819
             $inputVal = $this->post($inputName);
820
-    		if (! is_object($this->databaseInstance)){
820
+            if (! is_object($this->databaseInstance)){
821 821
                 $obj = & get_instance();
822 822
                 if(isset($obj->database)){
823 823
                     $this->databaseInstance = $obj->database;
824 824
                 } 
825 825
             }
826
-    		list($table, $column) = explode('.', $ruleArgs[1]);
827
-    		$this->databaseInstance->getQueryBuilder()->from($table)
828
-    			                                       ->where($column, $inputVal);
829
-    		$this->databaseInstance->get();
826
+            list($table, $column) = explode('.', $ruleArgs[1]);
827
+            $this->databaseInstance->getQueryBuilder()->from($table)
828
+                                                        ->where($column, $inputVal);
829
+            $this->databaseInstance->get();
830 830
             if ($this->databaseInstance->numRows() <= 0) {
831 831
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
832 832
                     return;
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
          * @param  string $ruleName  the rule name for this validation ("is_unique")
842 842
          * @param  array  $ruleArgs  the rules argument
843 843
          */
844
-    	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
844
+        protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
845 845
             $inputVal = $this->post($inputName);
846 846
             if (! is_object($this->databaseInstance)){
847 847
                 $obj = & get_instance();
@@ -849,11 +849,11 @@  discard block
 block discarded – undo
849 849
                     $this->databaseInstance = $obj->database;
850 850
                 } 
851 851
             }
852
-    		list($table, $column) = explode('.', $ruleArgs[1]);
853
-    		$this->databaseInstance->getQueryBuilder()->from($table)
854
-    			                                      ->where($column, $inputVal);
855
-    		$this->databaseInstance->get();
856
-    		if ($this->databaseInstance->numRows() > 0) {
852
+            list($table, $column) = explode('.', $ruleArgs[1]);
853
+            $this->databaseInstance->getQueryBuilder()->from($table)
854
+                                                        ->where($column, $inputVal);
855
+            $this->databaseInstance->get();
856
+            if ($this->databaseInstance->numRows() > 0) {
857 857
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
858 858
                     return;
859 859
                 }
@@ -867,25 +867,25 @@  discard block
 block discarded – undo
867 867
          * @param  string $ruleName  the rule name for this validation ("is_unique_update")
868 868
          * @param  array  $ruleArgs  the rules argument
869 869
          */
870
-    	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
870
+        protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
871 871
             $inputVal = $this->post($inputName);
872
-    		if (! is_object($this->databaseInstance)){
872
+            if (! is_object($this->databaseInstance)){
873 873
                 $obj = & get_instance();
874 874
                 if(isset($obj->database)){
875 875
                     $this->databaseInstance = $obj->database;
876 876
                 } 
877 877
             }
878
-    		$data = explode(',', $ruleArgs[1]);
879
-    		if(count($data) < 2){
880
-    			return;
881
-    		}
882
-    		list($table, $column) = explode('.', $data[0]);
883
-    		list($field, $val)    = explode('=', $data[1]);
884
-    		$this->databaseInstance->getQueryBuilder()->from($table)
885
-                                			          ->where($column, $inputVal)
886
-                                            		  ->where($field, '!=', trim($val));
878
+            $data = explode(',', $ruleArgs[1]);
879
+            if(count($data) < 2){
880
+                return;
881
+            }
882
+            list($table, $column) = explode('.', $data[0]);
883
+            list($field, $val)    = explode('=', $data[1]);
884
+            $this->databaseInstance->getQueryBuilder()->from($table)
885
+                                                        ->where($column, $inputVal)
886
+                                                        ->where($field, '!=', trim($val));
887 887
             $this->databaseInstance->get();
888
-    		if ($this->databaseInstance->numRows() > 0) {
888
+            if ($this->databaseInstance->numRows() > 0) {
889 889
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
890 890
                     return;
891 891
                 }
@@ -901,7 +901,7 @@  discard block
 block discarded – undo
901 901
          */
902 902
         protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
903 903
             $inputVal = $this->post($inputName);
904
-    		$list = explode(',', $ruleArgs[1]);
904
+            $list = explode(',', $ruleArgs[1]);
905 905
             $list = array_map('trim', $list);
906 906
             if (! in_array($inputVal, $list)) {
907 907
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
@@ -919,7 +919,7 @@  discard block
 block discarded – undo
919 919
          */
920 920
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
921 921
             $inputVal = $this->post($inputName);
922
-    		$regex = $ruleArgs[1];
922
+            $regex = $ruleArgs[1];
923 923
             if (! preg_match($regex, $inputVal)) {
924 924
                 if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
925 925
                     return;
Please login to merge, or discard this patch.
core/libraries/Upload.php 1 patch
Indentation   +293 added lines, -293 removed lines patch added patch discarded remove patch
@@ -22,139 +22,139 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
 
27 27
 
28 28
 
29 29
     /**
30
-    *    Upload
31
-    *
32
-    *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
33
-    *
34
-    *    @author Olaf Erlandsen <[email protected]>
35
-    *    @author http://www.webdevfreelance.com/
36
-    *
37
-    *    @package FileUpload
38
-    *    @version 1.5
39
-    */
30
+     *    Upload
31
+     *
32
+     *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
33
+     *
34
+     *    @author Olaf Erlandsen <[email protected]>
35
+     *    @author http://www.webdevfreelance.com/
36
+     *
37
+     *    @package FileUpload
38
+     *    @version 1.5
39
+     */
40 40
     class Upload extends BaseClass{
41 41
 
42 42
         /**
43
-        *   Version
44
-        *
45
-        *   @since      1.5
46
-        *   @version    1.0
47
-        */
43
+         *   Version
44
+         *
45
+         *   @since      1.5
46
+         *   @version    1.0
47
+         */
48 48
         const VERSION = '1.5';
49 49
 
50 50
         /**
51
-        *    Upload function name
52
-        *    Remember:
53
-        *        Default function: move_uploaded_file
54
-        *        Native options:
55
-        *            - move_uploaded_file (Default and best option)
56
-        *            - copy
57
-        *
58
-        *    @since        1.0
59
-        *    @version    1.0
60
-        *    @var        string
61
-        */
51
+         *    Upload function name
52
+         *    Remember:
53
+         *        Default function: move_uploaded_file
54
+         *        Native options:
55
+         *            - move_uploaded_file (Default and best option)
56
+         *            - copy
57
+         *
58
+         *    @since        1.0
59
+         *    @version    1.0
60
+         *    @var        string
61
+         */
62 62
         private $upload_function = 'move_uploaded_file';
63 63
 
64 64
         /**
65
-        *    Array with the information obtained from the
66
-        *    variable $_FILES or $HTTP_POST_FILES.
67
-        *
68
-        *    @since        1.0
69
-        *    @version    1.0
70
-        *    @var        array
71
-        */
65
+         *    Array with the information obtained from the
66
+         *    variable $_FILES or $HTTP_POST_FILES.
67
+         *
68
+         *    @since        1.0
69
+         *    @version    1.0
70
+         *    @var        array
71
+         */
72 72
         private $file_array    = array();
73 73
 
74 74
         /**
75
-        *    If the file you are trying to upload already exists it will
76
-        *    be overwritten if you set the variable to true.
77
-        *
78
-        *    @since        1.0
79
-        *    @version    1.0
80
-        *    @var        boolean
81
-        */
75
+         *    If the file you are trying to upload already exists it will
76
+         *    be overwritten if you set the variable to true.
77
+         *
78
+         *    @since        1.0
79
+         *    @version    1.0
80
+         *    @var        boolean
81
+         */
82 82
         private $overwrite_file = false;
83 83
 
84 84
         /**
85
-        *    Input element
86
-        *    Example:
87
-        *        <input type="file" name="file" />
88
-        *    Result:
89
-        *        FileUpload::$input = file
90
-        *
91
-        *    @since        1.0
92
-        *    @version    1.0
93
-        *    @var        string
94
-        */
85
+         *    Input element
86
+         *    Example:
87
+         *        <input type="file" name="file" />
88
+         *    Result:
89
+         *        FileUpload::$input = file
90
+         *
91
+         *    @since        1.0
92
+         *    @version    1.0
93
+         *    @var        string
94
+         */
95 95
         private $input;
96 96
 
97 97
         /**
98
-        *    Path output
99
-        *
100
-        *    @since        1.0
101
-        *    @version    1.0
102
-        *    @var        string
103
-        */
98
+         *    Path output
99
+         *
100
+         *    @since        1.0
101
+         *    @version    1.0
102
+         *    @var        string
103
+         */
104 104
         private $destination_directory;
105 105
 
106 106
         /**
107
-        *    Output filename
108
-        *
109
-        *    @since        1.0
110
-        *    @version    1.0
111
-        *    @var        string
112
-        */
107
+         *    Output filename
108
+         *
109
+         *    @since        1.0
110
+         *    @version    1.0
111
+         *    @var        string
112
+         */
113 113
         private $filename;
114 114
 
115 115
         /**
116
-        *    Max file size
117
-        *
118
-        *    @since        1.0
119
-        *    @version    1.0
120
-        *    @var        float
121
-        */
116
+         *    Max file size
117
+         *
118
+         *    @since        1.0
119
+         *    @version    1.0
120
+         *    @var        float
121
+         */
122 122
         private $max_file_size= 0.0;
123 123
 
124 124
         /**
125
-        *    List of allowed mime types
126
-        *
127
-        *    @since        1.0
128
-        *    @version    1.0
129
-        *    @var        array
130
-        */
125
+         *    List of allowed mime types
126
+         *
127
+         *    @since        1.0
128
+         *    @version    1.0
129
+         *    @var        array
130
+         */
131 131
         private $allowed_mime_types = array();
132 132
 
133 133
         /**
134
-        *    Callbacks
135
-        *
136
-        *    @since        1.0
137
-        *    @version    1.0
138
-        *    @var        array
139
-        */
134
+         *    Callbacks
135
+         *
136
+         *    @since        1.0
137
+         *    @version    1.0
138
+         *    @var        array
139
+         */
140 140
         private $callbacks = array('before' => null, 'after' => null);
141 141
 
142 142
         /**
143
-        *    File object
144
-        *
145
-        *    @since        1.0
146
-        *    @version    1.0
147
-        *    @var        object
148
-        */
143
+         *    File object
144
+         *
145
+         *    @since        1.0
146
+         *    @version    1.0
147
+         *    @var        object
148
+         */
149 149
         private $file;
150 150
 
151 151
         /**
152
-        *    Helping mime types
153
-        *
154
-        *    @since        1.0
155
-        *    @version    1.0
156
-        *    @var        array
157
-        */
152
+         *    Helping mime types
153
+         *
154
+         *    @since        1.0
155
+         *    @version    1.0
156
+         *    @var        array
157
+         */
158 158
         private $mime_helping = array(
159 159
             'text'      =>    array('text/plain',),
160 160
             'image'     =>    array(
@@ -204,13 +204,13 @@  discard block
 block discarded – undo
204 204
 
205 205
 
206 206
         /**
207
-        *    Construct
208
-        *
209
-        *    @since     0.1
210
-        *    @version   1.0.1
211
-        *    @return    object
212
-        *    @method    object    __construct
213
-        */
207
+         *    Construct
208
+         *
209
+         *    @since     0.1
210
+         *    @version   1.0.1
211
+         *    @return    object
212
+         *    @method    object    __construct
213
+         */
214 214
         public function __construct(){
215 215
             parent::__construct();
216 216
 
@@ -253,17 +253,17 @@  discard block
 block discarded – undo
253 253
             $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
254 254
         }
255 255
         /**
256
-        *    Set input.
257
-        *    If you have $_FILES["file"], you must use the key "file"
258
-        *    Example:
259
-        *        $object->setInput("file");
260
-        *
261
-        *    @since     1.0
262
-        *    @version   1.0
263
-        *    @param     string      $input
264
-        *    @return    object
265
-        *    @method    boolean     setInput
266
-        */
256
+         *    Set input.
257
+         *    If you have $_FILES["file"], you must use the key "file"
258
+         *    Example:
259
+         *        $object->setInput("file");
260
+         *
261
+         *    @since     1.0
262
+         *    @version   1.0
263
+         *    @param     string      $input
264
+         *    @return    object
265
+         *    @method    boolean     setInput
266
+         */
267 267
         public function setInput($input)
268 268
         {
269 269
             if (!empty($input) && (is_string($input) || is_numeric($input) )) {
@@ -272,18 +272,18 @@  discard block
 block discarded – undo
272 272
             return $this;
273 273
         }
274 274
         /**
275
-        *    Set new filename
276
-        *    Example:
277
-        *        FileUpload::setFilename("new file.txt")
278
-        *    Remember:
279
-        *        Use %s to retrive file extension
280
-        *
281
-        *    @since     1.0
282
-        *    @version   1.0
283
-        *    @param     string      $filename
284
-        *    @return    object
285
-        *    @method    boolean     setFilename
286
-        */
275
+         *    Set new filename
276
+         *    Example:
277
+         *        FileUpload::setFilename("new file.txt")
278
+         *    Remember:
279
+         *        Use %s to retrive file extension
280
+         *
281
+         *    @since     1.0
282
+         *    @version   1.0
283
+         *    @param     string      $filename
284
+         *    @return    object
285
+         *    @method    boolean     setFilename
286
+         */
287 287
         public function setFilename($filename)
288 288
         {
289 289
             if ($this->isFilename($filename)) {
@@ -292,14 +292,14 @@  discard block
 block discarded – undo
292 292
             return $this;
293 293
         }
294 294
         /**
295
-        *    Set automatic filename
296
-        *
297
-        *    @since     1.0
298
-        *    @version   1.5
299
-        *    @param     string      $extension
300
-        *    @return    object
301
-        *    @method    boolean     setAutoFilename
302
-        */
295
+         *    Set automatic filename
296
+         *
297
+         *    @since     1.0
298
+         *    @version   1.5
299
+         *    @param     string      $extension
300
+         *    @return    object
301
+         *    @method    boolean     setAutoFilename
302
+         */
303 303
         public function setAutoFilename()
304 304
         {
305 305
             $this->filename = sha1(mt_rand(1, 9999).uniqid());
@@ -307,14 +307,14 @@  discard block
 block discarded – undo
307 307
             return $this;
308 308
         }
309 309
         /**
310
-        *    Set file size limit
311
-        *
312
-        *    @since     1.0
313
-        *    @version   1.0
314
-        *    @param     double     $file_size
315
-        *    @return    object
316
-        *    @method    boolean     setMaxFileSize
317
-        */
310
+         *    Set file size limit
311
+         *
312
+         *    @since     1.0
313
+         *    @version   1.0
314
+         *    @param     double     $file_size
315
+         *    @return    object
316
+         *    @method    boolean     setMaxFileSize
317
+         */
318 318
         public function setMaxFileSize($file_size)
319 319
         {
320 320
             $file_size = $this->sizeInBytes($file_size);
@@ -330,14 +330,14 @@  discard block
 block discarded – undo
330 330
             return $this;
331 331
         }
332 332
         /**
333
-        *    Set array mime types
334
-        *
335
-        *    @since     1.0
336
-        *    @version   1.0
337
-        *    @param     array       $mimes
338
-        *    @return    object
339
-        *    @method    boolean     setAllowedMimeTypes
340
-        */
333
+         *    Set array mime types
334
+         *
335
+         *    @since     1.0
336
+         *    @version   1.0
337
+         *    @param     array       $mimes
338
+         *    @return    object
339
+         *    @method    boolean     setAllowedMimeTypes
340
+         */
341 341
         public function setAllowedMimeTypes(array $mimes)
342 342
         {
343 343
             if (count($mimes) > 0) {
@@ -346,14 +346,14 @@  discard block
 block discarded – undo
346 346
             return $this;
347 347
         }
348 348
         /**
349
-        *    Set input callback
350
-        *
351
-        *    @since     1.0
352
-        *    @version   1.0
353
-        *    @param     mixed       $callback
354
-        *    @return    object
355
-        *    @method    boolean     setCallbackInput
356
-        */
349
+         *    Set input callback
350
+         *
351
+         *    @since     1.0
352
+         *    @version   1.0
353
+         *    @param     mixed       $callback
354
+         *    @return    object
355
+         *    @method    boolean     setCallbackInput
356
+         */
357 357
         public function setCallbackInput($callback)
358 358
         {
359 359
             if (is_callable($callback, false)) {
@@ -362,14 +362,14 @@  discard block
 block discarded – undo
362 362
             return $this;
363 363
         }
364 364
         /**
365
-        *    Set output callback
366
-        *
367
-        *    @since     1.0
368
-        *    @version   1.0
369
-        *    @param     mixed       $callback
370
-        *    @return    object
371
-        *    @method    boolean     setCallbackOutput
372
-        */
365
+         *    Set output callback
366
+         *
367
+         *    @since     1.0
368
+         *    @version   1.0
369
+         *    @param     mixed       $callback
370
+         *    @return    object
371
+         *    @method    boolean     setCallbackOutput
372
+         */
373 373
         public function setCallbackOutput($callback)
374 374
         {
375 375
             if (is_callable($callback, false)) {
@@ -378,14 +378,14 @@  discard block
 block discarded – undo
378 378
             return $this;
379 379
         }
380 380
         /**
381
-        *    Append a mime type to allowed mime types
382
-        *
383
-        *    @since     1.0
384
-        *    @version   1.0.1
385
-        *    @param     string      $mime
386
-        *    @return    object
387
-        *    @method    boolean     setAllowMimeType
388
-        */
381
+         *    Append a mime type to allowed mime types
382
+         *
383
+         *    @since     1.0
384
+         *    @version   1.0.1
385
+         *    @param     string      $mime
386
+         *    @return    object
387
+         *    @method    boolean     setAllowMimeType
388
+         */
389 389
         public function setAllowMimeType($mime)
390 390
         {
391 391
             if (!empty($mime) && is_string($mime)) {
@@ -395,13 +395,13 @@  discard block
 block discarded – undo
395 395
             return $this;
396 396
         }
397 397
         /**
398
-        *    Set allowed mime types from mime helping
399
-        *
400
-        *    @since     1.0.1
401
-        *    @version   1.0.1
402
-        *    @return    object
403
-        *    @method    boolean    setMimeHelping
404
-        */
398
+         *    Set allowed mime types from mime helping
399
+         *
400
+         *    @since     1.0.1
401
+         *    @version   1.0.1
402
+         *    @return    object
403
+         *    @method    boolean    setMimeHelping
404
+         */
405 405
         public function setMimeHelping($name)
406 406
         {
407 407
             if (!empty($name) && is_string($name)) {
@@ -412,17 +412,17 @@  discard block
 block discarded – undo
412 412
             return $this;
413 413
         }
414 414
         /**
415
-        *    Set function to upload file
416
-        *    Examples:
417
-        *        1.- FileUpload::setUploadFunction("move_uploaded_file");
418
-        *        2.- FileUpload::setUploadFunction("copy");
419
-        *
420
-        *    @since     1.0
421
-        *    @version   1.0
422
-        *    @param     string      $function
423
-        *    @return    object
424
-        *    @method    boolean     setUploadFunction
425
-        */
415
+         *    Set function to upload file
416
+         *    Examples:
417
+         *        1.- FileUpload::setUploadFunction("move_uploaded_file");
418
+         *        2.- FileUpload::setUploadFunction("copy");
419
+         *
420
+         *    @since     1.0
421
+         *    @version   1.0
422
+         *    @param     string      $function
423
+         *    @return    object
424
+         *    @method    boolean     setUploadFunction
425
+         */
426 426
         public function setUploadFunction($function)
427 427
         {
428 428
             if (!empty($function) && (is_array($function) || is_string($function) )) {
@@ -433,13 +433,13 @@  discard block
 block discarded – undo
433 433
             return $this;
434 434
         }
435 435
         /**
436
-        *    Clear allowed mime types cache
437
-        *
438
-        *    @since     1.0
439
-        *    @version   1.0
440
-        *    @return    object
441
-        *    @method    boolean    clearAllowedMimeTypes
442
-        */
436
+         *    Clear allowed mime types cache
437
+         *
438
+         *    @since     1.0
439
+         *    @version   1.0
440
+         *    @return    object
441
+         *    @method    boolean    clearAllowedMimeTypes
442
+         */
443 443
         public function clearAllowedMimeTypes()
444 444
         {
445 445
             $this->allowed_mime_types = array();
@@ -447,15 +447,15 @@  discard block
 block discarded – undo
447 447
             return $this;
448 448
         }
449 449
         /**
450
-        *    Set destination output
451
-        *
452
-        *    @since     1.0
453
-        *    @version   1.0
454
-        *    @param     string      $destination_directory      Destination path
455
-        *    @param     boolean     $create_if_not_exist
456
-        *    @return    object
457
-        *    @method    boolean     setDestinationDirectory
458
-        */
450
+         *    Set destination output
451
+         *
452
+         *    @since     1.0
453
+         *    @version   1.0
454
+         *    @param     string      $destination_directory      Destination path
455
+         *    @param     boolean     $create_if_not_exist
456
+         *    @return    object
457
+         *    @method    boolean     setDestinationDirectory
458
+         */
459 459
         public function setDestinationDirectory($destination_directory, $create_if_not_exist = false) {
460 460
             $destination_directory = realpath($destination_directory);
461 461
             if (substr($destination_directory, -1) != DIRECTORY_SEPARATOR) {
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
             return $this;
480 480
         }
481 481
         /**
482
-        *    Check file exists
483
-        *
484
-        *    @since      1.0
485
-        *    @version    1.0.1
486
-        *    @param      string     $file_destination
487
-        *    @return     boolean
488
-        *    @method     boolean    fileExists
489
-        */
482
+         *    Check file exists
483
+         *
484
+         *    @since      1.0
485
+         *    @version    1.0.1
486
+         *    @param      string     $file_destination
487
+         *    @return     boolean
488
+         *    @method     boolean    fileExists
489
+         */
490 490
         public function fileExists($file_destination)
491 491
         {
492 492
             if ($this->isFilename($file_destination)) {
@@ -495,14 +495,14 @@  discard block
 block discarded – undo
495 495
             return false;
496 496
         }
497 497
         /**
498
-        *    Check dir exists
499
-        *
500
-        *    @since        1.0
501
-        *    @version    1.0.1
502
-        *    @param      string     $path
503
-        *    @return     boolean
504
-        *    @method     boolean    dirExists
505
-        */
498
+         *    Check dir exists
499
+         *
500
+         *    @since        1.0
501
+         *    @version    1.0.1
502
+         *    @param      string     $path
503
+         *    @return     boolean
504
+         *    @method     boolean    dirExists
505
+         */
506 506
         public function dirExists($path)
507 507
         {
508 508
             if ($this->isDirpath($path)) {
@@ -511,29 +511,29 @@  discard block
 block discarded – undo
511 511
             return false;
512 512
         }
513 513
         /**
514
-        *    Check valid filename
515
-        *
516
-        *    @since     1.0
517
-        *    @version   1.0.1
518
-        *    @param     string      $filename
519
-        *    @return    boolean
520
-        *    @method    boolean     isFilename
521
-        */
514
+         *    Check valid filename
515
+         *
516
+         *    @since     1.0
517
+         *    @version   1.0.1
518
+         *    @param     string      $filename
519
+         *    @return    boolean
520
+         *    @method    boolean     isFilename
521
+         */
522 522
         public function isFilename($filename)
523 523
         {
524 524
             $filename = basename($filename);
525 525
             return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
526 526
         }
527 527
         /**
528
-        *    Validate mime type with allowed mime types,
529
-        *    but if allowed mime types is empty, this method return true
530
-        *
531
-        *    @since     1.0
532
-        *    @version   1.0
533
-        *    @param     string      $mime
534
-        *    @return    boolean
535
-        *    @method    boolean     checkMimeType
536
-        */
528
+         *    Validate mime type with allowed mime types,
529
+         *    but if allowed mime types is empty, this method return true
530
+         *
531
+         *    @since     1.0
532
+         *    @version   1.0
533
+         *    @param     string      $mime
534
+         *    @return    boolean
535
+         *    @method    boolean     checkMimeType
536
+         */
537 537
         public function checkMimeType($mime)
538 538
         {
539 539
             if (count($this->allowed_mime_types) == 0) {
@@ -542,26 +542,26 @@  discard block
 block discarded – undo
542 542
             return in_array(strtolower($mime), $this->allowed_mime_types);
543 543
         }
544 544
         /**
545
-        *    Retrive status of upload
546
-        *
547
-        *    @since     1.0
548
-        *    @version   1.0
549
-        *    @return    boolean
550
-        *    @method    boolean    getStatus
551
-        */
545
+         *    Retrive status of upload
546
+         *
547
+         *    @since     1.0
548
+         *    @version   1.0
549
+         *    @return    boolean
550
+         *    @method    boolean    getStatus
551
+         */
552 552
         public function getStatus()
553 553
         {
554 554
             return $this->file['status'];
555 555
         }
556 556
         /**
557
-        *    Check valid path
558
-        *
559
-        *    @since        1.0
560
-        *    @version    1.0.1
561
-        *    @param        string    $filename
562
-        *    @return     boolean
563
-        *    @method     boolean    isDirpath
564
-        */
557
+         *    Check valid path
558
+         *
559
+         *    @since        1.0
560
+         *    @version    1.0.1
561
+         *    @param        string    $filename
562
+         *    @return     boolean
563
+         *    @method     boolean    isDirpath
564
+         */
565 565
         public function isDirpath($path)
566 566
         {
567 567
             if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
@@ -574,26 +574,26 @@  discard block
 block discarded – undo
574 574
             return false;
575 575
         }
576 576
         /**
577
-        *    Allow overwriting files
578
-        *
579
-        *    @since      1.0
580
-        *    @version    1.0
581
-        *    @return     object
582
-        *    @method     boolean    allowOverwriting
583
-        */
577
+         *    Allow overwriting files
578
+         *
579
+         *    @since      1.0
580
+         *    @version    1.0
581
+         *    @return     object
582
+         *    @method     boolean    allowOverwriting
583
+         */
584 584
         public function allowOverwriting()
585 585
         {
586 586
             $this->overwrite_file = true;
587 587
             return $this;
588 588
         }
589 589
         /**
590
-        *    File info
591
-        *
592
-        *    @since      1.0
593
-        *    @version    1.0
594
-        *    @return     object
595
-        *    @method     object    getInfo
596
-        */
590
+         *    File info
591
+         *
592
+         *    @since      1.0
593
+         *    @version    1.0
594
+         *    @return     object
595
+         *    @method     object    getInfo
596
+         */
597 597
         public function getInfo()
598 598
         {
599 599
             return (object)$this->file;
@@ -611,13 +611,13 @@  discard block
 block discarded – undo
611 611
 
612 612
         
613 613
         /**
614
-        *    Upload file
615
-        *
616
-        *    @since     1.0
617
-        *    @version   1.0.1
618
-        *    @return    boolean
619
-        *    @method    boolean    save
620
-        */
614
+         *    Upload file
615
+         *
616
+         *    @since     1.0
617
+         *    @version   1.0.1
618
+         *    @return    boolean
619
+         *    @method    boolean    save
620
+         */
621 621
         public function save(){
622 622
             if (count($this->file_array) > 0 && array_key_exists($this->input, $this->file_array)) {
623 623
                 // set original filename if not have a new name
@@ -674,15 +674,15 @@  discard block
 block discarded – undo
674 674
 
675 675
 
676 676
         /**
677
-        *    File size for humans.
678
-        *
679
-        *    @since      1.0
680
-        *    @version    1.0
681
-        *    @param      integer    $bytes
682
-        *    @param      integer    $precision
683
-        *    @return     string
684
-        *    @method     string     sizeFormat
685
-        */
677
+         *    File size for humans.
678
+         *
679
+         *    @since      1.0
680
+         *    @version    1.0
681
+         *    @param      integer    $bytes
682
+         *    @param      integer    $precision
683
+         *    @return     string
684
+         *    @method     string     sizeFormat
685
+         */
686 686
         public function sizeFormat($size, $precision = 2)
687 687
         {
688 688
             if($size > 0){
@@ -695,14 +695,14 @@  discard block
 block discarded – undo
695 695
 
696 696
         
697 697
         /**
698
-        *    Convert human file size to bytes
699
-        *
700
-        *    @since      1.0
701
-        *    @version    1.0.1
702
-        *    @param      integer|double    $size
703
-        *    @return     integer|double
704
-        *    @method     string     sizeInBytes
705
-        */
698
+         *    Convert human file size to bytes
699
+         *
700
+         *    @since      1.0
701
+         *    @version    1.0.1
702
+         *    @param      integer|double    $size
703
+         *    @return     integer|double
704
+         *    @method     string     sizeInBytes
705
+         */
706 706
         public function sizeInBytes($size)
707 707
         {
708 708
             $unit = 'B';
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
                 return true;
755 755
             }
756 756
 
757
-             //check for php upload error
757
+                //check for php upload error
758 758
             if(is_numeric($this->file['error']) && $this->file['error'] > 0){
759 759
                 $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
760 760
                 return true;
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
                 return true;
767 767
             }
768 768
 
769
-             // Check file size
769
+                // Check file size
770 770
             if ($this->max_file_size > 0 && $this->max_file_size < $this->file['size']) {
771 771
                 $this->setError(sprintf($this->error_messages['max_file_size'], $this->sizeFormat($this->max_file_size)));
772 772
                 return true;
Please login to merge, or discard this patch.
core/libraries/Assets.php 1 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') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	/**
28
-	 *  @file Assets.php
29
-	 *    
30
-	 *  This class contains static methods for generating static content links (images, Javascript, CSS, etc.).
31
-	 *  
32
-	 *  @package	core	
33
-	 *  @author	Tony NGUEREZA
34
-	 *  @copyright	Copyright (c) 2017
35
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
-	 *  @link	http://www.iacademy.cf
37
-	 *  @version 1.0.0
38
-	 *  @since 1.0.0
39
-	 *  @filesource
40
-	 */
41
-	class Assets extends BaseStaticClass{
27
+    /**
28
+     *  @file Assets.php
29
+     *    
30
+     *  This class contains static methods for generating static content links (images, Javascript, CSS, etc.).
31
+     *  
32
+     *  @package	core	
33
+     *  @author	Tony NGUEREZA
34
+     *  @copyright	Copyright (c) 2017
35
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
+     *  @link	http://www.iacademy.cf
37
+     *  @version 1.0.0
38
+     *  @since 1.0.0
39
+     *  @filesource
40
+     */
41
+    class Assets extends BaseStaticClass{
42 42
 
43 43
 
44
-		/**
45
-		 *  Generate the link of the assets file.
46
-		 *  
47
-		 *  Generates the absolute link of a file inside ASSETS_PATH folder.
48
-		 *  For example :
49
-		 *  	echo Assets::path('foo/bar/css/style.css'); => http://mysite.com/assets/foo/bar/css/style.css
50
-		 *  Note:
51
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
52
-		 *  
53
-		 *  @param string $asset the name of the assets file path with the extension.
54
-		 *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
55
-		 */
56
-		public static function path($asset){
57
-			$logger = self::getLogger();	
58
-			$path = ASSETS_PATH . $asset;
44
+        /**
45
+         *  Generate the link of the assets file.
46
+         *  
47
+         *  Generates the absolute link of a file inside ASSETS_PATH folder.
48
+         *  For example :
49
+         *  	echo Assets::path('foo/bar/css/style.css'); => http://mysite.com/assets/foo/bar/css/style.css
50
+         *  Note:
51
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
52
+         *  
53
+         *  @param string $asset the name of the assets file path with the extension.
54
+         *  @return string|null the absolute path of the assets file, if it exists otherwise returns null if the file does not exist.
55
+         */
56
+        public static function path($asset){
57
+            $logger = self::getLogger();	
58
+            $path = ASSETS_PATH . $asset;
59 59
 			
60
-			$logger->debug('Including the Assets file [' . $path . ']');
61
-			//Check if the file exists
62
-			if(file_exists($path)){
63
-				$logger->info('Assets file [' . $path . '] included successfully');
64
-				return Url::base_url($path);
65
-			}
66
-			$logger->warning('Assets file [' . $path . '] does not exist');
67
-			return null;
68
-		}
60
+            $logger->debug('Including the Assets file [' . $path . ']');
61
+            //Check if the file exists
62
+            if(file_exists($path)){
63
+                $logger->info('Assets file [' . $path . '] included successfully');
64
+                return Url::base_url($path);
65
+            }
66
+            $logger->warning('Assets file [' . $path . '] does not exist');
67
+            return null;
68
+        }
69 69
 		
70
-		/**
71
-		 *  Generate the link of the css file.
72
-		 *  
73
-		 *  Generates the absolute link of a file containing the CSS style.
74
-		 *  For example :
75
-		 *  	echo Assets::css('mystyle'); => http://mysite.com/assets/css/mystyle.css
76
-		 *  Note:
77
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
78
-		 *  
79
-		 *  @param string $path the name of the css file without the extension.
80
-		 *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
81
-		 */
82
-		public static function css($path){
83
-			$logger = self::getLogger();
84
-			/*
70
+        /**
71
+         *  Generate the link of the css file.
72
+         *  
73
+         *  Generates the absolute link of a file containing the CSS style.
74
+         *  For example :
75
+         *  	echo Assets::css('mystyle'); => http://mysite.com/assets/css/mystyle.css
76
+         *  Note:
77
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
78
+         *  
79
+         *  @param string $path the name of the css file without the extension.
80
+         *  @return string|null the absolute path of the css file, if it exists otherwise returns null if the file does not exist.
81
+         */
82
+        public static function css($path){
83
+            $logger = self::getLogger();
84
+            /*
85 85
 			* if the file name contains the ".css" extension, replace it with 
86 86
 			* an empty string for better processing.
87 87
 			*/
88
-			$path = str_ireplace('.css', '', $path);
89
-			$path = ASSETS_PATH . 'css/' . $path . '.css';
88
+            $path = str_ireplace('.css', '', $path);
89
+            $path = ASSETS_PATH . 'css/' . $path . '.css';
90 90
 			
91
-			$logger->debug('Including the Assets file [' . $path . '] for CSS');
92
-			//Check if the file exists
93
-			if(file_exists($path)){
94
-				$logger->info('Assets file [' . $path . '] for CSS included successfully');
95
-				return Url::base_url($path);
96
-			}
97
-			$logger->warning('Assets file [' . $path . '] for CSS does not exist');
98
-			return null;
99
-		}
91
+            $logger->debug('Including the Assets file [' . $path . '] for CSS');
92
+            //Check if the file exists
93
+            if(file_exists($path)){
94
+                $logger->info('Assets file [' . $path . '] for CSS included successfully');
95
+                return Url::base_url($path);
96
+            }
97
+            $logger->warning('Assets file [' . $path . '] for CSS does not exist');
98
+            return null;
99
+        }
100 100
 
101
-		/**
102
-		 *  Generate the link of the javascript file.
103
-		 *  
104
-		 *  Generates the absolute link of a file containing the javascript.
105
-		 *  For example :
106
-		 *  	echo Assets::js('myscript'); => http://mysite.com/assets/js/myscript.js
107
-		 *  Note:
108
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
109
-		 *  
110
-		 *  @param string $path the name of the javascript file without the extension.
111
-		 *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
112
-		 */
113
-		public static function js($path){
114
-			$logger = self::getLogger();
115
-			$path = str_ireplace('.js', '', $path);
116
-			$path = ASSETS_PATH . 'js/' . $path . '.js';
117
-			$logger->debug('Including the Assets file [' . $path . '] for javascript');
118
-			if(file_exists($path)){
119
-				$logger->info('Assets file [' . $path . '] for Javascript included successfully');
120
-				return Url::base_url($path);
121
-			}
122
-			$logger->warning('Assets file [' . $path . '] for Javascript does not exist');
123
-			return null;
124
-		}
101
+        /**
102
+         *  Generate the link of the javascript file.
103
+         *  
104
+         *  Generates the absolute link of a file containing the javascript.
105
+         *  For example :
106
+         *  	echo Assets::js('myscript'); => http://mysite.com/assets/js/myscript.js
107
+         *  Note:
108
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
109
+         *  
110
+         *  @param string $path the name of the javascript file without the extension.
111
+         *  @return string|null the absolute path of the javascript file, if it exists otherwise returns null if the file does not exist.
112
+         */
113
+        public static function js($path){
114
+            $logger = self::getLogger();
115
+            $path = str_ireplace('.js', '', $path);
116
+            $path = ASSETS_PATH . 'js/' . $path . '.js';
117
+            $logger->debug('Including the Assets file [' . $path . '] for javascript');
118
+            if(file_exists($path)){
119
+                $logger->info('Assets file [' . $path . '] for Javascript included successfully');
120
+                return Url::base_url($path);
121
+            }
122
+            $logger->warning('Assets file [' . $path . '] for Javascript does not exist');
123
+            return null;
124
+        }
125 125
 
126
-		/**
127
-		 *  Generate the link of the image file.
128
-		 *  
129
-		 *  Generates the absolute link of a file containing the image.
130
-		 *  For example :
131
-		 *  	echo Assets::img('myimage.png'); => http://mysite.com/assets/images/myimage.png
132
-		 *  Note:
133
-		 *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
134
-		 *  
135
-		 *  @param string $path the name of the image file with the extension.
136
-		 *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
137
-		 */
138
-		public static function img($path){
139
-			$logger = self::getLogger();
140
-			$path = ASSETS_PATH . 'images/' . $path;
141
-			$logger->debug('Including the Assets file [' . $path . '] for image');
142
-			if(file_exists($path)){
143
-				$logger->info('Assets file [' . $path . '] for image included successfully');
144
-				return Url::base_url($path);
145
-			}
146
-			$logger->warning('Assets file [' . $path . '] for image does not exist');
147
-			return null;
148
-		}
149
-	}
126
+        /**
127
+         *  Generate the link of the image file.
128
+         *  
129
+         *  Generates the absolute link of a file containing the image.
130
+         *  For example :
131
+         *  	echo Assets::img('myimage.png'); => http://mysite.com/assets/images/myimage.png
132
+         *  Note:
133
+         *  The argument passed to this function must be the relative link to the folder that contains the static contents defined by the constant ASSETS_PATH.
134
+         *  
135
+         *  @param string $path the name of the image file with the extension.
136
+         *  @return string|null the absolute path of the image file, if it exists otherwise returns null if the file does not exist.
137
+         */
138
+        public static function img($path){
139
+            $logger = self::getLogger();
140
+            $path = ASSETS_PATH . 'images/' . $path;
141
+            $logger->debug('Including the Assets file [' . $path . '] for image');
142
+            if(file_exists($path)){
143
+                $logger->info('Assets file [' . $path . '] for image included successfully');
144
+                return Url::base_url($path);
145
+            }
146
+            $logger->warning('Assets file [' . $path . '] for image does not exist');
147
+            return null;
148
+        }
149
+    }
Please login to merge, or discard this patch.
core/libraries/Cookie.php 1 patch
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -1,94 +1,94 @@
 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 Cookie extends BaseStaticClass{
27
+    class Cookie extends BaseStaticClass{
28 28
 
29
-		/**
30
-		 * Get the cookie item value
31
-		 * @param  string $item    the cookie item name to get
32
-		 * @param  mixed $default the default value to use if can not find the cokkie item in the list
33
-		 * @return mixed          the cookie value if exist or the default value
34
-		 */
35
-		public static function get($item, $default = null){
36
-			$logger = self::getLogger();
37
-			if(array_key_exists($item, $_COOKIE)){
38
-				return $_COOKIE[$item];
39
-			}
40
-			$logger->warning('Cannot find cookie item [' . $item . '], using the default value [' . $default . ']');
41
-			return $default;
42
-		}
29
+        /**
30
+         * Get the cookie item value
31
+         * @param  string $item    the cookie item name to get
32
+         * @param  mixed $default the default value to use if can not find the cokkie item in the list
33
+         * @return mixed          the cookie value if exist or the default value
34
+         */
35
+        public static function get($item, $default = null){
36
+            $logger = self::getLogger();
37
+            if(array_key_exists($item, $_COOKIE)){
38
+                return $_COOKIE[$item];
39
+            }
40
+            $logger->warning('Cannot find cookie item [' . $item . '], using the default value [' . $default . ']');
41
+            return $default;
42
+        }
43 43
 
44
-		/**
45
-		 * Set the cookie item value
46
-		 * @param string  $name     the cookie item name
47
-		 * @param string  $value    the cookie value to set
48
-		 * @param integer $expire   the time to live for this cookie
49
-		 * @param string  $path     the path that the cookie will be available
50
-		 * @param string  $domain   the domain that the cookie will be available
51
-		 * @param boolean $secure   if this cookie will be available on secure connection or not
52
-		 * @param boolean $httponly if this cookie will be available under HTTP protocol.
53
-		 */
54
-		public static function set($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false){
55
-			if(headers_sent()){
56
-				show_error('There exists a cookie that we wanted to create that we couldn\'t 
44
+        /**
45
+         * Set the cookie item value
46
+         * @param string  $name     the cookie item name
47
+         * @param string  $value    the cookie value to set
48
+         * @param integer $expire   the time to live for this cookie
49
+         * @param string  $path     the path that the cookie will be available
50
+         * @param string  $domain   the domain that the cookie will be available
51
+         * @param boolean $secure   if this cookie will be available on secure connection or not
52
+         * @param boolean $httponly if this cookie will be available under HTTP protocol.
53
+         */
54
+        public static function set($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false){
55
+            if(headers_sent()){
56
+                show_error('There exists a cookie that we wanted to create that we couldn\'t 
57 57
 						    because headers was already sent. Make sure to do this first 
58 58
 							before outputing anything.');
59
-			}
60
-			$timestamp = $expire;
61
-			if($expire){
62
-				$timestamp = time() + $expire;
63
-			}
64
-			setcookie($name, $value, $timestamp, $path, $domain, $secure, $httponly);
65
-		}
59
+            }
60
+            $timestamp = $expire;
61
+            if($expire){
62
+                $timestamp = time() + $expire;
63
+            }
64
+            setcookie($name, $value, $timestamp, $path, $domain, $secure, $httponly);
65
+        }
66 66
 
67
-		/**
68
-		 * Delete the cookie item in the list
69
-		 * @param  string $item the cookie item name to be cleared
70
-		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
71
-		 */
72
-		public static function delete($item){
73
-			$logger = self::getLogger();
74
-			if(array_key_exists($item, $_COOKIE)){
75
-				$logger->info('Delete cookie item ['.$item.']');
76
-				unset($_COOKIE[$item]);
77
-				return true;
78
-			}
79
-			else{
80
-				$logger->warning('Cookie item ['.$item.'] to be deleted does not exists');
81
-				return false;
82
-			}
83
-		}
67
+        /**
68
+         * Delete the cookie item in the list
69
+         * @param  string $item the cookie item name to be cleared
70
+         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
71
+         */
72
+        public static function delete($item){
73
+            $logger = self::getLogger();
74
+            if(array_key_exists($item, $_COOKIE)){
75
+                $logger->info('Delete cookie item ['.$item.']');
76
+                unset($_COOKIE[$item]);
77
+                return true;
78
+            }
79
+            else{
80
+                $logger->warning('Cookie item ['.$item.'] to be deleted does not exists');
81
+                return false;
82
+            }
83
+        }
84 84
 
85
-		/**
86
-		 * Check if the given cookie item exists
87
-		 * @param  string $item the cookie item name
88
-		 * @return boolean       true if the cookie item is set, false or not
89
-		 */
90
-		public static function exists($item){
91
-			return array_key_exists($item, $_COOKIE);
92
-		}
85
+        /**
86
+         * Check if the given cookie item exists
87
+         * @param  string $item the cookie item name
88
+         * @return boolean       true if the cookie item is set, false or not
89
+         */
90
+        public static function exists($item){
91
+            return array_key_exists($item, $_COOKIE);
92
+        }
93 93
 
94
-	}
94
+    }
Please login to merge, or discard this patch.
core/classes/Module.php 1 patch
Indentation   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4 4
      * TNH Framework
5 5
      *
6 6
      * A simple PHP framework using HMVC architecture
@@ -22,252 +22,252 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
    
27
-	class Module extends BaseStaticClass{
27
+    class Module extends BaseStaticClass{
28 28
 		
29
-		/**
30
-		 * list of loaded module
31
-		 * @var array
32
-		 */
33
-		private static $list = array();
29
+        /**
30
+         * list of loaded module
31
+         * @var array
32
+         */
33
+        private static $list = array();
34 34
 
35
-		/**
36
-		 * Initialise the module list by scanning the directory MODULE_PATH
37
-		 */
38
-		public function init(){
39
-			$logger = self::getLogger();
40
-			$logger->debug('Check if the application contains the modules ...');
41
-			$moduleDir = opendir(MODULE_PATH);
42
-			if (is_resource($moduleDir)){
43
-				while(($module = readdir($moduleDir)) !== false){
44
-					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
45
-						self::$list[] = $module;
46
-					}
47
-					else{
48
-						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
49
-					}
50
-				}
51
-				closedir($moduleDir);
52
-			}
53
-			ksort(self::$list);
35
+        /**
36
+         * Initialise the module list by scanning the directory MODULE_PATH
37
+         */
38
+        public function init(){
39
+            $logger = self::getLogger();
40
+            $logger->debug('Check if the application contains the modules ...');
41
+            $moduleDir = opendir(MODULE_PATH);
42
+            if (is_resource($moduleDir)){
43
+                while(($module = readdir($moduleDir)) !== false){
44
+                    if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
45
+                        self::$list[] = $module;
46
+                    }
47
+                    else{
48
+                        $logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
49
+                    }
50
+                }
51
+                closedir($moduleDir);
52
+            }
53
+            ksort(self::$list);
54 54
 			
55
-			if (! empty(self::$list)){
56
-				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
57
-			}
58
-		}
55
+            if (! empty(self::$list)){
56
+                $logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
57
+            }
58
+        }
59 59
 		
60 60
 
61
-		/**
62
-		 * Add new module in the list
63
-		 * @param string $name the name of the module
64
-		 *
65
-		 * @return object the current instance
66
-		 */
67
-		public function add($name){
68
-			self::$list[] = $name;
69
-			return $this;
70
-		}
61
+        /**
62
+         * Add new module in the list
63
+         * @param string $name the name of the module
64
+         *
65
+         * @return object the current instance
66
+         */
67
+        public function add($name){
68
+            self::$list[] = $name;
69
+            return $this;
70
+        }
71 71
 		
72
-		/**
73
-		 * Get the list of the custom autoload configuration from module if exists
74
-		 * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
75
-		 */
76
-		public static function getModulesAutoloadConfig(){
77
-			$logger = self::getLogger();
78
-			if (empty(self::$list)){
79
-				$logger->info('No module was loaded skipping.');
80
-				return false;
81
-			}
82
-			$autoloads = array();
83
-			$autoloads['libraries'] = array();
84
-			$autoloads['config']    = array();
85
-			$autoloads['models']    = array();
86
-			$autoloads['functions'] = array();
87
-			$autoloads['languages'] = array();
72
+        /**
73
+         * Get the list of the custom autoload configuration from module if exists
74
+         * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
75
+         */
76
+        public static function getModulesAutoloadConfig(){
77
+            $logger = self::getLogger();
78
+            if (empty(self::$list)){
79
+                $logger->info('No module was loaded skipping.');
80
+                return false;
81
+            }
82
+            $autoloads = array();
83
+            $autoloads['libraries'] = array();
84
+            $autoloads['config']    = array();
85
+            $autoloads['models']    = array();
86
+            $autoloads['functions'] = array();
87
+            $autoloads['languages'] = array();
88 88
 			
89
-			foreach (self::$list as $module) {
90
-				$file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
91
-				if (file_exists($file)){
92
-					$autoload = array();
93
-					require_once $file;
94
-					if (! empty($autoload) && is_array($autoload)){
95
-						$autoloads = array_merge_recursive($autoloads, $autoload);
96
-						unset($autoload);
97
-					}
98
-				}
99
-			}
100
-			return $autoloads;
101
-		}
89
+            foreach (self::$list as $module) {
90
+                $file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
91
+                if (file_exists($file)){
92
+                    $autoload = array();
93
+                    require_once $file;
94
+                    if (! empty($autoload) && is_array($autoload)){
95
+                        $autoloads = array_merge_recursive($autoloads, $autoload);
96
+                        unset($autoload);
97
+                    }
98
+                }
99
+            }
100
+            return $autoloads;
101
+        }
102 102
 
103
-		/**
104
-		 * Get the list of the custom routes configuration from module if exists
105
-		 * @return array|boolean the routes list or false if no module contains the routes configuration
106
-		 */
107
-		public static function getModulesRoutesConfig(){
108
-			$logger = self::getLogger();
109
-			if (empty(self::$list)){
110
-				$logger->info('No module was loaded skipping.');
111
-				return false;
112
-			}
113
-			$routes = array();
114
-			foreach (self::$list as $module) {
115
-				$file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
116
-				if (file_exists($file)){
117
-					$route = array();
118
-					require_once $file;
119
-					if (! empty($route) && is_array($route)){
120
-						$routes = array_merge($routes, $route);
121
-						unset($route);
122
-					}
123
-				}
124
-			}
125
-			return $routes;
126
-		}
103
+        /**
104
+         * Get the list of the custom routes configuration from module if exists
105
+         * @return array|boolean the routes list or false if no module contains the routes configuration
106
+         */
107
+        public static function getModulesRoutesConfig(){
108
+            $logger = self::getLogger();
109
+            if (empty(self::$list)){
110
+                $logger->info('No module was loaded skipping.');
111
+                return false;
112
+            }
113
+            $routes = array();
114
+            foreach (self::$list as $module) {
115
+                $file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
116
+                if (file_exists($file)){
117
+                    $route = array();
118
+                    require_once $file;
119
+                    if (! empty($route) && is_array($route)){
120
+                        $routes = array_merge($routes, $route);
121
+                        unset($route);
122
+                    }
123
+                }
124
+            }
125
+            return $routes;
126
+        }
127 127
 
128 128
 
129
-		/**
130
-		 * Check if in module list can have this controller
131
-		 * @see Module::findClassInModuleFullFilePath
132
-		 * @return boolean|string  false or null if no module have this controller, path the full path of the controller
133
-		 */
134
-		public static function findControllerFullPath($class, $module = null){
135
-			return self::findClassInModuleFullFilePath($class, $module, 'controllers');
136
-		}
129
+        /**
130
+         * Check if in module list can have this controller
131
+         * @see Module::findClassInModuleFullFilePath
132
+         * @return boolean|string  false or null if no module have this controller, path the full path of the controller
133
+         */
134
+        public static function findControllerFullPath($class, $module = null){
135
+            return self::findClassInModuleFullFilePath($class, $module, 'controllers');
136
+        }
137 137
 
138
-		/**
139
-		 * Check if in module list can have this model
140
-		 * @see Module::findClassInModuleFullFilePath
141
-		 * @return boolean|string  false or null if no module have this model, return the full path of this model
142
-		 */
143
-		public static function findModelFullPath($class, $module = null){
144
-			return self::findClassInModuleFullFilePath($class, $module, 'models');
145
-		}
138
+        /**
139
+         * Check if in module list can have this model
140
+         * @see Module::findClassInModuleFullFilePath
141
+         * @return boolean|string  false or null if no module have this model, return the full path of this model
142
+         */
143
+        public static function findModelFullPath($class, $module = null){
144
+            return self::findClassInModuleFullFilePath($class, $module, 'models');
145
+        }
146 146
 
147
-		/**
148
-		 * Check if in module list can have this library
149
-		 * @see Module::findClassInModuleFullFilePath
150
-		 * @return boolean|string  false or null if no module have this library,  return the full path of this library
151
-		 */
152
-		public static function findLibraryFullPath($class, $module = null){
153
-			return self::findClassInModuleFullFilePath($class, $module, 'libraries');
154
-		}
147
+        /**
148
+         * Check if in module list can have this library
149
+         * @see Module::findClassInModuleFullFilePath
150
+         * @return boolean|string  false or null if no module have this library,  return the full path of this library
151
+         */
152
+        public static function findLibraryFullPath($class, $module = null){
153
+            return self::findClassInModuleFullFilePath($class, $module, 'libraries');
154
+        }
155 155
 
156 156
 		
157
-		/**
158
-		 * Check if in module list can have this config
159
-		 * @see  Module::findNonClassInModuleFullFilePath
160
-		 * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
161
-		 */
162
-		public static function findConfigFullPath($configuration, $module = null){
163
-			return self::findNonClassInModuleFullFilePath($configuration, $module, 'config');
164
-		}
157
+        /**
158
+         * Check if in module list can have this config
159
+         * @see  Module::findNonClassInModuleFullFilePath
160
+         * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
161
+         */
162
+        public static function findConfigFullPath($configuration, $module = null){
163
+            return self::findNonClassInModuleFullFilePath($configuration, $module, 'config');
164
+        }
165 165
 
166
-		/**
167
-		 * Check if in module list can have this helper
168
-		 * @see  Module::findNonClassInModuleFullFilePath
169
-		 * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
170
-		 */
171
-		public static function findFunctionFullPath($helper, $module = null){
172
-			return self::findNonClassInModuleFullFilePath($helper, $module, 'functions');
173
-		}
166
+        /**
167
+         * Check if in module list can have this helper
168
+         * @see  Module::findNonClassInModuleFullFilePath
169
+         * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
170
+         */
171
+        public static function findFunctionFullPath($helper, $module = null){
172
+            return self::findNonClassInModuleFullFilePath($helper, $module, 'functions');
173
+        }
174 174
 
175
-		/**
176
-		 * Check if in module list can have this view
177
-		 * @see  Module::findNonClassInModuleFullFilePath
178
-		 * @return boolean|string  false or null if no module have this view, path the full path of the view
179
-		 */
180
-		public static function findViewFullPath($view, $module = null){
181
-			return self::findNonClassInModuleFullFilePath($view, $module, 'views');
182
-		}
175
+        /**
176
+         * Check if in module list can have this view
177
+         * @see  Module::findNonClassInModuleFullFilePath
178
+         * @return boolean|string  false or null if no module have this view, path the full path of the view
179
+         */
180
+        public static function findViewFullPath($view, $module = null){
181
+            return self::findNonClassInModuleFullFilePath($view, $module, 'views');
182
+        }
183 183
 
184
-		/**
185
-		 * Check if in module list can have this language
186
-		 * @see  Module::findNonClassInModuleFullFilePath
187
-		 * @return boolean|string  false or null if no module have this language,  return the full path of this language
188
-		 */
189
-		public static function findLanguageFullPath($language, $appLang, $module = null){
190
-			return self::findNonClassInModuleFullFilePath($language, $module, 'lang', $appLang);
191
-		}
184
+        /**
185
+         * Check if in module list can have this language
186
+         * @see  Module::findNonClassInModuleFullFilePath
187
+         * @return boolean|string  false or null if no module have this language,  return the full path of this language
188
+         */
189
+        public static function findLanguageFullPath($language, $appLang, $module = null){
190
+            return self::findNonClassInModuleFullFilePath($language, $module, 'lang', $appLang);
191
+        }
192 192
 
193
-		/**
194
-		 * Get the list of module loaded
195
-		 * @return array the module list
196
-		 */
197
-		public static function getModuleList(){
198
-			return self::$list;
199
-		}
193
+        /**
194
+         * Get the list of module loaded
195
+         * @return array the module list
196
+         */
197
+        public static function getModuleList(){
198
+            return self::$list;
199
+        }
200 200
 
201
-		/**
202
-		 * Check if the application has an module
203
-		 * @return boolean
204
-		 */
205
-		public static function hasModule(){
206
-			return !empty(self::$list);
207
-		}
201
+        /**
202
+         * Check if the application has an module
203
+         * @return boolean
204
+         */
205
+        public static function hasModule(){
206
+            return !empty(self::$list);
207
+        }
208 208
 
209
-		/**
210
-		 * Check if in module list can have the model, controller, library
211
-		 * @param  string $class the class name of library, model, controller
212
-		 * @param string $module the module name
213
-		 * @param string $type the name of the type "controllers", "libraries", "models"
214
-		 * @return boolean|string  false or null if no module 
215
-		 * have this class, return the full path of the class
216
-		 */
217
-		protected static function findClassInModuleFullFilePath($class, $module, $type){
218
-			$logger = self::getLogger();
219
-		    $class = str_ireplace('.php', '', $class);
220
-		    $class = ucfirst($class);
221
-		    $classFile = $class.'.php';
222
-		    $logger->debug('Checking the class [' . $class . '] in module [' . $module . '] for [' . $type . '] ...');
223
-		    $filePath = MODULE_PATH . $module . DS . $type . DS . $classFile;
224
-		    if (file_exists($filePath)){
225
-		        $logger->info('Found class [' . $class . '] in module [' . $module . '] for [' . $type . '] the file path is [' .$filePath. ']');
226
-		        return $filePath;
227
-		    }
228
-		    $logger->info('Class [' . $class . '] does not exist in the module [' .$module. '] for [' . $type . ']');
229
-		    return false;
230
-		}
209
+        /**
210
+         * Check if in module list can have the model, controller, library
211
+         * @param  string $class the class name of library, model, controller
212
+         * @param string $module the module name
213
+         * @param string $type the name of the type "controllers", "libraries", "models"
214
+         * @return boolean|string  false or null if no module 
215
+         * have this class, return the full path of the class
216
+         */
217
+        protected static function findClassInModuleFullFilePath($class, $module, $type){
218
+            $logger = self::getLogger();
219
+            $class = str_ireplace('.php', '', $class);
220
+            $class = ucfirst($class);
221
+            $classFile = $class.'.php';
222
+            $logger->debug('Checking the class [' . $class . '] in module [' . $module . '] for [' . $type . '] ...');
223
+            $filePath = MODULE_PATH . $module . DS . $type . DS . $classFile;
224
+            if (file_exists($filePath)){
225
+                $logger->info('Found class [' . $class . '] in module [' . $module . '] for [' . $type . '] the file path is [' .$filePath. ']');
226
+                return $filePath;
227
+            }
228
+            $logger->info('Class [' . $class . '] does not exist in the module [' .$module. '] for [' . $type . ']');
229
+            return false;
230
+        }
231 231
 
232
-		/**
233
-		 * Check if in module list can have the config, view, helper, language
234
-		 * @param string $name the name of config, view, helper, language
235
-		 * @param string $module the module name
236
-		 * @param string $type the name of the type "config", "functions", "views", "lang"
237
-		 * @param string|null $appLang the application language. This is use only when $type = "lang"
238
-		 * @return boolean|string  false or null if no module 
239
-		 * have this resource, return the full path of the resource
240
-		 */
241
-		protected static function findNonClassInModuleFullFilePath($name, $module, $type, $appLang = null){
242
-		    $logger = self::getLogger();
243
-		    $name = str_ireplace('.php', '', $name);
244
-		    $file = $name.'.php';
245
-		    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
246
-		    switch($type){
247
-		        case 'functions':
248
-		            $name = str_ireplace('function_', '', $name);
249
-		            $file = 'function_'.$name.'.php';
250
-		            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
251
-		        break;
252
-		        case 'views':
253
-		            $name = trim($name, '/\\');
254
-		            $name = str_ireplace('/', DS, $name);
255
-		            $file = $name . '.php';
256
-		            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
257
-		        break;
258
-		        case 'lang':
259
-		            $name = str_ireplace('lang_', '', $name);
260
-		            $file = 'lang_'.$name.'.php';
261
-		            $filePath = MODULE_PATH . $module . DS . $type . DS . $appLang . DS . $file;
262
-		        break;
263
-		    }
264
-		    $logger->debug('Checking resource [' . $name . '] in module [' .$module. '] for [' . $type . '] ...');
265
-		    if (file_exists($filePath)){
266
-		        $logger->info('Found resource [' . $name . '] in module [' .$module. '] for [' . $type . '] the file path is [' .$filePath. ']');
267
-		        return $filePath;
268
-		    }
269
-		    $logger->info('Resource [' . $name . '] does not exist in the module [' .$module. '] for [' . $type . ']');
270
-		    return false;
271
-		}
232
+        /**
233
+         * Check if in module list can have the config, view, helper, language
234
+         * @param string $name the name of config, view, helper, language
235
+         * @param string $module the module name
236
+         * @param string $type the name of the type "config", "functions", "views", "lang"
237
+         * @param string|null $appLang the application language. This is use only when $type = "lang"
238
+         * @return boolean|string  false or null if no module 
239
+         * have this resource, return the full path of the resource
240
+         */
241
+        protected static function findNonClassInModuleFullFilePath($name, $module, $type, $appLang = null){
242
+            $logger = self::getLogger();
243
+            $name = str_ireplace('.php', '', $name);
244
+            $file = $name.'.php';
245
+            $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
246
+            switch($type){
247
+                case 'functions':
248
+                    $name = str_ireplace('function_', '', $name);
249
+                    $file = 'function_'.$name.'.php';
250
+                    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
251
+                break;
252
+                case 'views':
253
+                    $name = trim($name, '/\\');
254
+                    $name = str_ireplace('/', DS, $name);
255
+                    $file = $name . '.php';
256
+                    $filePath = MODULE_PATH . $module . DS . $type . DS . $file;
257
+                break;
258
+                case 'lang':
259
+                    $name = str_ireplace('lang_', '', $name);
260
+                    $file = 'lang_'.$name.'.php';
261
+                    $filePath = MODULE_PATH . $module . DS . $type . DS . $appLang . DS . $file;
262
+                break;
263
+            }
264
+            $logger->debug('Checking resource [' . $name . '] in module [' .$module. '] for [' . $type . '] ...');
265
+            if (file_exists($filePath)){
266
+                $logger->info('Found resource [' . $name . '] in module [' .$module. '] for [' . $type . '] the file path is [' .$filePath. ']');
267
+                return $filePath;
268
+            }
269
+            $logger->info('Resource [' . $name . '] does not exist in the module [' .$module. '] for [' . $type . ']');
270
+            return false;
271
+        }
272 272
 
273
-	}
273
+    }
Please login to merge, or discard this patch.
core/classes/Config.php 1 patch
Indentation   +148 added lines, -148 removed lines patch added patch discarded remove patch
@@ -1,160 +1,160 @@
 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 extends BaseStaticClass{
27
+    class Config extends BaseStaticClass{
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
-		 * Initialize the configuration by loading all the configuration from config file
37
-		 */
38
-		public static function init(){
39
-			$logger = self::getLogger();
40
-			$logger->debug('Initialization of the configuration');
41
-			self::$config = & load_configurations();
42
-			self::setBaseUrlUsingServerVar();
43
-			if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
44
-				$logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
45
-			}
46
-			$logger->info('Configuration initialized successfully');
47
-			$logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
48
-		}
35
+        /**
36
+         * Initialize the configuration by loading all the configuration from config file
37
+         */
38
+        public static function init(){
39
+            $logger = self::getLogger();
40
+            $logger->debug('Initialization of the configuration');
41
+            self::$config = & load_configurations();
42
+            self::setBaseUrlUsingServerVar();
43
+            if(ENVIRONMENT == 'production' && in_array(strtolower(self::$config['log_level']), array('debug', 'info','all'))){
44
+                $logger->warning('You are in production environment, please set log level to WARNING, ERROR, FATAL to increase the application performance');
45
+            }
46
+            $logger->info('Configuration initialized successfully');
47
+            $logger->info('The application configuration are listed below: ' . stringfy_vars(self::$config));
48
+        }
49 49
 
50
-		/**
51
-		 * Get the configuration item value
52
-		 * @param  string $item    the configuration item name to get
53
-		 * @param  mixed $default the default value to use if can not find the config item in the list
54
-		 * @return mixed          the config value if exist or the default value
55
-		 */
56
-		public static function get($item, $default = null){
57
-			$logger = self::getLogger();
58
-			if(array_key_exists($item, self::$config)){
59
-				return self::$config[$item];
60
-			}
61
-			$logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
62
-			return $default;
63
-		}
50
+        /**
51
+         * Get the configuration item value
52
+         * @param  string $item    the configuration item name to get
53
+         * @param  mixed $default the default value to use if can not find the config item in the list
54
+         * @return mixed          the config value if exist or the default value
55
+         */
56
+        public static function get($item, $default = null){
57
+            $logger = self::getLogger();
58
+            if(array_key_exists($item, self::$config)){
59
+                return self::$config[$item];
60
+            }
61
+            $logger->warning('Cannot find config item ['.$item.'] using the default value ['.$default.']');
62
+            return $default;
63
+        }
64 64
 
65
-		/**
66
-		 * Set the configuration item value
67
-		 * @param string $item  the config item name to set
68
-		 * @param mixed $value the config item value
69
-		 */
70
-		public static function set($item, $value){
71
-			self::$config[$item] = $value;
72
-		}
65
+        /**
66
+         * Set the configuration item value
67
+         * @param string $item  the config item name to set
68
+         * @param mixed $value the config item value
69
+         */
70
+        public static function set($item, $value){
71
+            self::$config[$item] = $value;
72
+        }
73 73
 
74
-		/**
75
-		 * Get all the configuration values
76
-		 * @return array the config values
77
-		 */
78
-		public static function getAll(){
79
-			return self::$config;
80
-		}
74
+        /**
75
+         * Get all the configuration values
76
+         * @return array the config values
77
+         */
78
+        public static function getAll(){
79
+            return self::$config;
80
+        }
81 81
 
82
-		/**
83
-		 * Set the configuration values bu merged with the existing configuration
84
-		 * @param array $config the config values to add in the configuration list
85
-		 */
86
-		public static function setAll(array $config = array()){
87
-			self::$config = array_merge(self::$config, $config);
88
-		}
82
+        /**
83
+         * Set the configuration values bu merged with the existing configuration
84
+         * @param array $config the config values to add in the configuration list
85
+         */
86
+        public static function setAll(array $config = array()){
87
+            self::$config = array_merge(self::$config, $config);
88
+        }
89 89
 
90
-		/**
91
-		 * Delete the configuration item in the list
92
-		 * @param  string $item the config item name to be deleted
93
-		 * @return boolean true if the item exists and is deleted successfully otherwise will return false.
94
-		 */
95
-		public static function delete($item){
96
-			$logger = self::getLogger();
97
-			if(array_key_exists($item, self::$config)){
98
-				$logger->info('Delete config item ['.$item.']');
99
-				unset(self::$config[$item]);
100
-				return true;
101
-			}
102
-			else{
103
-				$logger->warning('Config item ['.$item.'] to be deleted does not exists');
104
-				return false;
105
-			}
106
-		}
90
+        /**
91
+         * Delete the configuration item in the list
92
+         * @param  string $item the config item name to be deleted
93
+         * @return boolean true if the item exists and is deleted successfully otherwise will return false.
94
+         */
95
+        public static function delete($item){
96
+            $logger = self::getLogger();
97
+            if(array_key_exists($item, self::$config)){
98
+                $logger->info('Delete config item ['.$item.']');
99
+                unset(self::$config[$item]);
100
+                return true;
101
+            }
102
+            else{
103
+                $logger->warning('Config item ['.$item.'] to be deleted does not exists');
104
+                return false;
105
+            }
106
+        }
107 107
 
108
-		/**
109
-		 * Load the configuration file. This an alias to Loader::config()
110
-		 * @param  string $config the config name to be loaded
111
-		 */
112
-		public static function load($config){
113
-			Loader::config($config);
114
-		}
108
+        /**
109
+         * Load the configuration file. This an alias to Loader::config()
110
+         * @param  string $config the config name to be loaded
111
+         */
112
+        public static function load($config){
113
+            Loader::config($config);
114
+        }
115 115
 
116
-		/**
117
-		 * Set the configuration for "base_url" if is not set in the configuration
118
-		 */
119
-		private static function setBaseUrlUsingServerVar(){
120
-			$logger = self::getLogger();
121
-			if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
122
-				if(ENVIRONMENT == 'production'){
123
-					$logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
124
-				}
125
-				$baseUrl = null;
126
-				$protocol = 'http';
127
-				if(is_https()){
128
-					$protocol = 'https';
129
-				}
130
-				$protocol .='://';
116
+        /**
117
+         * Set the configuration for "base_url" if is not set in the configuration
118
+         */
119
+        private static function setBaseUrlUsingServerVar(){
120
+            $logger = self::getLogger();
121
+            if (! isset(self::$config['base_url']) || ! is_url(self::$config['base_url'])){
122
+                if(ENVIRONMENT == 'production'){
123
+                    $logger->warning('Application base URL is not set or invalid, please set application base URL to increase the application loading time');
124
+                }
125
+                $baseUrl = null;
126
+                $protocol = 'http';
127
+                if(is_https()){
128
+                    $protocol = 'https';
129
+                }
130
+                $protocol .='://';
131 131
 
132
-				if (isset($_SERVER['SERVER_ADDR'])){
133
-					$baseUrl = $_SERVER['SERVER_ADDR'];
134
-					//check if the server is running under IPv6
135
-					if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
136
-						$baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
137
-					}
138
-					$serverPort = 80;
139
-					if (isset($_SERVER['SERVER_PORT'])) {
140
-						$serverPort = $_SERVER['SERVER_PORT'];
141
-					}
142
-					$port = '';
143
-					if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
144
-						$port = ':'.$serverPort;
145
-					}
146
-					$baseUrl = $protocol . $baseUrl . $port . substr(
147
-																		$_SERVER['SCRIPT_NAME'], 
148
-																		0, 
149
-																		strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
150
-																	);
151
-				}
152
-				else{
153
-					$logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
154
-					$baseUrl = 'http://localhost/';
155
-				}
156
-				self::set('base_url', $baseUrl);
157
-			}
158
-			self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
159
-		}
160
-	}
132
+                if (isset($_SERVER['SERVER_ADDR'])){
133
+                    $baseUrl = $_SERVER['SERVER_ADDR'];
134
+                    //check if the server is running under IPv6
135
+                    if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE){
136
+                        $baseUrl = '['.$_SERVER['SERVER_ADDR'].']';
137
+                    }
138
+                    $serverPort = 80;
139
+                    if (isset($_SERVER['SERVER_PORT'])) {
140
+                        $serverPort = $_SERVER['SERVER_PORT'];
141
+                    }
142
+                    $port = '';
143
+                    if($serverPort && ((is_https() && $serverPort != 443) || (!is_https() && $serverPort != 80))){
144
+                        $port = ':'.$serverPort;
145
+                    }
146
+                    $baseUrl = $protocol . $baseUrl . $port . substr(
147
+                                                                        $_SERVER['SCRIPT_NAME'], 
148
+                                                                        0, 
149
+                                                                        strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))
150
+                                                                    );
151
+                }
152
+                else{
153
+                    $logger->warning('Can not determine the application base URL automatically, use http://localhost as default');
154
+                    $baseUrl = 'http://localhost/';
155
+                }
156
+                self::set('base_url', $baseUrl);
157
+            }
158
+            self::$config['base_url'] = rtrim(self::$config['base_url'], '/') .'/';
159
+        }
160
+    }
Please login to merge, or discard this patch.
core/classes/database/DatabaseQueryRunner.php 1 patch
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -1,85 +1,85 @@  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 DatabaseQueryRunner extends BaseClass{
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 DatabaseQueryRunner extends BaseClass{
27 27
       
28 28
    
29
-  	/**
30
-  	 * The last query result
31
-  	 * @var object
32
-  	*/
33
-  	private $queryResult       = null;
29
+        /**
30
+         * The last query result
31
+         * @var object
32
+         */
33
+        private $queryResult       = null;
34 34
   	
35
-  	/**
36
-    * The benchmark instance
37
-    * @var object
38
-    */
35
+        /**
36
+         * The benchmark instance
37
+         * @var object
38
+         */
39 39
     private $benchmarkInstance = null;
40 40
     
41 41
     /**
42
-	 * The SQL query statment to execute
43
-	 * @var string
44
-	*/
42
+     * The SQL query statment to execute
43
+     * @var string
44
+     */
45 45
     private $query             = null;
46 46
     
47 47
     /**
48
-	 * Indicate if we need return result as list (boolean) 
48
+     * Indicate if we need return result as list (boolean) 
49 49
      * or the data used to replace the placeholder (array)
50
-	 * @var array|boolean
51
-	 */
52
-     private $returnAsList     = true;
50
+     * @var array|boolean
51
+     */
52
+        private $returnAsList     = true;
53 53
      
54 54
      
55
-     /**
56
-	   * Indicate if we need return result as array or not
57
-     * @var boolean
58
-	   */
59
-     private $returnAsArray     = true;
55
+        /**
56
+         * Indicate if we need return result as array or not
57
+         * @var boolean
58
+         */
59
+        private $returnAsArray     = true;
60 60
      
61
-     /**
62
-     * The last PDOStatment instance
63
-     * @var object
64
-     */
65
-     private $pdoStatment       = null;
61
+        /**
62
+         * The last PDOStatment instance
63
+         * @var object
64
+         */
65
+        private $pdoStatment       = null;
66 66
      
67
-     /**
68
-  	 * The error returned for the last query
69
-  	 * @var string
70
-  	 */
71
-     private $error             = null;
67
+        /**
68
+         * The error returned for the last query
69
+         * @var string
70
+         */
71
+        private $error             = null;
72 72
 	
73 73
     /**
74 74
      * The PDO instance
75 75
      * @var object
76
-    */
76
+     */
77 77
     private $pdo                = null;
78 78
   
79 79
     /**
80 80
      * The database driver name used
81 81
      * @var string
82
-    */
82
+     */
83 83
     private $driver             = null;
84 84
 
85 85
 
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
     public function __construct(PDO $pdo = null, $query = null, $returnAsList = true, $returnAsArray = false){
95 95
         parent::__construct();
96 96
         if (is_object($pdo)){
97
-          $this->pdo = $pdo;
97
+            $this->pdo = $pdo;
98 98
         }
99 99
         $this->query         = $query;
100 100
         $this->returnAsList  = $returnAsList;
@@ -112,10 +112,10 @@  discard block
 block discarded – undo
112 112
         //reset instance
113 113
         $this->reset();
114 114
        
115
-       //for database query execution time
115
+        //for database query execution time
116 116
         $benchmarkMarkerKey = $this->getBenchmarkKey();
117 117
         if (! is_object($this->benchmarkInstance)){
118
-          $this->benchmarkInstance = & class_loader('Benchmark');
118
+            $this->benchmarkInstance = & class_loader('Benchmark');
119 119
         }
120 120
         
121 121
         $this->logger->info('Execute SQL query [' . $this->query . ']');
@@ -128,101 +128,101 @@  discard block
 block discarded – undo
128 128
         $responseTime = $this->benchmarkInstance->elapsedTime(
129 129
                                                                 'DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 
130 130
                                                                 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')'
131
-                                                              );
132
-		    //TODO use the configuration value for the high response time currently is 1 second
131
+                                                                );
132
+            //TODO use the configuration value for the high response time currently is 1 second
133 133
         if ($responseTime >= 1 ){
134 134
             $this->logger->warning(
135 135
                                     'High response time while processing database query [' . $this->query . ']. 
136 136
                                      The response time is [' .$responseTime. '] sec.'
137
-                                  );
137
+                                    );
138 138
         }
139 139
 		
140 140
         if ($this->pdoStatment !== false){
141
-          $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
142
-          if($isSqlSELECTQuery){
143
-              $this->setResultForSelect();              
144
-          }
145
-          else{
146
-              $this->setResultForNonSelect();
147
-          }
148
-          return $this->queryResult;
141
+            $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
142
+            if($isSqlSELECTQuery){
143
+                $this->setResultForSelect();              
144
+            }
145
+            else{
146
+                $this->setResultForNonSelect();
147
+            }
148
+            return $this->queryResult;
149 149
         }
150 150
         $this->setQueryRunnerError();
151 151
     }
152 152
 	
153
-   /**
154
-   * Return the result for SELECT query
155
-   * @see DatabaseQueryRunner::execute
156
-   */
153
+    /**
154
+     * Return the result for SELECT query
155
+     * @see DatabaseQueryRunner::execute
156
+     */
157 157
     protected function setResultForSelect(){
158
-      //if need return all result like list of record
159
-      $result = null;
160
-      $numRows = 0;
161
-      $fetchMode = PDO::FETCH_OBJ;
162
-      if($this->returnAsArray){
158
+        //if need return all result like list of record
159
+        $result = null;
160
+        $numRows = 0;
161
+        $fetchMode = PDO::FETCH_OBJ;
162
+        if($this->returnAsArray){
163 163
         $fetchMode = PDO::FETCH_ASSOC;
164
-      }
165
-      if ($this->returnAsList){
166
-          $result = $this->pdoStatment->fetchAll($fetchMode);
167
-      }
168
-      else{
169
-          $result = $this->pdoStatment->fetch($fetchMode);
170
-      }
171
-      //Sqlite and pgsql always return 0 when using rowCount()
172
-      if (in_array($this->driver, array('sqlite', 'pgsql'))){
164
+        }
165
+        if ($this->returnAsList){
166
+            $result = $this->pdoStatment->fetchAll($fetchMode);
167
+        }
168
+        else{
169
+            $result = $this->pdoStatment->fetch($fetchMode);
170
+        }
171
+        //Sqlite and pgsql always return 0 when using rowCount()
172
+        if (in_array($this->driver, array('sqlite', 'pgsql'))){
173 173
         $numRows = count($result);  
174
-      }
175
-      else{
174
+        }
175
+        else{
176 176
         $numRows = $this->pdoStatment->rowCount(); 
177
-      }
178
-      if(! is_object($this->queryResult)){
179
-          $this->queryResult = & class_loader('DatabaseQueryResult', 'classes/database');
180
-      }
181
-      $this->queryResult->setResult($result);
182
-      $this->queryResult->setNumRows($numRows);
177
+        }
178
+        if(! is_object($this->queryResult)){
179
+            $this->queryResult = & class_loader('DatabaseQueryResult', 'classes/database');
180
+        }
181
+        $this->queryResult->setResult($result);
182
+        $this->queryResult->setNumRows($numRows);
183 183
     }
184 184
 
185 185
     /**
186
-   * Return the result for non SELECT query
187
-   * @see DatabaseQueryRunner::execute
188
-   */
186
+     * Return the result for non SELECT query
187
+     * @see DatabaseQueryRunner::execute
188
+     */
189 189
     protected function setResultForNonSelect(){
190
-      //Sqlite and pgsql always return 0 when using rowCount()
191
-      $result = false;
192
-      $numRows = 0;
193
-      if (in_array($this->driver, array('sqlite', 'pgsql'))){
190
+        //Sqlite and pgsql always return 0 when using rowCount()
191
+        $result = false;
192
+        $numRows = 0;
193
+        if (in_array($this->driver, array('sqlite', 'pgsql'))){
194 194
         $result = true; //to test the result for the query like UPDATE, INSERT, DELETE
195 195
         $numRows = 1; //TODO use the correct method to get the exact affected row
196
-      }
197
-      else{
198
-          //to test the result for the query like UPDATE, INSERT, DELETE
199
-          $result  = $this->pdoStatment->rowCount() >= 0; 
200
-          $numRows = $this->pdoStatment->rowCount(); 
201
-      }
202
-      if(! is_object($this->queryResult)){
203
-          $this->queryResult = & class_loader('DatabaseQueryResult', 'classes/database');
204
-      }
205
-      $this->queryResult->setResult($result);
206
-      $this->queryResult->setNumRows($numRows);
196
+        }
197
+        else{
198
+            //to test the result for the query like UPDATE, INSERT, DELETE
199
+            $result  = $this->pdoStatment->rowCount() >= 0; 
200
+            $numRows = $this->pdoStatment->rowCount(); 
201
+        }
202
+        if(! is_object($this->queryResult)){
203
+            $this->queryResult = & class_loader('DatabaseQueryResult', 'classes/database');
204
+        }
205
+        $this->queryResult->setResult($result);
206
+        $this->queryResult->setNumRows($numRows);
207 207
     }
208 208
 
209 209
 
210
-	/**
210
+    /**
211 211
      * Return the benchmark instance
212 212
      * @return Benchmark
213 213
      */
214 214
     public function getBenchmark(){
215
-      return $this->benchmarkInstance;
215
+        return $this->benchmarkInstance;
216 216
     }
217 217
 
218 218
     /**
219 219
      * Set the benchmark instance
220 220
      * @param Benchmark $benchmark the benchmark object
221
-	 * @return object DatabaseQueryRunner
221
+     * @return object DatabaseQueryRunner
222 222
      */
223 223
     public function setBenchmark($benchmark){
224
-      $this->benchmarkInstance = $benchmark;
225
-      return $this;
224
+        $this->benchmarkInstance = $benchmark;
225
+        return $this;
226 226
     }
227 227
     
228 228
     /**
@@ -231,18 +231,18 @@  discard block
 block discarded – undo
231 231
      * @return object DatabaseQueryResult
232 232
      */
233 233
     public function getQueryResult(){
234
-      return $this->queryResult;
234
+        return $this->queryResult;
235 235
     }
236 236
 
237 237
     /**
238 238
      * Set the database query result instance
239 239
      * @param object $queryResult the query result
240 240
      *
241
-	 * @return object DatabaseQueryRunner
241
+     * @return object DatabaseQueryRunner
242 242
      */
243 243
     public function setQueryResult(DatabaseQueryResult $queryResult){
244
-      $this->queryResult = $queryResult;
245
-      return $this;
244
+        $this->queryResult = $queryResult;
245
+        return $this;
246 246
     }
247 247
     
248 248
     /**
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
      * @return string
251 251
      */
252 252
     public function getQuery(){
253
-      return $this->query;
253
+        return $this->query;
254 254
     }
255 255
     
256 256
     /**
@@ -259,8 +259,8 @@  discard block
 block discarded – undo
259 259
      * @return object DatabaseQueryRunner
260 260
      */
261 261
     public function setQuery($query){
262
-       $this->query = $query;
263
-       return $this;
262
+        $this->query = $query;
263
+        return $this;
264 264
     }
265 265
     
266 266
     /**
@@ -269,8 +269,8 @@  discard block
 block discarded – undo
269 269
      * @return object DatabaseQueryRunner
270 270
      */
271 271
     public function setReturnType($returnType){
272
-       $this->returnAsList = $returnType;
273
-       return $this;
272
+        $this->returnAsList = $returnType;
273
+        return $this;
274 274
     }
275 275
     
276 276
     /**
@@ -279,8 +279,8 @@  discard block
 block discarded – undo
279 279
      * @return object DatabaseQueryRunner
280 280
      */
281 281
     public function setReturnAsArray($status = true){
282
-       $this->returnAsArray = $status;
283
-       return $this;
282
+        $this->returnAsArray = $status;
283
+        return $this;
284 284
     }
285 285
     
286 286
     /**
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
      * @return string
289 289
      */
290 290
     public function getQueryError(){
291
-      return $this->error;
291
+        return $this->error;
292 292
     }
293 293
 
294 294
     /**
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
      * @return object
297 297
      */
298 298
     public function getPdo(){
299
-      return $this->pdo;
299
+        return $this->pdo;
300 300
     }
301 301
 
302 302
     /**
@@ -305,16 +305,16 @@  discard block
 block discarded – undo
305 305
      * @return object DatabaseQueryRunner
306 306
      */
307 307
     public function setPdo(PDO $pdo = null){
308
-      $this->pdo = $pdo;
309
-      return $this;
308
+        $this->pdo = $pdo;
309
+        return $this;
310 310
     }
311 311
   
312
-     /**
313
-     * Return the database driver
314
-     * @return string
315
-     */
312
+        /**
313
+         * Return the database driver
314
+         * @return string
315
+         */
316 316
     public function getDriver(){
317
-      return $this->driver;
317
+        return $this->driver;
318 318
     }
319 319
 
320 320
     /**
@@ -323,8 +323,8 @@  discard block
 block discarded – undo
323 323
      * @return object DatabaseQueryRunner
324 324
      */
325 325
     public function setDriver($driver){
326
-      $this->driver = $driver;
327
-      return $this;
326
+        $this->driver = $driver;
327
+        return $this;
328 328
     }
329 329
     
330 330
     /**
@@ -333,18 +333,18 @@  discard block
 block discarded – undo
333 333
      *  @return string
334 334
      */
335 335
     protected function getBenchmarkKey(){
336
-      return md5($this->query . $this->returnAsList . $this->returnAsArray);
336
+        return md5($this->query . $this->returnAsList . $this->returnAsArray);
337 337
     }
338 338
     
339 339
     /**
340 340
      * Set error for database query execution
341 341
      */
342 342
     protected function setQueryRunnerError(){
343
-      $error = $this->pdo->errorInfo();
344
-      $this->error = isset($error[2]) ? $error[2] : '';
345
-      $this->logger->error('The database query execution got an error: ' . stringfy_vars($error));
346
-	  //show error message
347
-      show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
343
+        $error = $this->pdo->errorInfo();
344
+        $this->error = isset($error[2]) ? $error[2] : '';
345
+        $this->logger->error('The database query execution got an error: ' . stringfy_vars($error));
346
+        //show error message
347
+        show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
348 348
     }
349 349
     
350 350
     /**
@@ -352,19 +352,19 @@  discard block
 block discarded – undo
352 352
      * @param object $logger the Log instance if not null
353 353
      */
354 354
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
355
-      if ($logger !== null){
355
+        if ($logger !== null){
356 356
         $this->logger = $logger;
357
-      }
358
-      else{
359
-          $this->logger =& class_loader('Log', 'classes');
360
-          $this->logger->setLogger('Library::DatabaseQueryRunner');
361
-      }
357
+        }
358
+        else{
359
+            $this->logger =& class_loader('Log', 'classes');
360
+            $this->logger->setLogger('Library::DatabaseQueryRunner');
361
+        }
362 362
     }
363 363
     
364 364
     
365 365
     /**
366
-    * Reset the instance before run each query
367
-    */
366
+     * Reset the instance before run each query
367
+     */
368 368
     private function reset(){
369 369
         $this->error = null;
370 370
         $this->pdoStatment = null;
Please login to merge, or discard this patch.
core/classes/database/Database.php 1 patch
Indentation   +322 added lines, -322 removed lines patch added patch discarded remove patch
@@ -1,113 +1,113 @@  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 extends BaseClass{
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 extends BaseClass{
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 94
     /**
95
-    * The cache instance
96
-    * @var object
97
-    */
95
+     * The cache instance
96
+     * @var object
97
+     */
98 98
     private $cacheInstance       = null;
99 99
 
100 100
     
101
-  	/**
102
-    * The DatabaseQueryBuilder instance
103
-    * @var object
104
-    */
101
+        /**
102
+         * The DatabaseQueryBuilder instance
103
+         * @var object
104
+         */
105 105
     protected $queryBuilder        = null;
106 106
     
107 107
     /**
108
-    * The DatabaseQueryRunner instance
109
-    * @var object
110
-    */
108
+     * The DatabaseQueryRunner instance
109
+     * @var object
110
+     */
111 111
     protected $queryRunner         = null;
112 112
 
113 113
 
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     public function __construct($overwriteConfig = array(), $autoConnect = true){
120 120
         parent::__construct();
121 121
 		
122
-    		//Set DatabaseQueryBuilder instance to use
122
+            //Set DatabaseQueryBuilder instance to use
123 123
         $this->setDependencyInstanceFromParamOrCreate('queryBuilder', null, 'DatabaseQueryBuilder', 'classes/database');
124 124
        
125 125
         //Set DatabaseQueryRunner instance to use
@@ -137,8 +137,8 @@  discard block
 block discarded – undo
137 137
      * @return bool 
138 138
      */
139 139
     public function connect(){
140
-      $config = $this->getDatabaseConfiguration();
141
-      if (! empty($config)){
140
+        $config = $this->getDatabaseConfiguration();
141
+        if (! empty($config)){
142 142
         try{
143 143
             $this->pdo = new PDO($this->getDsnValueFromConfig(), $config['username'], $config['password']);
144 144
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
@@ -149,14 +149,14 @@  discard block
 block discarded – undo
149 149
             $this->updateQueryBuilderAndRunnerProperties();
150 150
 
151 151
             return is_object($this->pdo);
152
-          }
153
-          catch (PDOException $e){
152
+            }
153
+            catch (PDOException $e){
154 154
             $this->logger->fatal($e->getMessage());
155 155
             show_error('Cannot connect to Database.');
156 156
             return false;
157
-          }
158
-      }
159
-      return false;
157
+            }
158
+        }
159
+        return false;
160 160
     }
161 161
 
162 162
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
      * @return int
166 166
      */
167 167
     public function numRows(){
168
-      return $this->numRows;
168
+        return $this->numRows;
169 169
     }
170 170
 
171 171
     /**
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
      * @return mixed
174 174
      */
175 175
     public function insertId(){
176
-      return $this->insertId;
176
+        return $this->insertId;
177 177
     }
178 178
 
179 179
 
@@ -184,13 +184,13 @@  discard block
 block discarded – undo
184 184
      * @return mixed       the query SQL string or the record result
185 185
      */
186 186
     public function get($returnSQLQueryOrResultType = false){
187
-      $this->queryBuilder->limit(1);
188
-      $query = $this->getAll(true);
189
-      if ($returnSQLQueryOrResultType === true){
187
+        $this->queryBuilder->limit(1);
188
+        $query = $this->getAll(true);
189
+        if ($returnSQLQueryOrResultType === true){
190 190
         return $query;
191
-      } else {
191
+        } else {
192 192
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
193
-      }
193
+        }
194 194
     }
195 195
 
196 196
     /**
@@ -200,11 +200,11 @@  discard block
 block discarded – undo
200 200
      * @return mixed       the query SQL string or the record result
201 201
      */
202 202
     public function getAll($returnSQLQueryOrResultType = false){
203
-	   $query = $this->queryBuilder->getQuery();
204
-	   if ($returnSQLQueryOrResultType === true){
205
-      	return $query;
206
-      }
207
-      return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
203
+        $query = $this->queryBuilder->getQuery();
204
+        if ($returnSQLQueryOrResultType === true){
205
+            return $query;
206
+        }
207
+        return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
208 208
     }
209 209
 
210 210
     /**
@@ -214,19 +214,19 @@  discard block
 block discarded – undo
214 214
      * @return mixed          the insert id of the new record or null
215 215
      */
216 216
     public function insert($data = array(), $escape = true){
217
-      if (empty($data) && ! empty($this->data)){
217
+        if (empty($data) && ! empty($this->data)){
218 218
         //as when using $this->setData() may be the data already escaped
219 219
         $escape = false;
220 220
         $data = $this->data;
221
-      }
222
-      $query = $this->queryBuilder->insert($data, $escape)->getQuery();
223
-      $result = $this->query($query);
224
-      if ($result){
221
+        }
222
+        $query = $this->queryBuilder->insert($data, $escape)->getQuery();
223
+        $result = $this->query($query);
224
+        if ($result){
225 225
         $this->insertId = $this->pdo->lastInsertId();
226
-		    //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
226
+            //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
227 227
         return ! ($this->insertId) ? true : $this->insertId;
228
-      }
229
-      return false;
228
+        }
229
+        return false;
230 230
     }
231 231
 
232 232
     /**
@@ -236,13 +236,13 @@  discard block
 block discarded – undo
236 236
      * @return mixed          the update status
237 237
      */
238 238
     public function update($data = array(), $escape = true){
239
-      if (empty($data) && ! empty($this->data)){
239
+        if (empty($data) && ! empty($this->data)){
240 240
         //as when using $this->setData() may be the data already escaped
241 241
         $escape = false;
242 242
         $data = $this->data;
243
-      }
244
-      $query = $this->queryBuilder->update($data, $escape)->getQuery();
245
-      return $this->query($query);
243
+        }
244
+        $query = $this->queryBuilder->update($data, $escape)->getQuery();
245
+        return $this->query($query);
246 246
     }
247 247
 
248 248
     /**
@@ -250,8 +250,8 @@  discard block
 block discarded – undo
250 250
      * @return mixed the delete status
251 251
      */
252 252
     public function delete(){
253
-		  $query = $this->queryBuilder->delete()->getQuery();
254
-    	return $this->query($query);
253
+            $query = $this->queryBuilder->delete()->getQuery();
254
+        return $this->query($query);
255 255
     }
256 256
 
257 257
     /**
@@ -260,17 +260,17 @@  discard block
 block discarded – undo
260 260
      * @return object        the current Database instance
261 261
      */
262 262
     public function setCache($ttl = 0){
263
-      $this->cacheTtl = $ttl;
264
-      $this->temporaryCacheTtl = $ttl;
265
-      return $this;
263
+        $this->cacheTtl = $ttl;
264
+        $this->temporaryCacheTtl = $ttl;
265
+        return $this;
266 266
     }
267 267
 	
268
-	/**
269
-	 * Enabled cache temporary for the current query not globally	
270
-	 * @param  integer $ttl the cache time to live in second
271
-	 * @return object        the current Database instance
272
-	 */
273
-  	public function cached($ttl = 0){
268
+    /**
269
+     * Enabled cache temporary for the current query not globally	
270
+     * @param  integer $ttl the cache time to live in second
271
+     * @return object        the current Database instance
272
+     */
273
+        public function cached($ttl = 0){
274 274
         $this->temporaryCacheTtl = $ttl;
275 275
         return $this;
276 276
     }
@@ -283,11 +283,11 @@  discard block
 block discarded – undo
283 283
      * need escaped
284 284
      */
285 285
     public function escape($data, $escaped = true){
286
-      $data = trim($data);
287
-      if($escaped){
286
+        $data = trim($data);
287
+        if($escaped){
288 288
         return $this->pdo->quote($data);
289
-      }
290
-      return $data; 
289
+        }
290
+        return $data; 
291 291
     }
292 292
 
293 293
     /**
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
      * @return int
296 296
      */
297 297
     public function queryCount(){
298
-      return $this->queryCount;
298
+        return $this->queryCount;
299 299
     }
300 300
 
301 301
     /**
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
      * @return string
304 304
      */
305 305
     public function getQuery(){
306
-      return $this->query;
306
+        return $this->query;
307 307
     }
308 308
 
309 309
     /**
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
      * @return string
312 312
      */
313 313
     public function getDatabaseName(){
314
-      return $this->databaseName;
314
+        return $this->databaseName;
315 315
     }
316 316
 
317 317
     /**
@@ -319,44 +319,44 @@  discard block
 block discarded – undo
319 319
      * @return object
320 320
      */
321 321
     public function getPdo(){
322
-      return $this->pdo;
322
+        return $this->pdo;
323 323
     }
324 324
 
325 325
     /**
326 326
      * Set the PDO instance
327 327
      * @param object $pdo the pdo object
328
-	 * @return object Database
328
+     * @return object Database
329 329
      */
330 330
     public function setPdo(PDO $pdo){
331
-      $this->pdo = $pdo;
332
-      return $this;
331
+        $this->pdo = $pdo;
332
+        return $this;
333 333
     }
334 334
 
335
-     /**
336
-     * Return the cache instance
337
-     * @return CacheInterface
338
-     */
335
+        /**
336
+         * Return the cache instance
337
+         * @return CacheInterface
338
+         */
339 339
     public function getCacheInstance(){
340
-      return $this->cacheInstance;
340
+        return $this->cacheInstance;
341 341
     }
342 342
 
343 343
     /**
344 344
      * Set the cache instance
345 345
      * @param CacheInterface $cache the cache object
346
-	 * @return object Database
346
+     * @return object Database
347 347
      */
348 348
     public function setCacheInstance($cache){
349
-      $this->cacheInstance = $cache;
350
-      return $this;
349
+        $this->cacheInstance = $cache;
350
+        return $this;
351 351
     }
352 352
 	
353 353
 	
354
-	   /**
355
-     * Return the DatabaseQueryBuilder instance
356
-     * @return object DatabaseQueryBuilder
357
-     */
354
+        /**
355
+         * Return the DatabaseQueryBuilder instance
356
+         * @return object DatabaseQueryBuilder
357
+         */
358 358
     public function getQueryBuilder(){
359
-      return $this->queryBuilder;
359
+        return $this->queryBuilder;
360 360
     }
361 361
 
362 362
     /**
@@ -364,8 +364,8 @@  discard block
 block discarded – undo
364 364
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
365 365
      */
366 366
     public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
367
-      $this->queryBuilder = $queryBuilder;
368
-      return $this;
367
+        $this->queryBuilder = $queryBuilder;
368
+        return $this;
369 369
     }
370 370
     
371 371
     /**
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
      * @return object DatabaseQueryRunner
374 374
      */
375 375
     public function getQueryRunner(){
376
-      return $this->queryRunner;
376
+        return $this->queryRunner;
377 377
     }
378 378
 
379 379
     /**
@@ -381,8 +381,8 @@  discard block
 block discarded – undo
381 381
      * @param object DatabaseQueryRunner $queryRunner the DatabaseQueryRunner object
382 382
      */
383 383
     public function setQueryRunner(DatabaseQueryRunner $queryRunner){
384
-      $this->queryRunner = $queryRunner;
385
-      return $this;
384
+        $this->queryRunner = $queryRunner;
385
+        return $this;
386 386
     }
387 387
 
388 388
     /**
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
      * @return array
391 391
      */
392 392
     public function getData(){
393
-      return $this->data;
393
+        return $this->data;
394 394
     }
395 395
 
396 396
     /**
@@ -401,62 +401,62 @@  discard block
 block discarded – undo
401 401
      * @return object        the current Database instance
402 402
      */
403 403
     public function setData($key, $value = null, $escape = true){
404
-  	  if (is_array($key)){
405
-    		foreach($key as $k => $v){
406
-    			$this->setData($k, $v, $escape);
407
-    		}	
408
-  	  } else {
404
+        if (is_array($key)){
405
+            foreach($key as $k => $v){
406
+                $this->setData($k, $v, $escape);
407
+            }	
408
+        } else {
409 409
         $this->data[$key] = $this->escape($value, $escape);
410
-  	  }
411
-      return $this;
410
+        }
411
+        return $this;
412 412
     }
413 413
 
414
-     /**
415
-     * Execute an SQL query
416
-     * @param  string  $query the query SQL string
417
-     * @param  boolean $returnAsList  indicate whether to return all record or just one row 
418
-     * @param  boolean $returnAsArray return the result as array or not
419
-     * @return mixed         the query result
420
-     */
414
+        /**
415
+         * Execute an SQL query
416
+         * @param  string  $query the query SQL string
417
+         * @param  boolean $returnAsList  indicate whether to return all record or just one row 
418
+         * @param  boolean $returnAsArray return the result as array or not
419
+         * @return mixed         the query result
420
+         */
421 421
     public function query($query, $returnAsList = true, $returnAsArray = false){
422
-      $this->reset();
423
-      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
424
-      //If is the SELECT query
425
-      $isSqlSELECTQuery = stristr($this->query, 'SELECT');
422
+        $this->reset();
423
+        $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
424
+        //If is the SELECT query
425
+        $isSqlSELECTQuery = stristr($this->query, 'SELECT');
426 426
 
427
-      //cache expire time
428
-      $cacheExpire = $this->temporaryCacheTtl;
427
+        //cache expire time
428
+        $cacheExpire = $this->temporaryCacheTtl;
429 429
       
430
-      //return to the initial cache time
431
-      $this->temporaryCacheTtl = $this->cacheTtl;
430
+        //return to the initial cache time
431
+        $this->temporaryCacheTtl = $this->cacheTtl;
432 432
       
433
-      //config for cache
434
-      $cacheEnable = get_config('cache_enable');
433
+        //config for cache
434
+        $cacheEnable = get_config('cache_enable');
435 435
       
436
-      //the database cache content
437
-      $cacheContent = null;
436
+        //the database cache content
437
+        $cacheContent = null;
438 438
 
439
-      //if can use cache feature for this query
440
-      $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
439
+        //if can use cache feature for this query
440
+        $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
441 441
     
442
-      if ($dbCacheStatus && $isSqlSELECTQuery){
443
-          $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
444
-          $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
445
-      }
442
+        if ($dbCacheStatus && $isSqlSELECTQuery){
443
+            $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
444
+            $cacheContent = $this->getCacheContentForQuery($query, $returnAsList, $returnAsArray);  
445
+        }
446 446
       
447
-      if (!$cacheContent){
448
-  	   	//count the number of query execution to server
447
+        if (!$cacheContent){
448
+                //count the number of query execution to server
449 449
         $this->queryCount++;
450 450
         
451 451
         $queryResult = $this->queryRunner->setQuery($query)
452
-                                          ->setReturnType($returnAsList)
453
-                                          ->setReturnAsArray($returnAsArray)
454
-                                          ->execute();
452
+                                            ->setReturnType($returnAsList)
453
+                                            ->setReturnAsArray($returnAsArray)
454
+                                            ->execute();
455 455
 
456 456
         if (!is_object($queryResult)){
457
-          $this->result = false;
458
-          $this->numRows = 0;
459
-          return $this->result;
457
+            $this->result = false;
458
+            $this->numRows = 0;
459
+            return $this->result;
460 460
         }
461 461
         $this->result  = $queryResult->getResult();
462 462
         $this->numRows = $queryResult->getNumRows();
@@ -464,72 +464,72 @@  discard block
 block discarded – undo
464 464
             $key = $this->getCacheKeyForQuery($this->query, $returnAsList, $returnAsArray);
465 465
             $this->setCacheContentForQuery($this->query, $key, $this->result, $cacheExpire);
466 466
         }
467
-      } else if ($isSqlSELECTQuery){
468
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
469
-          $this->result = $cacheContent;
470
-          $this->numRows = count($this->result);
471
-      }
472
-      return $this->result;
473
-    }
474
-
475
-   /**
476
-    * Setting the database configuration using the configuration file and additional configuration from param
477
-    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
478
-    * @param boolean $useConfigFile whether to use database configuration file
479
-    * @param boolean $autoConnect whether to connect to database after set the configuration
480
-	  * @return object Database
481
-    */
467
+        } else if ($isSqlSELECTQuery){
468
+            $this->logger->info('The result for query [' .$this->query. '] already cached use it');
469
+            $this->result = $cacheContent;
470
+            $this->numRows = count($this->result);
471
+        }
472
+        return $this->result;
473
+    }
474
+
475
+    /**
476
+     * Setting the database configuration using the configuration file and additional configuration from param
477
+     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
478
+     * @param boolean $useConfigFile whether to use database configuration file
479
+     * @param boolean $autoConnect whether to connect to database after set the configuration
480
+     * @return object Database
481
+     */
482 482
     public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true, $autoConnect = false){
483
-      $db = array();
484
-      if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
485
-          //here don't use require_once because somewhere user can create database instance directly
486
-          require CONFIG_PATH . 'database.php';
487
-      }
483
+        $db = array();
484
+        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
485
+            //here don't use require_once because somewhere user can create database instance directly
486
+            require CONFIG_PATH . 'database.php';
487
+        }
488 488
       
489
-      //merge with the parameter  
490
-      $db = array_merge($db, $overwriteConfig);
489
+        //merge with the parameter  
490
+        $db = array_merge($db, $overwriteConfig);
491 491
       
492
-      //get the default configuration
493
-      $config = $this->getDatabaseDefaultConfiguration();
492
+        //get the default configuration
493
+        $config = $this->getDatabaseDefaultConfiguration();
494 494
 		  
495
-    	$config = array_merge($config, $db);
496
-    	//determine the port using the hostname like localhost:3307
497
-      //hostname will be "localhost", and port "3307"
498
-      $p = explode(':', $config['hostname']);
499
-  	  if (count($p) >= 2){
500
-  		  $config['hostname'] = $p[0];
501
-  		  $config['port'] = $p[1];
502
-  		}
495
+        $config = array_merge($config, $db);
496
+        //determine the port using the hostname like localhost:3307
497
+        //hostname will be "localhost", and port "3307"
498
+        $p = explode(':', $config['hostname']);
499
+        if (count($p) >= 2){
500
+            $config['hostname'] = $p[0];
501
+            $config['port'] = $p[1];
502
+            }
503 503
 		
504
-		 $this->databaseName = $config['database'];
505
-		 $this->config = $config;
506
-		 $this->logger->info(
507
-								'The database configuration are listed below: ' 
508
-								. stringfy_vars(array_merge(
509
-															$this->config, 
510
-															array('password' => string_hidden($this->config['password']))
511
-												))
512
-							);
513
-  	  if($autoConnect){
514
-    		 //Now connect to the database
515
-    		 $this->connect();
516
-  		}
517
-		 return $this;
518
-    }
519
-
520
-    /**
521
-   * Return the database configuration
522
-   * @return array
523
-   */
504
+            $this->databaseName = $config['database'];
505
+            $this->config = $config;
506
+            $this->logger->info(
507
+                                'The database configuration are listed below: ' 
508
+                                . stringfy_vars(array_merge(
509
+                                                            $this->config, 
510
+                                                            array('password' => string_hidden($this->config['password']))
511
+                                                ))
512
+                            );
513
+        if($autoConnect){
514
+                //Now connect to the database
515
+                $this->connect();
516
+            }
517
+            return $this;
518
+    }
519
+
520
+    /**
521
+     * Return the database configuration
522
+     * @return array
523
+     */
524 524
     public  function getDatabaseConfiguration(){
525
-      return $this->config;
525
+        return $this->config;
526 526
     }
527 527
 
528 528
     /**
529 529
      * Close the connexion
530 530
      */
531 531
     public function close(){
532
-      $this->pdo = null;
532
+        $this->pdo = null;
533 533
     }
534 534
 
535 535
     /**
@@ -537,16 +537,16 @@  discard block
 block discarded – undo
537 537
      * @return array
538 538
      */
539 539
     protected function getDatabaseDefaultConfiguration(){
540
-      return array(
541
-              'driver' => '',
542
-              'username' => '',
543
-              'password' => '',
544
-              'database' => '',
545
-              'hostname' => 'localhost',
546
-              'charset' => 'utf8',
547
-              'collation' => 'utf8_general_ci',
548
-              'prefix' => '',
549
-              'port' => ''
540
+        return array(
541
+                'driver' => '',
542
+                'username' => '',
543
+                'password' => '',
544
+                'database' => '',
545
+                'hostname' => 'localhost',
546
+                'charset' => 'utf8',
547
+                'collation' => 'utf8_general_ci',
548
+                'prefix' => '',
549
+                'port' => ''
550 550
             );
551 551
     }
552 552
 
@@ -555,18 +555,18 @@  discard block
 block discarded – undo
555 555
      * @return void
556 556
      */
557 557
     protected function updateQueryBuilderAndRunnerProperties(){
558
-       //update queryBuilder with some properties needed
559
-     if (is_object($this->queryBuilder)){
558
+        //update queryBuilder with some properties needed
559
+        if (is_object($this->queryBuilder)){
560 560
         $this->queryBuilder->setDriver($this->config['driver'])
561
-                           ->setPrefix($this->config['prefix'])
562
-                           ->setPdo($this->pdo);
563
-     }
561
+                            ->setPrefix($this->config['prefix'])
562
+                            ->setPdo($this->pdo);
563
+        }
564 564
 
565
-      //update queryRunner with some properties needed
566
-     if (is_object($this->queryRunner)){
565
+        //update queryRunner with some properties needed
566
+        if (is_object($this->queryRunner)){
567 567
         $this->queryRunner->setDriver($this->config['driver'])
568
-                          ->setPdo($this->pdo);
569
-     }
568
+                            ->setPdo($this->pdo);
569
+        }
570 570
     }
571 571
 	
572 572
 
@@ -575,21 +575,21 @@  discard block
 block discarded – undo
575 575
      * @return string|null the DSN string or null if can not find it
576 576
      */
577 577
     protected function getDsnValueFromConfig(){
578
-      $dsn = null;
579
-      $config = $this->getDatabaseConfiguration();
580
-      if (! empty($config)){
578
+        $dsn = null;
579
+        $config = $this->getDatabaseConfiguration();
580
+        if (! empty($config)){
581 581
         $driver = $config['driver'];
582 582
         $driverDsnMap = array(
583
-                              'mysql'  => $this->getDsnValueForDriver('mysql'),
584
-                              'pgsql'  => $this->getDsnValueForDriver('pgsql'),
585
-                              'sqlite' => $this->getDsnValueForDriver('sqlite'),
586
-                              'oracle' => $this->getDsnValueForDriver('oracle')
587
-                              );
583
+                                'mysql'  => $this->getDsnValueForDriver('mysql'),
584
+                                'pgsql'  => $this->getDsnValueForDriver('pgsql'),
585
+                                'sqlite' => $this->getDsnValueForDriver('sqlite'),
586
+                                'oracle' => $this->getDsnValueForDriver('oracle')
587
+                                );
588 588
         if (isset($driverDsnMap[$driver])){
589
-          $dsn = $driverDsnMap[$driver];
589
+            $dsn = $driverDsnMap[$driver];
590 590
         }
591
-      }    
592
-      return $dsn;
591
+        }    
592
+        return $dsn;
593 593
     }
594 594
 
595 595
     /**
@@ -598,32 +598,32 @@  discard block
 block discarded – undo
598 598
      * @return string|null         the dsn name
599 599
      */
600 600
     protected function getDsnValueForDriver($driver){
601
-      $dsn = '';
602
-      $config = $this->getDatabaseConfiguration();
603
-      if (empty($config)){
601
+        $dsn = '';
602
+        $config = $this->getDatabaseConfiguration();
603
+        if (empty($config)){
604 604
         return null;
605
-      }
606
-      switch ($driver) {
605
+        }
606
+        switch ($driver) {
607 607
         case 'mysql':
608 608
         case 'pgsql':
609 609
           $port = '';
610
-          if (! empty($config['port'])) {
610
+            if (! empty($config['port'])) {
611 611
             $port = 'port=' . $config['port'] . ';';
612
-          }
613
-          $dsn = $driver . ':host=' . $config['hostname'] . ';' . $port . 'dbname=' . $config['database'];
614
-          break;
612
+            }
613
+            $dsn = $driver . ':host=' . $config['hostname'] . ';' . $port . 'dbname=' . $config['database'];
614
+            break;
615 615
         case 'sqlite':
616 616
           $dsn = 'sqlite:' . $config['database'];
617
-          break;
618
-          case 'oracle':
617
+            break;
618
+            case 'oracle':
619 619
           $port = '';
620
-          if (! empty($config['port'])) {
620
+            if (! empty($config['port'])) {
621 621
             $port = ':' . $config['port'];
622
-          }
623
-          $dsn =  'oci:dbname=' . $config['hostname'] . $port . '/' . $config['database'];
624
-          break;
625
-      }
626
-      return $dsn;
622
+            }
623
+            $dsn =  'oci:dbname=' . $config['hostname'] . $port . '/' . $config['database'];
624
+            break;
625
+        }
626
+        return $dsn;
627 627
     }
628 628
 
629 629
     /**
@@ -635,11 +635,11 @@  discard block
 block discarded – undo
635 635
     protected function getCacheContentForQuery($query, $returnAsList, $returnAsArray){
636 636
         $cacheKey = $this->getCacheKeyForQuery($query, $returnAsList, $returnAsArray);
637 637
         if (! is_object($this->cacheInstance)){
638
-    			//can not call method with reference in argument
639
-    			//like $this->setCacheInstance(& get_instance()->cache);
640
-    			//use temporary variable
641
-    			$instance = & get_instance()->cache;
642
-    			$this->cacheInstance = $instance;
638
+                //can not call method with reference in argument
639
+                //like $this->setCacheInstance(& get_instance()->cache);
640
+                //use temporary variable
641
+                $instance = & get_instance()->cache;
642
+                $this->cacheInstance = $instance;
643 643
         }
644 644
         return $this->cacheInstance->get($cacheKey);
645 645
     }
@@ -651,27 +651,27 @@  discard block
 block discarded – undo
651 651
      * @param mixed $result the query result to save
652 652
      * @param int $expire the cache TTL
653 653
      */
654
-     protected function setCacheContentForQuery($query, $key, $result, $expire){
654
+        protected function setCacheContentForQuery($query, $key, $result, $expire){
655 655
         $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
656 656
         if (! is_object($this->cacheInstance)){
657
-  				//can not call method with reference in argument
658
-  				//like $this->setCacheInstance(& get_instance()->cache);
659
-  				//use temporary variable
660
-  				$instance = & get_instance()->cache;
661
-  				$this->cacheInstance = $instance;
662
-  			}
657
+                    //can not call method with reference in argument
658
+                    //like $this->setCacheInstance(& get_instance()->cache);
659
+                    //use temporary variable
660
+                    $instance = & get_instance()->cache;
661
+                    $this->cacheInstance = $instance;
662
+                }
663 663
         $this->cacheInstance->set($key, $result, $expire);
664
-     }
664
+        }
665 665
 
666 666
     
667
-	 /**
668
-     * Return the cache key for the given query
669
-     * @see Database::query
670
-     * 
671
-     *  @return string
672
-     */
667
+        /**
668
+         * Return the cache key for the given query
669
+         * @see Database::query
670
+         * 
671
+         *  @return string
672
+         */
673 673
     protected function getCacheKeyForQuery($query, $returnAsList, $returnAsArray){
674
-      return md5($query . $returnAsList . $returnAsArray);
674
+        return md5($query . $returnAsList . $returnAsArray);
675 675
     }
676 676
 
677 677
 	
@@ -679,20 +679,20 @@  discard block
 block discarded – undo
679 679
      * Reset the database class attributs to the initail values before each query.
680 680
      */
681 681
     private function reset(){
682
-	   //query builder reset
683
-      $this->queryBuilder->reset();
684
-      $this->numRows  = 0;
685
-      $this->insertId = null;
686
-      $this->query    = null;
687
-      $this->result   = array();
688
-      $this->data     = array();
682
+        //query builder reset
683
+        $this->queryBuilder->reset();
684
+        $this->numRows  = 0;
685
+        $this->insertId = null;
686
+        $this->query    = null;
687
+        $this->result   = array();
688
+        $this->data     = array();
689 689
     }
690 690
 
691 691
     /**
692 692
      * The class destructor
693 693
      */
694 694
     public function __destruct(){
695
-      $this->pdo = null;
695
+        $this->pdo = null;
696 696
     }
697 697
 
698 698
 }
Please login to merge, or discard this patch.