Passed
Push — 1.0.0-dev ( 407604...83bedf )
by nguereza
03:26
created
core/classes/EventDispatcher.php 3 patches
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
 	 * also to dispatch the event
30 30
 	 */
31 31
 	
32
-	class EventDispatcher{
32
+	class EventDispatcher {
33 33
 		
34 34
 		/**
35 35
 		 * The list of the registered listeners
@@ -44,8 +44,8 @@  discard block
 block discarded – undo
44 44
 		 */
45 45
 		private $logger;
46 46
 
47
-		public function __construct(){
48
-			$this->logger =& class_loader('Log', 'classes');
47
+		public function __construct() {
48
+			$this->logger = & class_loader('Log', 'classes');
49 49
 			$this->logger->setLogger('Library::EventDispatcher');
50 50
 		}
51 51
 
@@ -54,13 +54,13 @@  discard block
 block discarded – undo
54 54
 		 * @param string   $eventName the name of the event to register for
55 55
 		 * @param callable $listener  the function or class method to receive the event information after dispatch
56 56
 		 */
57
-		public function addListener($eventName, callable $listener){
58
-			$this->logger->debug('Adding new event listener for the event name [' .$eventName. '], listener [' .stringfy_vars($listener). ']');
59
-			if(! isset($this->listeners[$eventName])){
57
+		public function addListener($eventName, callable $listener) {
58
+			$this->logger->debug('Adding new event listener for the event name [' . $eventName . '], listener [' . stringfy_vars($listener) . ']');
59
+			if (!isset($this->listeners[$eventName])) {
60 60
 				$this->logger->info('This event does not have the registered event listener before, adding new one');
61 61
 				$this->listeners[$eventName] = array();
62 62
 			}
63
-			else{
63
+			else {
64 64
 				$this->logger->info('This event already have the registered listener, add this listener to the list');
65 65
 			}
66 66
 			$this->listeners[$eventName][] = $listener;
@@ -71,19 +71,19 @@  discard block
 block discarded – undo
71 71
 		 * @param  string   $eventName the event name
72 72
 		 * @param  callable $listener  the listener callback
73 73
 		 */
74
-		public function removeListener($eventName, callable $listener){
75
-			$this->logger->debug('Removing of the event listener, the event name [' .$eventName. '], listener [' .stringfy_vars($listener). ']');
76
-			if(isset($this->listeners[$eventName])){
74
+		public function removeListener($eventName, callable $listener) {
75
+			$this->logger->debug('Removing of the event listener, the event name [' . $eventName . '], listener [' . stringfy_vars($listener) . ']');
76
+			if (isset($this->listeners[$eventName])) {
77 77
 				$this->logger->info('This event have the listeners, check if this listener exists');
78
-				if(false !== $index = array_search($listener, $this->listeners[$eventName], true)){
79
-					$this->logger->info('Found the listener at index [' .$index. '] remove it');
78
+				if (false !== $index = array_search($listener, $this->listeners[$eventName], true)) {
79
+					$this->logger->info('Found the listener at index [' . $index . '] remove it');
80 80
 					unset($this->listeners[$eventName][$index]);
81 81
 				}
82
-				else{
82
+				else {
83 83
 					$this->logger->info('Cannot found this listener in the event listener list');
84 84
 				}
85 85
 			}
86
-			else{
86
+			else {
87 87
 				$this->logger->info('This event does not have this listener ignore remove');
88 88
 			}
89 89
 		}
@@ -93,13 +93,13 @@  discard block
 block discarded – undo
93 93
 		 * remove all listeners for this event
94 94
 		 * @param  string $eventName the event name
95 95
 		 */
96
-		public function removeAllListener($eventName = null){
97
-			$this->logger->debug('Removing of all event listener, the event name [' .$eventName. ']');
98
-			if($eventName !== null && isset($this->listeners[$eventName])){
96
+		public function removeAllListener($eventName = null) {
97
+			$this->logger->debug('Removing of all event listener, the event name [' . $eventName . ']');
98
+			if ($eventName !== null && isset($this->listeners[$eventName])) {
99 99
 				$this->logger->info('The event name is set of exist in the listener just remove all event listener for this event');
100 100
 				unset($this->listeners[$eventName]);
101 101
 			}
102
-			else{
102
+			else {
103 103
 				$this->logger->info('The event name is not set or does not exist in the listener, so remove all event listener');
104 104
 				$this->listeners = array();
105 105
 			}
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 		 * @param string $eventName the event name
111 111
 		 * @return array the listeners for this event or empty array if this event does not contain any listener
112 112
 		 */
113
-		public function getListeners($eventName){
113
+		public function getListeners($eventName) {
114 114
 			return isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : array();
115 115
 		}
116 116
 		
@@ -119,21 +119,21 @@  discard block
 block discarded – undo
119 119
 		 * @param  mixed|object $event the event information
120 120
 		 * @return void|object if event need return, will return the final EventInfo object.
121 121
 		 */	
122
-		public function dispatch($event){
123
-			if(! $event || !$event instanceof EventInfo){
122
+		public function dispatch($event) {
123
+			if (!$event || !$event instanceof EventInfo) {
124 124
 				$this->logger->info('The event is not set or is not an instance of "EventInfo" create the default "EventInfo" object to use instead of.');
125 125
 				$event = new EventInfo((string) $event);
126 126
 			}			
127
-			$this->logger->debug('Dispatch to the event listener, the event [' .stringfy_vars($event). ']');
128
-			if(isset($event->stop) && $event->stop){
127
+			$this->logger->debug('Dispatch to the event listener, the event [' . stringfy_vars($event) . ']');
128
+			if (isset($event->stop) && $event->stop) {
129 129
 				$this->logger->info('This event need stopped, no need call any listener');
130 130
 				return;
131 131
 			}
132
-			if($event->returnBack){
132
+			if ($event->returnBack) {
133 133
 				$this->logger->info('This event need return back, return the result for future use');
134 134
 				return $this->dispatchToListerners($event);
135 135
 			}
136
-			else{
136
+			else {
137 137
 				$this->logger->info('This event no need return back the result, just dispatch it');
138 138
 				$this->dispatchToListerners($event);
139 139
 			}
@@ -144,38 +144,38 @@  discard block
 block discarded – undo
144 144
 		 * @param  object EventInfo $event  the event information
145 145
 		 * @return void|object if event need return, will return the final EventInfo instance.
146 146
 		 */	
147
-		private function dispatchToListerners(EventInfo $event){
147
+		private function dispatchToListerners(EventInfo $event) {
148 148
 			$eBackup = $event;
149 149
 			$list = $this->getListeners($event->name);
150
-			if(empty($list)){
151
-				$this->logger->info('No event listener is registered for the event [' .$event->name. '] skipping.');
152
-				if($event->returnBack){
150
+			if (empty($list)) {
151
+				$this->logger->info('No event listener is registered for the event [' . $event->name . '] skipping.');
152
+				if ($event->returnBack) {
153 153
 					return $event;
154 154
 				}
155 155
 				return;
156 156
 			}
157
-			else{
158
-				$this->logger->info('Found the registered event listener for the event [' .$event->name. '] the list are: ' . stringfy_vars($list));
157
+			else {
158
+				$this->logger->info('Found the registered event listener for the event [' . $event->name . '] the list are: ' . stringfy_vars($list));
159 159
 			}
160
-			foreach($list as $listener){
161
-				if($eBackup->returnBack){
160
+			foreach ($list as $listener) {
161
+				if ($eBackup->returnBack) {
162 162
 					$returnedEvent = call_user_func_array($listener, array($event));
163
-					if($returnedEvent instanceof EventInfo){
163
+					if ($returnedEvent instanceof EventInfo) {
164 164
 						$event = $returnedEvent;
165 165
 					}
166
-					else{
167
-						show_error('This event [' .$event->name. '] need you return the event object after processing');
166
+					else {
167
+						show_error('This event [' . $event->name . '] need you return the event object after processing');
168 168
 					}
169 169
 				}
170
-				else{
170
+				else {
171 171
 					call_user_func_array($listener, array($event));
172 172
 				}
173
-				if($event->stop){
173
+				if ($event->stop) {
174 174
 					break;
175 175
 				}
176 176
 			}
177 177
 			//only test for original event may be during the flow some listeners change this parameter
178
-			if($eBackup->returnBack){
178
+			if ($eBackup->returnBack) {
179 179
 				return $event;
180 180
 			}
181 181
 		}
Please login to merge, or discard this patch.
Braces   +8 added lines, -16 removed lines patch added patch discarded remove patch
@@ -59,8 +59,7 @@  discard block
 block discarded – undo
59 59
 			if(! isset($this->listeners[$eventName])){
60 60
 				$this->logger->info('This event does not have the registered event listener before, adding new one');
61 61
 				$this->listeners[$eventName] = array();
62
-			}
63
-			else{
62
+			} else{
64 63
 				$this->logger->info('This event already have the registered listener, add this listener to the list');
65 64
 			}
66 65
 			$this->listeners[$eventName][] = $listener;
@@ -78,12 +77,10 @@  discard block
 block discarded – undo
78 77
 				if(false !== $index = array_search($listener, $this->listeners[$eventName], true)){
79 78
 					$this->logger->info('Found the listener at index [' .$index. '] remove it');
80 79
 					unset($this->listeners[$eventName][$index]);
81
-				}
82
-				else{
80
+				} else{
83 81
 					$this->logger->info('Cannot found this listener in the event listener list');
84 82
 				}
85
-			}
86
-			else{
83
+			} else{
87 84
 				$this->logger->info('This event does not have this listener ignore remove');
88 85
 			}
89 86
 		}
@@ -98,8 +95,7 @@  discard block
 block discarded – undo
98 95
 			if($eventName !== null && isset($this->listeners[$eventName])){
99 96
 				$this->logger->info('The event name is set of exist in the listener just remove all event listener for this event');
100 97
 				unset($this->listeners[$eventName]);
101
-			}
102
-			else{
98
+			} else{
103 99
 				$this->logger->info('The event name is not set or does not exist in the listener, so remove all event listener');
104 100
 				$this->listeners = array();
105 101
 			}
@@ -132,8 +128,7 @@  discard block
 block discarded – undo
132 128
 			if($event->returnBack){
133 129
 				$this->logger->info('This event need return back, return the result for future use');
134 130
 				return $this->dispatchToListerners($event);
135
-			}
136
-			else{
131
+			} else{
137 132
 				$this->logger->info('This event no need return back the result, just dispatch it');
138 133
 				$this->dispatchToListerners($event);
139 134
 			}
@@ -153,8 +148,7 @@  discard block
 block discarded – undo
153 148
 					return $event;
154 149
 				}
155 150
 				return;
156
-			}
157
-			else{
151
+			} else{
158 152
 				$this->logger->info('Found the registered event listener for the event [' .$event->name. '] the list are: ' . stringfy_vars($list));
159 153
 			}
160 154
 			foreach($list as $listener){
@@ -162,12 +156,10 @@  discard block
 block discarded – undo
162 156
 					$returnedEvent = call_user_func_array($listener, array($event));
163 157
 					if($returnedEvent instanceof EventInfo){
164 158
 						$event = $returnedEvent;
165
-					}
166
-					else{
159
+					} else{
167 160
 						show_error('This event [' .$event->name. '] need you return the event object after processing');
168 161
 					}
169
-				}
170
-				else{
162
+				} else{
171 163
 					call_user_func_array($listener, array($event));
172 164
 				}
173 165
 				if($event->stop){
Please login to merge, or discard this patch.
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -1,182 +1,182 @@
 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
-	 * This class represent the event dispatcher management, permit to record the listener and 
29
-	 * also to dispatch the event
30
-	 */
27
+    /**
28
+     * This class represent the event dispatcher management, permit to record the listener and 
29
+     * also to dispatch the event
30
+     */
31 31
 	
32
-	class EventDispatcher{
32
+    class EventDispatcher{
33 33
 		
34
-		/**
35
-		 * The list of the registered listeners
36
-		 * @var array
37
-		 */
38
-		private $listeners = array();
34
+        /**
35
+         * The list of the registered listeners
36
+         * @var array
37
+         */
38
+        private $listeners = array();
39 39
 		
40 40
 
41
-		/**
42
-		 * The logger instance
43
-		 * @var Log
44
-		 */
45
-		private $logger;
41
+        /**
42
+         * The logger instance
43
+         * @var Log
44
+         */
45
+        private $logger;
46 46
 
47
-		public function __construct(){
48
-			$this->logger =& class_loader('Log', 'classes');
49
-			$this->logger->setLogger('Library::EventDispatcher');
50
-		}
47
+        public function __construct(){
48
+            $this->logger =& class_loader('Log', 'classes');
49
+            $this->logger->setLogger('Library::EventDispatcher');
50
+        }
51 51
 
52
-		/**
53
-		 * Register new listener
54
-		 * @param string   $eventName the name of the event to register for
55
-		 * @param callable $listener  the function or class method to receive the event information after dispatch
56
-		 */
57
-		public function addListener($eventName, callable $listener){
58
-			$this->logger->debug('Adding new event listener for the event name [' .$eventName. '], listener [' .stringfy_vars($listener). ']');
59
-			if(! isset($this->listeners[$eventName])){
60
-				$this->logger->info('This event does not have the registered event listener before, adding new one');
61
-				$this->listeners[$eventName] = array();
62
-			}
63
-			else{
64
-				$this->logger->info('This event already have the registered listener, add this listener to the list');
65
-			}
66
-			$this->listeners[$eventName][] = $listener;
67
-		}
52
+        /**
53
+         * Register new listener
54
+         * @param string   $eventName the name of the event to register for
55
+         * @param callable $listener  the function or class method to receive the event information after dispatch
56
+         */
57
+        public function addListener($eventName, callable $listener){
58
+            $this->logger->debug('Adding new event listener for the event name [' .$eventName. '], listener [' .stringfy_vars($listener). ']');
59
+            if(! isset($this->listeners[$eventName])){
60
+                $this->logger->info('This event does not have the registered event listener before, adding new one');
61
+                $this->listeners[$eventName] = array();
62
+            }
63
+            else{
64
+                $this->logger->info('This event already have the registered listener, add this listener to the list');
65
+            }
66
+            $this->listeners[$eventName][] = $listener;
67
+        }
68 68
 		
69
-		/**
70
-		 * Remove the event listener from list
71
-		 * @param  string   $eventName the event name
72
-		 * @param  callable $listener  the listener callback
73
-		 */
74
-		public function removeListener($eventName, callable $listener){
75
-			$this->logger->debug('Removing of the event listener, the event name [' .$eventName. '], listener [' .stringfy_vars($listener). ']');
76
-			if(isset($this->listeners[$eventName])){
77
-				$this->logger->info('This event have the listeners, check if this listener exists');
78
-				if(false !== $index = array_search($listener, $this->listeners[$eventName], true)){
79
-					$this->logger->info('Found the listener at index [' .$index. '] remove it');
80
-					unset($this->listeners[$eventName][$index]);
81
-				}
82
-				else{
83
-					$this->logger->info('Cannot found this listener in the event listener list');
84
-				}
85
-			}
86
-			else{
87
-				$this->logger->info('This event does not have this listener ignore remove');
88
-			}
89
-		}
69
+        /**
70
+         * Remove the event listener from list
71
+         * @param  string   $eventName the event name
72
+         * @param  callable $listener  the listener callback
73
+         */
74
+        public function removeListener($eventName, callable $listener){
75
+            $this->logger->debug('Removing of the event listener, the event name [' .$eventName. '], listener [' .stringfy_vars($listener). ']');
76
+            if(isset($this->listeners[$eventName])){
77
+                $this->logger->info('This event have the listeners, check if this listener exists');
78
+                if(false !== $index = array_search($listener, $this->listeners[$eventName], true)){
79
+                    $this->logger->info('Found the listener at index [' .$index. '] remove it');
80
+                    unset($this->listeners[$eventName][$index]);
81
+                }
82
+                else{
83
+                    $this->logger->info('Cannot found this listener in the event listener list');
84
+                }
85
+            }
86
+            else{
87
+                $this->logger->info('This event does not have this listener ignore remove');
88
+            }
89
+        }
90 90
 		
91
-		/**
92
-		 * Remove all the event listener. If event name is null will remove all listeners, else will just 
93
-		 * remove all listeners for this event
94
-		 * @param  string $eventName the event name
95
-		 */
96
-		public function removeAllListener($eventName = null){
97
-			$this->logger->debug('Removing of all event listener, the event name [' .$eventName. ']');
98
-			if($eventName !== null && isset($this->listeners[$eventName])){
99
-				$this->logger->info('The event name is set of exist in the listener just remove all event listener for this event');
100
-				unset($this->listeners[$eventName]);
101
-			}
102
-			else{
103
-				$this->logger->info('The event name is not set or does not exist in the listener, so remove all event listener');
104
-				$this->listeners = array();
105
-			}
106
-		}
91
+        /**
92
+         * Remove all the event listener. If event name is null will remove all listeners, else will just 
93
+         * remove all listeners for this event
94
+         * @param  string $eventName the event name
95
+         */
96
+        public function removeAllListener($eventName = null){
97
+            $this->logger->debug('Removing of all event listener, the event name [' .$eventName. ']');
98
+            if($eventName !== null && isset($this->listeners[$eventName])){
99
+                $this->logger->info('The event name is set of exist in the listener just remove all event listener for this event');
100
+                unset($this->listeners[$eventName]);
101
+            }
102
+            else{
103
+                $this->logger->info('The event name is not set or does not exist in the listener, so remove all event listener');
104
+                $this->listeners = array();
105
+            }
106
+        }
107 107
 		
108
-		/**
109
-		 * Get the list of listener for this event
110
-		 * @param string $eventName the event name
111
-		 * @return array the listeners for this event or empty array if this event does not contain any listener
112
-		 */
113
-		public function getListeners($eventName){
114
-			return isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : array();
115
-		}
108
+        /**
109
+         * Get the list of listener for this event
110
+         * @param string $eventName the event name
111
+         * @return array the listeners for this event or empty array if this event does not contain any listener
112
+         */
113
+        public function getListeners($eventName){
114
+            return isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : array();
115
+        }
116 116
 		
117
-		/**
118
-		 * Dispatch the event to the registered listeners.
119
-		 * @param  mixed|object $event the event information
120
-		 * @return void|object if event need return, will return the final EventInfo object.
121
-		 */	
122
-		public function dispatch($event){
123
-			if(! $event || !$event instanceof EventInfo){
124
-				$this->logger->info('The event is not set or is not an instance of "EventInfo" create the default "EventInfo" object to use instead of.');
125
-				$event = new EventInfo((string) $event);
126
-			}			
127
-			$this->logger->debug('Dispatch to the event listener, the event [' .stringfy_vars($event). ']');
128
-			if(isset($event->stop) && $event->stop){
129
-				$this->logger->info('This event need stopped, no need call any listener');
130
-				return;
131
-			}
132
-			if($event->returnBack){
133
-				$this->logger->info('This event need return back, return the result for future use');
134
-				return $this->dispatchToListerners($event);
135
-			}
136
-			else{
137
-				$this->logger->info('This event no need return back the result, just dispatch it');
138
-				$this->dispatchToListerners($event);
139
-			}
140
-		}
117
+        /**
118
+         * Dispatch the event to the registered listeners.
119
+         * @param  mixed|object $event the event information
120
+         * @return void|object if event need return, will return the final EventInfo object.
121
+         */	
122
+        public function dispatch($event){
123
+            if(! $event || !$event instanceof EventInfo){
124
+                $this->logger->info('The event is not set or is not an instance of "EventInfo" create the default "EventInfo" object to use instead of.');
125
+                $event = new EventInfo((string) $event);
126
+            }			
127
+            $this->logger->debug('Dispatch to the event listener, the event [' .stringfy_vars($event). ']');
128
+            if(isset($event->stop) && $event->stop){
129
+                $this->logger->info('This event need stopped, no need call any listener');
130
+                return;
131
+            }
132
+            if($event->returnBack){
133
+                $this->logger->info('This event need return back, return the result for future use');
134
+                return $this->dispatchToListerners($event);
135
+            }
136
+            else{
137
+                $this->logger->info('This event no need return back the result, just dispatch it');
138
+                $this->dispatchToListerners($event);
139
+            }
140
+        }
141 141
 		
142
-		/**
143
-		 * Dispatch the event to the registered listeners.
144
-		 * @param  object EventInfo $event  the event information
145
-		 * @return void|object if event need return, will return the final EventInfo instance.
146
-		 */	
147
-		private function dispatchToListerners(EventInfo $event){
148
-			$eBackup = $event;
149
-			$list = $this->getListeners($event->name);
150
-			if(empty($list)){
151
-				$this->logger->info('No event listener is registered for the event [' .$event->name. '] skipping.');
152
-				if($event->returnBack){
153
-					return $event;
154
-				}
155
-				return;
156
-			}
157
-			else{
158
-				$this->logger->info('Found the registered event listener for the event [' .$event->name. '] the list are: ' . stringfy_vars($list));
159
-			}
160
-			foreach($list as $listener){
161
-				if($eBackup->returnBack){
162
-					$returnedEvent = call_user_func_array($listener, array($event));
163
-					if($returnedEvent instanceof EventInfo){
164
-						$event = $returnedEvent;
165
-					}
166
-					else{
167
-						show_error('This event [' .$event->name. '] need you return the event object after processing');
168
-					}
169
-				}
170
-				else{
171
-					call_user_func_array($listener, array($event));
172
-				}
173
-				if($event->stop){
174
-					break;
175
-				}
176
-			}
177
-			//only test for original event may be during the flow some listeners change this parameter
178
-			if($eBackup->returnBack){
179
-				return $event;
180
-			}
181
-		}
182
-	}
142
+        /**
143
+         * Dispatch the event to the registered listeners.
144
+         * @param  object EventInfo $event  the event information
145
+         * @return void|object if event need return, will return the final EventInfo instance.
146
+         */	
147
+        private function dispatchToListerners(EventInfo $event){
148
+            $eBackup = $event;
149
+            $list = $this->getListeners($event->name);
150
+            if(empty($list)){
151
+                $this->logger->info('No event listener is registered for the event [' .$event->name. '] skipping.');
152
+                if($event->returnBack){
153
+                    return $event;
154
+                }
155
+                return;
156
+            }
157
+            else{
158
+                $this->logger->info('Found the registered event listener for the event [' .$event->name. '] the list are: ' . stringfy_vars($list));
159
+            }
160
+            foreach($list as $listener){
161
+                if($eBackup->returnBack){
162
+                    $returnedEvent = call_user_func_array($listener, array($event));
163
+                    if($returnedEvent instanceof EventInfo){
164
+                        $event = $returnedEvent;
165
+                    }
166
+                    else{
167
+                        show_error('This event [' .$event->name. '] need you return the event object after processing');
168
+                    }
169
+                }
170
+                else{
171
+                    call_user_func_array($listener, array($event));
172
+                }
173
+                if($event->stop){
174
+                    break;
175
+                }
176
+            }
177
+            //only test for original event may be during the flow some listeners change this parameter
178
+            if($eBackup->returnBack){
179
+                return $event;
180
+            }
181
+        }
182
+    }
Please login to merge, or discard this patch.
core/classes/Controller.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -115,8 +115,7 @@
 block discarded – undo
115 115
 		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116 116
 			if($logger !== null){
117 117
 	          $this->logger = $logger;
118
-	        }
119
-	        else{
118
+	        } else{
120 119
 	            $this->logger =& class_loader('Log', 'classes');
121 120
 				$this->logger->setLogger('MainController');
122 121
 	        }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Controller{
27
+	class Controller {
28 28
 		
29 29
 		/**
30 30
 		 * The name of the module if this controller belong to an module
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 		 * Class constructor
49 49
 		 * @param object $logger the Log instance to use if is null will create one
50 50
 		 */
51
-		public function __construct(Log $logger = null){
51
+		public function __construct(Log $logger = null) {
52 52
 			//setting the Log instance
53 53
 			$this->setLoggerFromParamOrCreateNewInstance($logger);
54 54
 			
@@ -84,9 +84,9 @@  discard block
 block discarded – undo
84 84
 		/**
85 85
 		 * This method is used to set the module name
86 86
 		 */
87
-		protected function setModuleNameFromRouter(){
87
+		protected function setModuleNameFromRouter() {
88 88
 			//determine the current module
89
-			if(isset($this->router) && $this->router->getModule()){
89
+			if (isset($this->router) && $this->router->getModule()) {
90 90
 				$this->moduleName = $this->router->getModule();
91 91
 			}
92 92
 		}
@@ -95,13 +95,13 @@  discard block
 block discarded – undo
95 95
 		 * Set the cache using the argument otherwise will use the configuration
96 96
 		 * @param CacheInterface $cache the implementation of CacheInterface if null will use the configured
97 97
 		 */
98
-		protected function setCacheFromParamOrConfig(CacheInterface $cache = null){
98
+		protected function setCacheFromParamOrConfig(CacheInterface $cache = null) {
99 99
 			$this->logger->debug('Setting the cache handler instance');
100 100
 			//set cache handler instance
101
-			if(get_config('cache_enable', false)){
102
-				if ($cache !== null){
101
+			if (get_config('cache_enable', false)) {
102
+				if ($cache !== null) {
103 103
 					$this->cache = $cache;
104
-				} else if (isset($this->{strtolower(get_config('cache_handler'))})){
104
+				} else if (isset($this->{strtolower(get_config('cache_handler'))})) {
105 105
 					$this->cache = $this->{strtolower(get_config('cache_handler'))};
106 106
 					unset($this->{strtolower(get_config('cache_handler'))});
107 107
 				} 
@@ -112,12 +112,12 @@  discard block
 block discarded – undo
112 112
 		 * Set the Log instance using argument or create new instance
113 113
 		 * @param object $logger the Log instance if not null
114 114
 		 */
115
-		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116
-			if($logger !== null){
115
+		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
116
+			if ($logger !== null) {
117 117
 	          $this->logger = $logger;
118 118
 	        }
119
-	        else{
120
-	            $this->logger =& class_loader('Log', 'classes');
119
+	        else {
120
+	            $this->logger = & class_loader('Log', 'classes');
121 121
 				$this->logger->setLogger('MainController');
122 122
 	        }
123 123
 		}
@@ -126,20 +126,20 @@  discard block
 block discarded – undo
126 126
 		 * This method is used to load the required resources for framework to work
127 127
 		 * @return void 
128 128
 		 */
129
-		private function loadRequiredResources(){
129
+		private function loadRequiredResources() {
130 130
 			$this->logger->debug('Adding the loaded classes to the super instance');
131
-			foreach (class_loaded() as $var => $class){
132
-				$this->$var =& class_loader($class);
131
+			foreach (class_loaded() as $var => $class) {
132
+				$this->$var = & class_loader($class);
133 133
 			}
134 134
 
135 135
 			$this->logger->debug('Loading the required classes into super instance');
136
-			$this->eventdispatcher =& class_loader('EventDispatcher', 'classes');
137
-			$this->loader =& class_loader('Loader', 'classes');
138
-			$this->lang =& class_loader('Lang', 'classes');
139
-			$this->request =& class_loader('Request', 'classes');
136
+			$this->eventdispatcher = & class_loader('EventDispatcher', 'classes');
137
+			$this->loader = & class_loader('Loader', 'classes');
138
+			$this->lang = & class_loader('Lang', 'classes');
139
+			$this->request = & class_loader('Request', 'classes');
140 140
 			//dispatch the request instance created event
141 141
 			$this->eventdispatcher->dispatch('REQUEST_CREATED');
142
-			$this->response =& class_loader('Response', 'classes', 'classes');
142
+			$this->response = & class_loader('Response', 'classes', 'classes');
143 143
 		}
144 144
 
145 145
 	}
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -1,145 +1,145 @@
 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 Controller{
27
+    class Controller{
28 28
 		
29
-		/**
30
-		 * The name of the module if this controller belong to an module
31
-		 * @var string
32
-		 */
33
-		public $moduleName = null;
29
+        /**
30
+         * The name of the module if this controller belong to an module
31
+         * @var string
32
+         */
33
+        public $moduleName = null;
34 34
 
35
-		/**
36
-		 * The singleton of the super object
37
-		 * @var Controller
38
-		 */
39
-		private static $instance;
35
+        /**
36
+         * The singleton of the super object
37
+         * @var Controller
38
+         */
39
+        private static $instance;
40 40
 
41
-		/**
42
-		 * The logger instance
43
-		 * @var Log
44
-		 */
45
-		protected $logger;
41
+        /**
42
+         * The logger instance
43
+         * @var Log
44
+         */
45
+        protected $logger;
46 46
 
47
-		/**
48
-		 * Class constructor
49
-		 * @param object $logger the Log instance to use if is null will create one
50
-		 */
51
-		public function __construct(Log $logger = null){
52
-			//setting the Log instance
53
-			$this->setLoggerFromParamOrCreateNewInstance($logger);
47
+        /**
48
+         * Class constructor
49
+         * @param object $logger the Log instance to use if is null will create one
50
+         */
51
+        public function __construct(Log $logger = null){
52
+            //setting the Log instance
53
+            $this->setLoggerFromParamOrCreateNewInstance($logger);
54 54
 			
55
-			//instance of the super object
56
-			self::$instance = & $this;
55
+            //instance of the super object
56
+            self::$instance = & $this;
57 57
 			
58
-			//load the required resources
59
-			$this->loadRequiredResources();
58
+            //load the required resources
59
+            $this->loadRequiredResources();
60 60
 			
61
-			//set the cache using the configuration
62
-			$this->setCacheFromParamOrConfig(null);
61
+            //set the cache using the configuration
62
+            $this->setCacheFromParamOrConfig(null);
63 63
 			
64
-			//set application session configuration
65
-			$this->logger->debug('Setting PHP application session handler');
66
-			set_session_config();
64
+            //set application session configuration
65
+            $this->logger->debug('Setting PHP application session handler');
66
+            set_session_config();
67 67
 			
68
-			//set module using the router
69
-			$this->setModuleNameFromRouter();
68
+            //set module using the router
69
+            $this->setModuleNameFromRouter();
70 70
 
71
-			//dispatch the loaded instance of super controller event
72
-			$this->eventdispatcher->dispatch('SUPER_CONTROLLER_CREATED');
73
-		}
71
+            //dispatch the loaded instance of super controller event
72
+            $this->eventdispatcher->dispatch('SUPER_CONTROLLER_CREATED');
73
+        }
74 74
 
75 75
 
76
-		/**
77
-		 * This is a very useful method it's used to get the super object instance
78
-		 * @return Controller the super object instance
79
-		 */
80
-		public static function &get_instance(){
81
-			return self::$instance;
82
-		}
76
+        /**
77
+         * This is a very useful method it's used to get the super object instance
78
+         * @return Controller the super object instance
79
+         */
80
+        public static function &get_instance(){
81
+            return self::$instance;
82
+        }
83 83
 
84
-		/**
85
-		 * This method is used to set the module name
86
-		 */
87
-		protected function setModuleNameFromRouter(){
88
-			//determine the current module
89
-			if(isset($this->router) && $this->router->getModule()){
90
-				$this->moduleName = $this->router->getModule();
91
-			}
92
-		}
84
+        /**
85
+         * This method is used to set the module name
86
+         */
87
+        protected function setModuleNameFromRouter(){
88
+            //determine the current module
89
+            if(isset($this->router) && $this->router->getModule()){
90
+                $this->moduleName = $this->router->getModule();
91
+            }
92
+        }
93 93
 
94
-		/**
95
-		 * Set the cache using the argument otherwise will use the configuration
96
-		 * @param CacheInterface $cache the implementation of CacheInterface if null will use the configured
97
-		 */
98
-		protected function setCacheFromParamOrConfig(CacheInterface $cache = null){
99
-			$this->logger->debug('Setting the cache handler instance');
100
-			//set cache handler instance
101
-			if(get_config('cache_enable', false)){
102
-				if ($cache !== null){
103
-					$this->cache = $cache;
104
-				} else if (isset($this->{strtolower(get_config('cache_handler'))})){
105
-					$this->cache = $this->{strtolower(get_config('cache_handler'))};
106
-					unset($this->{strtolower(get_config('cache_handler'))});
107
-				} 
108
-			}
109
-		}
94
+        /**
95
+         * Set the cache using the argument otherwise will use the configuration
96
+         * @param CacheInterface $cache the implementation of CacheInterface if null will use the configured
97
+         */
98
+        protected function setCacheFromParamOrConfig(CacheInterface $cache = null){
99
+            $this->logger->debug('Setting the cache handler instance');
100
+            //set cache handler instance
101
+            if(get_config('cache_enable', false)){
102
+                if ($cache !== null){
103
+                    $this->cache = $cache;
104
+                } else if (isset($this->{strtolower(get_config('cache_handler'))})){
105
+                    $this->cache = $this->{strtolower(get_config('cache_handler'))};
106
+                    unset($this->{strtolower(get_config('cache_handler'))});
107
+                } 
108
+            }
109
+        }
110 110
 
111
-		/**
112
-		 * Set the Log instance using argument or create new instance
113
-		 * @param object $logger the Log instance if not null
114
-		 */
115
-		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116
-			if($logger !== null){
117
-	          $this->logger = $logger;
118
-	        }
119
-	        else{
120
-	            $this->logger =& class_loader('Log', 'classes');
121
-				$this->logger->setLogger('MainController');
122
-	        }
123
-		}
111
+        /**
112
+         * Set the Log instance using argument or create new instance
113
+         * @param object $logger the Log instance if not null
114
+         */
115
+        protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116
+            if($logger !== null){
117
+                $this->logger = $logger;
118
+            }
119
+            else{
120
+                $this->logger =& class_loader('Log', 'classes');
121
+                $this->logger->setLogger('MainController');
122
+            }
123
+        }
124 124
 
125
-		/**
126
-		 * This method is used to load the required resources for framework to work
127
-		 * @return void 
128
-		 */
129
-		private function loadRequiredResources(){
130
-			$this->logger->debug('Adding the loaded classes to the super instance');
131
-			foreach (class_loaded() as $var => $class){
132
-				$this->$var =& class_loader($class);
133
-			}
125
+        /**
126
+         * This method is used to load the required resources for framework to work
127
+         * @return void 
128
+         */
129
+        private function loadRequiredResources(){
130
+            $this->logger->debug('Adding the loaded classes to the super instance');
131
+            foreach (class_loaded() as $var => $class){
132
+                $this->$var =& class_loader($class);
133
+            }
134 134
 
135
-			$this->logger->debug('Loading the required classes into super instance');
136
-			$this->eventdispatcher =& class_loader('EventDispatcher', 'classes');
137
-			$this->loader =& class_loader('Loader', 'classes');
138
-			$this->lang =& class_loader('Lang', 'classes');
139
-			$this->request =& class_loader('Request', 'classes');
140
-			//dispatch the request instance created event
141
-			$this->eventdispatcher->dispatch('REQUEST_CREATED');
142
-			$this->response =& class_loader('Response', 'classes', 'classes');
143
-		}
135
+            $this->logger->debug('Loading the required classes into super instance');
136
+            $this->eventdispatcher =& class_loader('EventDispatcher', 'classes');
137
+            $this->loader =& class_loader('Loader', 'classes');
138
+            $this->lang =& class_loader('Lang', 'classes');
139
+            $this->request =& class_loader('Request', 'classes');
140
+            //dispatch the request instance created event
141
+            $this->eventdispatcher->dispatch('REQUEST_CREATED');
142
+            $this->response =& class_loader('Response', 'classes', 'classes');
143
+        }
144 144
 
145
-	}
145
+    }
Please login to merge, or discard this patch.
tests/tnhfw/classes/EventInfoTest.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
 
26 26
 		
27 27
 		
28
-		public function testDefaultValue(){
28
+		public function testDefaultValue() {
29 29
 			$e = new EventInfo('foo');
30 30
 			$this->assertSame($e->name, 'foo');
31 31
 			$this->assertSame($e->payload, array());
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 			$this->assertFalse($e->stop);
34 34
 		}
35 35
 		
36
-		public function testPayloadValueIsSet(){
36
+		public function testPayloadValueIsSet() {
37 37
 			$e = new EventInfo('foo', array('bar'));
38 38
 			$this->assertSame($e->name, 'foo');
39 39
 			$this->assertSame($e->payload, array('bar'));
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 			$this->assertFalse($e->stop);
42 42
 		}
43 43
 		
44
-		public function testReturnBackValueIsSetToTrue(){
44
+		public function testReturnBackValueIsSetToTrue() {
45 45
 			$e = new EventInfo('foo', array('bar'), true);
46 46
 			$this->assertSame($e->name, 'foo');
47 47
 			$this->assertSame($e->payload, array('bar'));
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 			$this->assertFalse($e->stop);
50 50
 		}
51 51
 		
52
-		public function testStopValueIsSetToTue(){
52
+		public function testStopValueIsSetToTue() {
53 53
 			$e = new EventInfo('foo', array('bar'), true, true);
54 54
 			$this->assertSame($e->name, 'foo');
55 55
 			$this->assertSame($e->payload, array('bar'));
Please login to merge, or discard this patch.
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -1,59 +1,59 @@
 block discarded – undo
1 1
 <?php 
2 2
 
3
-	use PHPUnit\Framework\TestCase;
3
+    use PHPUnit\Framework\TestCase;
4 4
 
5
-	class EventInfoTest extends TestCase
6
-	{	
5
+    class EventInfoTest extends TestCase
6
+    {	
7 7
 	
8
-		public static function setUpBeforeClass()
9
-		{
8
+        public static function setUpBeforeClass()
9
+        {
10 10
 		
11
-		}
11
+        }
12 12
 		
13
-		public static function tearDownAfterClass()
14
-		{
13
+        public static function tearDownAfterClass()
14
+        {
15 15
 			
16
-		}
16
+        }
17 17
 		
18
-		protected function setUp()
19
-		{
20
-		}
18
+        protected function setUp()
19
+        {
20
+        }
21 21
 
22
-		protected function tearDown()
23
-		{
24
-		}
22
+        protected function tearDown()
23
+        {
24
+        }
25 25
 
26 26
 		
27 27
 		
28
-		public function testDefaultValue(){
29
-			$e = new EventInfo('foo');
30
-			$this->assertSame($e->name, 'foo');
31
-			$this->assertSame($e->payload, array());
32
-			$this->assertFalse($e->returnBack);
33
-			$this->assertFalse($e->stop);
34
-		}
35
-		
36
-		public function testPayloadValueIsSet(){
37
-			$e = new EventInfo('foo', array('bar'));
38
-			$this->assertSame($e->name, 'foo');
39
-			$this->assertSame($e->payload, array('bar'));
40
-			$this->assertFalse($e->returnBack);
41
-			$this->assertFalse($e->stop);
42
-		}
43
-		
44
-		public function testReturnBackValueIsSetToTrue(){
45
-			$e = new EventInfo('foo', array('bar'), true);
46
-			$this->assertSame($e->name, 'foo');
47
-			$this->assertSame($e->payload, array('bar'));
48
-			$this->assertTrue($e->returnBack);
49
-			$this->assertFalse($e->stop);
50
-		}
51
-		
52
-		public function testStopValueIsSetToTue(){
53
-			$e = new EventInfo('foo', array('bar'), true, true);
54
-			$this->assertSame($e->name, 'foo');
55
-			$this->assertSame($e->payload, array('bar'));
56
-			$this->assertTrue($e->returnBack);
57
-			$this->assertTrue($e->stop);
58
-		}
59
-	}
60 28
\ No newline at end of file
29
+        public function testDefaultValue(){
30
+            $e = new EventInfo('foo');
31
+            $this->assertSame($e->name, 'foo');
32
+            $this->assertSame($e->payload, array());
33
+            $this->assertFalse($e->returnBack);
34
+            $this->assertFalse($e->stop);
35
+        }
36
+		
37
+        public function testPayloadValueIsSet(){
38
+            $e = new EventInfo('foo', array('bar'));
39
+            $this->assertSame($e->name, 'foo');
40
+            $this->assertSame($e->payload, array('bar'));
41
+            $this->assertFalse($e->returnBack);
42
+            $this->assertFalse($e->stop);
43
+        }
44
+		
45
+        public function testReturnBackValueIsSetToTrue(){
46
+            $e = new EventInfo('foo', array('bar'), true);
47
+            $this->assertSame($e->name, 'foo');
48
+            $this->assertSame($e->payload, array('bar'));
49
+            $this->assertTrue($e->returnBack);
50
+            $this->assertFalse($e->stop);
51
+        }
52
+		
53
+        public function testStopValueIsSetToTue(){
54
+            $e = new EventInfo('foo', array('bar'), true, true);
55
+            $this->assertSame($e->name, 'foo');
56
+            $this->assertSame($e->payload, array('bar'));
57
+            $this->assertTrue($e->returnBack);
58
+            $this->assertTrue($e->stop);
59
+        }
60
+    }
61 61
\ No newline at end of file
Please login to merge, or discard this patch.
tests/tnhfw/classes/DBSessionHandlerTest.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
 		
14 14
 		private static $config = null;
15 15
 		
16
-		public function __construct(){
16
+		public function __construct() {
17 17
 			$this->db = new Database(array(
18 18
 								'driver'    =>  'sqlite',
19 19
 								'database'  =>  TESTS_PATH . 'assets/db_tests.db',
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 
50 50
 		
51 51
 		
52
-		public function testUsingSessionConfiguration(){
52
+		public function testUsingSessionConfiguration() {
53 53
 			//using value in the configuration
54 54
 			self::$config->set('session_save_path', 'DBSessionModel');
55 55
 			self::$config->set('session_secret', $this->secret);
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 			$this->assertEquals($dbsh->decode($encoded), 'foo');
76 76
 		}
77 77
 		
78
-		public function testWhenDataIsExpired(){
78
+		public function testWhenDataIsExpired() {
79 79
 			$dbsh = new DBSessionHandler($this->model);
80 80
 			$dbsh->setSessionSecret($this->secret);
81 81
 			
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 			$this->assertNull($dbsh->read('foo'));
89 89
 		}
90 90
 		
91
-		public function testWhenDataAlreadyExistDoUpdate(){
91
+		public function testWhenDataAlreadyExistDoUpdate() {
92 92
 			$dbsh = new DBSessionHandler($this->model);
93 93
 			$dbsh->setSessionSecret($this->secret);
94 94
 			
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 			$this->assertEquals($dbsh->read('foo'), '445');	
102 102
 		}
103 103
 		
104
-		public function testUsingCustomModelInstance(){
104
+		public function testUsingCustomModelInstance() {
105 105
 			$dbsh = new DBSessionHandler($this->model);
106 106
 			$dbsh->setSessionSecret($this->secret);
107 107
 			
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 		}
130 130
 			
131 131
 			
132
-		public function testUsingCustomLogInstance(){
132
+		public function testUsingCustomLogInstance() {
133 133
 			$dbsh = new DBSessionHandler($this->model, new Log());
134 134
 			$dbsh->setSessionSecret($this->secret);
135 135
 			
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 			$this->assertEquals($dbsh->decode($encoded), 'foo');
157 157
 		}
158 158
 		
159
-		public function testUsingCustomLoaderInstance(){
159
+		public function testUsingCustomLoaderInstance() {
160 160
 			$dbsh = new DBSessionHandler($this->model, null, new Loader());
161 161
 			$dbsh->setSessionSecret($this->secret);
162 162
 			
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 		}
185 185
 		
186 186
 		
187
-		public function testWhenModelInsanceIsNotSet(){
187
+		public function testWhenModelInsanceIsNotSet() {
188 188
 			$dbsh = new DBSessionHandler(null, null, new Loader());
189 189
 			$dbsh->setSessionSecret($this->secret);
190 190
 			
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 			$this->assertEquals($dbsh->decode($encoded), 'foo');
213 213
 		}
214 214
 		
215
-		public function testWhenModelTableColumnsIsNotSet(){
215
+		public function testWhenModelTableColumnsIsNotSet() {
216 216
 			//session table is empty
217 217
 			$this->model->setSessionTableColumns(array());
218 218
 			$dbsh = new DBSessionHandler($this->model);
Please login to merge, or discard this patch.
Indentation   +204 added lines, -204 removed lines patch added patch discarded remove patch
@@ -1,226 +1,226 @@
 block discarded – undo
1 1
 <?php 
2 2
 
3
-	use PHPUnit\Framework\TestCase;
3
+    use PHPUnit\Framework\TestCase;
4 4
 
5
-	class DBSessionHandlerTest extends TestCase
6
-	{	
5
+    class DBSessionHandlerTest extends TestCase
6
+    {	
7 7
 	
8
-		private $db = null;
8
+        private $db = null;
9 9
 		
10
-		private $model = null;
10
+        private $model = null;
11 11
 		
12
-		private $secret = 'bXlzZWNyZXQ';
12
+        private $secret = 'bXlzZWNyZXQ';
13 13
 		
14
-		private static $config = null;
14
+        private static $config = null;
15 15
 		
16
-		public function __construct(){
17
-			$this->db = new Database(array(
18
-								'driver'    =>  'sqlite',
19
-								'database'  =>  TESTS_PATH . 'assets/db_tests.db',
20
-								'charset'   => 'utf8',
21
-								'collation' => 'utf8_general_ci',
22
-							));
16
+        public function __construct(){
17
+            $this->db = new Database(array(
18
+                                'driver'    =>  'sqlite',
19
+                                'database'  =>  TESTS_PATH . 'assets/db_tests.db',
20
+                                'charset'   => 'utf8',
21
+                                'collation' => 'utf8_general_ci',
22
+                            ));
23 23
             $qr = new DatabaseQueryRunner($this->db->getPdo());
24 24
             $qr->setBenchmark(new Benchmark());
25 25
             $qr->setDriver('sqlite');
26 26
             $this->db->setQueryRunner($qr);
27
-		}
27
+        }
28 28
 		
29
-		public static function setUpBeforeClass()
30
-		{
31
-			require APPS_MODEL_PATH . 'DBSessionModel.php';
32
-			self::$config = new Config();
33
-			self::$config->init();
34
-		}
29
+        public static function setUpBeforeClass()
30
+        {
31
+            require APPS_MODEL_PATH . 'DBSessionModel.php';
32
+            self::$config = new Config();
33
+            self::$config->init();
34
+        }
35 35
 		
36 36
 		
37
-		public static function tearDownAfterClass()
38
-		{
37
+        public static function tearDownAfterClass()
38
+        {
39 39
 			
40
-		}
40
+        }
41 41
 		
42
-		protected function setUp()
43
-		{
44
-			$this->model = new DBSessionModel($this->db);
42
+        protected function setUp()
43
+        {
44
+            $this->model = new DBSessionModel($this->db);
45 45
             //to prevent old data conflict
46
-			$this->model->truncate();
47
-		}
46
+            $this->model->truncate();
47
+        }
48 48
 
49
-		protected function tearDown()
50
-		{
51
-		}
49
+        protected function tearDown()
50
+        {
51
+        }
52 52
 
53 53
 		
54 54
 		
55
-		public function testUsingSessionConfiguration(){
56
-			//using value in the configuration
57
-			self::$config->set('session_save_path', 'DBSessionModel');
58
-			self::$config->set('session_secret', $this->secret);
59
-			$dbsh = new DBSessionHandler();
60
-			//assign Database instance manually
61
-			$o = &get_instance();
62
-			$o->database = $this->db;
63
-			
64
-			$this->assertTrue($dbsh->open(null, null));
65
-			$this->assertTrue($dbsh->close());
66
-			$this->assertNull($dbsh->read('foo'));
67
-			$this->assertTrue($dbsh->write('foo', '444'));
68
-			$this->assertNotEmpty($dbsh->read('foo'));
69
-			$this->assertEquals($dbsh->read('foo'), '444');
70
-			//do update of existing data
71
-			$this->assertTrue($dbsh->write('foo', '445'));
72
-			$this->assertEquals($dbsh->read('foo'), '445');	
73
-			$this->assertTrue($dbsh->destroy('foo'));
74
-			$this->assertNull($dbsh->read('foo'));
75
-			$this->assertTrue($dbsh->gc(13));
76
-			$encoded = $dbsh->encode('foo');
77
-			$this->assertNotEmpty($encoded);
78
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
79
-		}
80
-		
81
-		public function testWhenDataIsExpired(){
82
-			$dbsh = new DBSessionHandler($this->model);
83
-			$dbsh->setSessionSecret($this->secret);
84
-			
85
-			$this->assertTrue($dbsh->open(null, null));
86
-			$this->assertTrue($dbsh->write('foo', '444'));
87
-			$this->assertNotEmpty($dbsh->read('foo'));
88
-			$this->assertEquals($dbsh->read('foo'), '444');
89
-			//put it in expired
90
-			$this->model->update('foo', array('s_time' => 1234567));
91
-			$this->assertNull($dbsh->read('foo'));
92
-		}
93
-		
94
-		public function testWhenDataAlreadyExistDoUpdate(){
95
-			$dbsh = new DBSessionHandler($this->model);
96
-			$dbsh->setSessionSecret($this->secret);
97
-			
98
-			$this->assertTrue($dbsh->open(null, null));
99
-			$this->assertTrue($dbsh->write('foo', '444'));
100
-			$this->assertNotEmpty($dbsh->read('foo'));
101
-			$this->assertEquals($dbsh->read('foo'), '444');
102
-			//do update of existing data
103
-			$this->assertTrue($dbsh->write('foo', '445'));
104
-			$this->assertEquals($dbsh->read('foo'), '445');	
105
-		}
106
-		
107
-		public function testUsingCustomModelInstance(){
108
-			$dbsh = new DBSessionHandler($this->model);
109
-			$dbsh->setSessionSecret($this->secret);
110
-			
111
-			$this->assertTrue($dbsh->open(null, null));
112
-			$this->assertTrue($dbsh->close());
113
-			$this->assertNull($dbsh->read('foo'));
114
-			$this->assertTrue($dbsh->write('foo', '444'));
115
-			$this->assertNotEmpty($dbsh->read('foo'));
116
-			$this->assertEquals($dbsh->read('foo'), '444');
117
-			//put it in expired
118
-			$this->model->update('foo', array('s_time' => 1234567));
119
-			
120
-			$this->assertNull($dbsh->read('foo'));
121
-			$this->assertTrue($dbsh->write('foo', '444'));
122
-			
123
-			//do update of existing data
124
-			$this->assertTrue($dbsh->write('foo', '445'));
125
-			$this->assertEquals($dbsh->read('foo'), '445');	
126
-			$this->assertTrue($dbsh->destroy('foo'));
127
-			$this->assertNull($dbsh->read('foo'));
128
-			$this->assertTrue($dbsh->gc(13));
129
-			$encoded = $dbsh->encode('foo');
130
-			$this->assertNotEmpty($encoded);
131
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
132
-		}
133
-			
134
-			
135
-		public function testUsingCustomLogInstance(){
136
-			$dbsh = new DBSessionHandler($this->model, new Log());
137
-			$dbsh->setSessionSecret($this->secret);
138
-			
139
-			$this->assertTrue($dbsh->open(null, null));
140
-			$this->assertTrue($dbsh->close());
141
-			$this->assertNull($dbsh->read('foo'));
142
-			$this->assertTrue($dbsh->write('foo', '444'));
143
-			$this->assertNotEmpty($dbsh->read('foo'));
144
-			$this->assertEquals($dbsh->read('foo'), '444');
145
-			//put it in expired
146
-			$this->model->update('foo', array('s_time' => 1234567));
147
-			
148
-			$this->assertNull($dbsh->read('foo'));
149
-			$this->assertTrue($dbsh->write('foo', '444'));
150
-			
151
-			//do update of existing data
152
-			$this->assertTrue($dbsh->write('foo', '445'));
153
-			$this->assertEquals($dbsh->read('foo'), '445');	
154
-			$this->assertTrue($dbsh->destroy('foo'));
155
-			$this->assertNull($dbsh->read('foo'));
156
-			$this->assertTrue($dbsh->gc(13));
157
-			$encoded = $dbsh->encode('foo');
158
-			$this->assertNotEmpty($encoded);
159
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
160
-		}
161
-		
162
-		public function testUsingCustomLoaderInstance(){
163
-			$dbsh = new DBSessionHandler($this->model, null, new Loader());
164
-			$dbsh->setSessionSecret($this->secret);
165
-			
166
-			$this->assertTrue($dbsh->open(null, null));
167
-			$this->assertTrue($dbsh->close());
168
-			$this->assertNull($dbsh->read('foo'));
169
-			$this->assertTrue($dbsh->write('foo', '444'));
170
-			$this->assertNotEmpty($dbsh->read('foo'));
171
-			$this->assertEquals($dbsh->read('foo'), '444');
172
-			//put it in expired
173
-			$this->model->update('foo', array('s_time' => 1234567));
174
-			
175
-			$this->assertNull($dbsh->read('foo'));
176
-			$this->assertTrue($dbsh->write('foo', '444'));
177
-			
178
-			//do update of existing data
179
-			$this->assertTrue($dbsh->write('foo', '445'));
180
-			$this->assertEquals($dbsh->read('foo'), '445');	
181
-			$this->assertTrue($dbsh->destroy('foo'));
182
-			$this->assertNull($dbsh->read('foo'));
183
-			$this->assertTrue($dbsh->gc(13));
184
-			$encoded = $dbsh->encode('foo');
185
-			$this->assertNotEmpty($encoded);
186
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
187
-		}
188
-		
189
-		
190
-		public function testWhenModelInsanceIsNotSet(){
191
-			$dbsh = new DBSessionHandler(null, null, new Loader());
192
-			$dbsh->setSessionSecret($this->secret);
193
-			
194
-			$this->assertTrue($dbsh->open(null, null));
195
-			$this->assertTrue($dbsh->close());
196
-			$this->assertNull($dbsh->read('foo'));
197
-			$this->assertTrue($dbsh->write('foo', '444'));
198
-			$this->assertNotEmpty($dbsh->read('foo'));
199
-			$this->assertEquals($dbsh->read('foo'), '444');
200
-			//put it in expired
201
-			$this->model->update('foo', array('s_time' => 1234567));
202
-			
203
-			$this->assertNull($dbsh->read('foo'));
204
-			$this->assertTrue($dbsh->write('foo', '444'));
205
-			
206
-			//do update of existing data
207
-			$this->assertTrue($dbsh->write('tnh', '445'));
208
-			$this->assertTrue($dbsh->write('foo', '445'));
209
-			$this->assertEquals($dbsh->read('foo'), '445');	
210
-			$this->assertTrue($dbsh->destroy('foo'));
211
-			$this->assertNull($dbsh->read('foo'));
212
-			$this->assertTrue($dbsh->gc(13));
213
-			$encoded = $dbsh->encode('foo');
214
-			$this->assertNotEmpty($encoded);
215
-			$this->assertEquals($dbsh->decode($encoded), 'foo');
216
-		}
217
-		
218
-		public function testWhenModelTableColumnsIsNotSet(){
219
-			//session table is empty
220
-			$this->model->setSessionTableColumns(array());
221
-			$dbsh = new DBSessionHandler($this->model);
222
-			$this->assertTrue($dbsh->open(null, null));
223
-		}
224
-		
225
-		
226
-	}
227 55
\ No newline at end of file
56
+        public function testUsingSessionConfiguration(){
57
+            //using value in the configuration
58
+            self::$config->set('session_save_path', 'DBSessionModel');
59
+            self::$config->set('session_secret', $this->secret);
60
+            $dbsh = new DBSessionHandler();
61
+            //assign Database instance manually
62
+            $o = &get_instance();
63
+            $o->database = $this->db;
64
+			
65
+            $this->assertTrue($dbsh->open(null, null));
66
+            $this->assertTrue($dbsh->close());
67
+            $this->assertNull($dbsh->read('foo'));
68
+            $this->assertTrue($dbsh->write('foo', '444'));
69
+            $this->assertNotEmpty($dbsh->read('foo'));
70
+            $this->assertEquals($dbsh->read('foo'), '444');
71
+            //do update of existing data
72
+            $this->assertTrue($dbsh->write('foo', '445'));
73
+            $this->assertEquals($dbsh->read('foo'), '445');	
74
+            $this->assertTrue($dbsh->destroy('foo'));
75
+            $this->assertNull($dbsh->read('foo'));
76
+            $this->assertTrue($dbsh->gc(13));
77
+            $encoded = $dbsh->encode('foo');
78
+            $this->assertNotEmpty($encoded);
79
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
80
+        }
81
+		
82
+        public function testWhenDataIsExpired(){
83
+            $dbsh = new DBSessionHandler($this->model);
84
+            $dbsh->setSessionSecret($this->secret);
85
+			
86
+            $this->assertTrue($dbsh->open(null, null));
87
+            $this->assertTrue($dbsh->write('foo', '444'));
88
+            $this->assertNotEmpty($dbsh->read('foo'));
89
+            $this->assertEquals($dbsh->read('foo'), '444');
90
+            //put it in expired
91
+            $this->model->update('foo', array('s_time' => 1234567));
92
+            $this->assertNull($dbsh->read('foo'));
93
+        }
94
+		
95
+        public function testWhenDataAlreadyExistDoUpdate(){
96
+            $dbsh = new DBSessionHandler($this->model);
97
+            $dbsh->setSessionSecret($this->secret);
98
+			
99
+            $this->assertTrue($dbsh->open(null, null));
100
+            $this->assertTrue($dbsh->write('foo', '444'));
101
+            $this->assertNotEmpty($dbsh->read('foo'));
102
+            $this->assertEquals($dbsh->read('foo'), '444');
103
+            //do update of existing data
104
+            $this->assertTrue($dbsh->write('foo', '445'));
105
+            $this->assertEquals($dbsh->read('foo'), '445');	
106
+        }
107
+		
108
+        public function testUsingCustomModelInstance(){
109
+            $dbsh = new DBSessionHandler($this->model);
110
+            $dbsh->setSessionSecret($this->secret);
111
+			
112
+            $this->assertTrue($dbsh->open(null, null));
113
+            $this->assertTrue($dbsh->close());
114
+            $this->assertNull($dbsh->read('foo'));
115
+            $this->assertTrue($dbsh->write('foo', '444'));
116
+            $this->assertNotEmpty($dbsh->read('foo'));
117
+            $this->assertEquals($dbsh->read('foo'), '444');
118
+            //put it in expired
119
+            $this->model->update('foo', array('s_time' => 1234567));
120
+			
121
+            $this->assertNull($dbsh->read('foo'));
122
+            $this->assertTrue($dbsh->write('foo', '444'));
123
+			
124
+            //do update of existing data
125
+            $this->assertTrue($dbsh->write('foo', '445'));
126
+            $this->assertEquals($dbsh->read('foo'), '445');	
127
+            $this->assertTrue($dbsh->destroy('foo'));
128
+            $this->assertNull($dbsh->read('foo'));
129
+            $this->assertTrue($dbsh->gc(13));
130
+            $encoded = $dbsh->encode('foo');
131
+            $this->assertNotEmpty($encoded);
132
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
133
+        }
134
+			
135
+			
136
+        public function testUsingCustomLogInstance(){
137
+            $dbsh = new DBSessionHandler($this->model, new Log());
138
+            $dbsh->setSessionSecret($this->secret);
139
+			
140
+            $this->assertTrue($dbsh->open(null, null));
141
+            $this->assertTrue($dbsh->close());
142
+            $this->assertNull($dbsh->read('foo'));
143
+            $this->assertTrue($dbsh->write('foo', '444'));
144
+            $this->assertNotEmpty($dbsh->read('foo'));
145
+            $this->assertEquals($dbsh->read('foo'), '444');
146
+            //put it in expired
147
+            $this->model->update('foo', array('s_time' => 1234567));
148
+			
149
+            $this->assertNull($dbsh->read('foo'));
150
+            $this->assertTrue($dbsh->write('foo', '444'));
151
+			
152
+            //do update of existing data
153
+            $this->assertTrue($dbsh->write('foo', '445'));
154
+            $this->assertEquals($dbsh->read('foo'), '445');	
155
+            $this->assertTrue($dbsh->destroy('foo'));
156
+            $this->assertNull($dbsh->read('foo'));
157
+            $this->assertTrue($dbsh->gc(13));
158
+            $encoded = $dbsh->encode('foo');
159
+            $this->assertNotEmpty($encoded);
160
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
161
+        }
162
+		
163
+        public function testUsingCustomLoaderInstance(){
164
+            $dbsh = new DBSessionHandler($this->model, null, new Loader());
165
+            $dbsh->setSessionSecret($this->secret);
166
+			
167
+            $this->assertTrue($dbsh->open(null, null));
168
+            $this->assertTrue($dbsh->close());
169
+            $this->assertNull($dbsh->read('foo'));
170
+            $this->assertTrue($dbsh->write('foo', '444'));
171
+            $this->assertNotEmpty($dbsh->read('foo'));
172
+            $this->assertEquals($dbsh->read('foo'), '444');
173
+            //put it in expired
174
+            $this->model->update('foo', array('s_time' => 1234567));
175
+			
176
+            $this->assertNull($dbsh->read('foo'));
177
+            $this->assertTrue($dbsh->write('foo', '444'));
178
+			
179
+            //do update of existing data
180
+            $this->assertTrue($dbsh->write('foo', '445'));
181
+            $this->assertEquals($dbsh->read('foo'), '445');	
182
+            $this->assertTrue($dbsh->destroy('foo'));
183
+            $this->assertNull($dbsh->read('foo'));
184
+            $this->assertTrue($dbsh->gc(13));
185
+            $encoded = $dbsh->encode('foo');
186
+            $this->assertNotEmpty($encoded);
187
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
188
+        }
189
+		
190
+		
191
+        public function testWhenModelInsanceIsNotSet(){
192
+            $dbsh = new DBSessionHandler(null, null, new Loader());
193
+            $dbsh->setSessionSecret($this->secret);
194
+			
195
+            $this->assertTrue($dbsh->open(null, null));
196
+            $this->assertTrue($dbsh->close());
197
+            $this->assertNull($dbsh->read('foo'));
198
+            $this->assertTrue($dbsh->write('foo', '444'));
199
+            $this->assertNotEmpty($dbsh->read('foo'));
200
+            $this->assertEquals($dbsh->read('foo'), '444');
201
+            //put it in expired
202
+            $this->model->update('foo', array('s_time' => 1234567));
203
+			
204
+            $this->assertNull($dbsh->read('foo'));
205
+            $this->assertTrue($dbsh->write('foo', '444'));
206
+			
207
+            //do update of existing data
208
+            $this->assertTrue($dbsh->write('tnh', '445'));
209
+            $this->assertTrue($dbsh->write('foo', '445'));
210
+            $this->assertEquals($dbsh->read('foo'), '445');	
211
+            $this->assertTrue($dbsh->destroy('foo'));
212
+            $this->assertNull($dbsh->read('foo'));
213
+            $this->assertTrue($dbsh->gc(13));
214
+            $encoded = $dbsh->encode('foo');
215
+            $this->assertNotEmpty($encoded);
216
+            $this->assertEquals($dbsh->decode($encoded), 'foo');
217
+        }
218
+		
219
+        public function testWhenModelTableColumnsIsNotSet(){
220
+            //session table is empty
221
+            $this->model->setSessionTableColumns(array());
222
+            $dbsh = new DBSessionHandler($this->model);
223
+            $this->assertTrue($dbsh->open(null, null));
224
+        }
225
+		
226
+		
227
+    }
228 228
\ No newline at end of file
Please login to merge, or discard this patch.
tests/hmvc/models/DBSessionModel.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	class DBSessionModel extends DBSessionHandlerModel{
2
+	class DBSessionModel extends DBSessionHandlerModel {
3 3
 		
4 4
 		protected $_table = 'ses';
5 5
 		protected $primary_key = 's_id';
@@ -14,14 +14,14 @@  discard block
 block discarded – undo
14 14
 			'skey' => 'test_id' //VARCHAR(255) 
15 15
 		);
16 16
 		
17
-		public function deleteByTime($time){
17
+		public function deleteByTime($time) {
18 18
 			$this->getQueryBuilder()->from($this->_table)
19 19
 									->where('s_time', '<', $time);
20 20
 			$this->_database->delete();
21 21
 		}
22 22
 
23 23
 		
24
-		public function getKeyValue(){
24
+		public function getKeyValue() {
25 25
 			$user_id = 0;
26 26
 			return $user_id;
27 27
 		}
Please login to merge, or discard this patch.
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -1,28 +1,28 @@
 block discarded – undo
1 1
 <?php
2
-	class DBSessionModel extends DBSessionHandlerModel{
2
+    class DBSessionModel extends DBSessionHandlerModel{
3 3
 		
4
-		protected $_table = 'ses';
5
-		protected $primary_key = 's_id';
4
+        protected $_table = 'ses';
5
+        protected $primary_key = 's_id';
6 6
 		
7
-		protected $sessionTableColumns = array(
8
-			'sid' => 's_id', //VARCHAR(255)
9
-			'sdata' => 's_data', //TEXT
10
-			'stime' => 's_time', //unix timestamp (INT|BIGINT)
11
-			'shost' => 's_host', //VARCHAR(255)
12
-			'sip' => 's_ip', //VARCHAR(255) 
13
-			'sbrowser' => 's_browser', //VARCHAR(255) 
14
-			'skey' => 'test_id' //VARCHAR(255) 
15
-		);
7
+        protected $sessionTableColumns = array(
8
+            'sid' => 's_id', //VARCHAR(255)
9
+            'sdata' => 's_data', //TEXT
10
+            'stime' => 's_time', //unix timestamp (INT|BIGINT)
11
+            'shost' => 's_host', //VARCHAR(255)
12
+            'sip' => 's_ip', //VARCHAR(255) 
13
+            'sbrowser' => 's_browser', //VARCHAR(255) 
14
+            'skey' => 'test_id' //VARCHAR(255) 
15
+        );
16 16
 		
17
-		public function deleteByTime($time){
18
-			$this->getQueryBuilder()->from($this->_table)
19
-									->where('s_time', '<', $time);
20
-			$this->_database->delete();
21
-		}
17
+        public function deleteByTime($time){
18
+            $this->getQueryBuilder()->from($this->_table)
19
+                                    ->where('s_time', '<', $time);
20
+            $this->_database->delete();
21
+        }
22 22
 
23 23
 		
24
-		public function getKeyValue(){
25
-			$user_id = 0;
26
-			return $user_id;
27
-		}
28
-	}
29 24
\ No newline at end of file
25
+        public function getKeyValue(){
26
+            $user_id = 0;
27
+            return $user_id;
28
+        }
29
+    }
30 30
\ No newline at end of file
Please login to merge, or discard this patch.
tests/include/autoloader.php 3 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 	//Autoload function
3
-	function tests_autoload($class){
3
+	function tests_autoload($class) {
4 4
 		$classesMap = array(
5 5
 			//Caches
6 6
 			'ApcCache' => CORE_CLASSES_CACHE_PATH . 'ApcCache.php',
@@ -40,11 +40,11 @@  discard block
 block discarded – undo
40 40
 			'StringHash' => CORE_LIBRARY_PATH . 'StringHash.php',
41 41
 			'Upload' => CORE_LIBRARY_PATH . 'Upload.php',
42 42
 		);
43
-		if(isset($classesMap[$class])){
44
-			if(file_exists($classesMap[$class])){
43
+		if (isset($classesMap[$class])) {
44
+			if (file_exists($classesMap[$class])) {
45 45
 				require_once $classesMap[$class];
46 46
 			}
47
-			else{
47
+			else {
48 48
 				echo 'File for class ' . $class . ' not found';
49 49
 			}
50 50
 		}
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -43,8 +43,7 @@
 block discarded – undo
43 43
 		if(isset($classesMap[$class])){
44 44
 			if(file_exists($classesMap[$class])){
45 45
 				require_once $classesMap[$class];
46
-			}
47
-			else{
46
+			} else{
48 47
 				echo 'File for class ' . $class . ' not found';
49 48
 			}
50 49
 		}
Please login to merge, or discard this patch.
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -1,54 +1,54 @@
 block discarded – undo
1 1
 <?php
2
-	//Autoload function
3
-	function tests_autoload($class){
4
-		$classesMap = array(
5
-			//Caches
6
-			'ApcCache' => CORE_CLASSES_CACHE_PATH . 'ApcCache.php',
7
-			'CacheInterface' => CORE_CLASSES_CACHE_PATH . 'CacheInterface.php',
8
-			'FileCache' => CORE_CLASSES_CACHE_PATH . 'FileCache.php',
9
-			//models
10
-			'DBSessionHandlerModel' => CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php',
11
-			'Model' => CORE_CLASSES_MODEL_PATH . 'Model.php',
12
-			//Core classes
13
-			'Config' => CORE_CLASSES_PATH . 'Config.php',
14
-			'Controller' => CORE_CLASSES_PATH . 'Controller.php',
15
-			'Database' => CORE_CLASSES_DATABASE_PATH . 'Database.php',
16
-			'DatabaseQueryBuilder' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryBuilder.php',
17
-			'DatabaseQueryResult' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryResult.php',
18
-			'DatabaseQueryRunner' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryRunner.php',
19
-			'DBSessionHandler' => CORE_CLASSES_PATH . 'DBSessionHandler.php',
20
-			'EventInfo' => CORE_CLASSES_PATH . 'EventInfo.php',
21
-			'EventDispatcher' => CORE_CLASSES_PATH . 'EventDispatcher.php',
22
-			'Lang' => CORE_CLASSES_PATH . 'Lang.php',
23
-			'Loader' => CORE_CLASSES_PATH . 'Loader.php',
24
-			'Log' => CORE_CLASSES_PATH . 'Log.php',
25
-			'Module' => CORE_CLASSES_PATH . 'Module.php',
26
-			'Request' => CORE_CLASSES_PATH . 'Request.php',
27
-			'Response' => CORE_CLASSES_PATH . 'Response.php',
28
-			'Router' => CORE_CLASSES_PATH . 'Router.php',
29
-			'Security' => CORE_CLASSES_PATH . 'Security.php',
30
-			'Session' => CORE_CLASSES_PATH . 'Session.php',
31
-			'Url' => CORE_CLASSES_PATH . 'Url.php',
32
-			//Core libraries
33
-			'Assets' => CORE_LIBRARY_PATH . 'Assets.php',
34
-			'Benchmark' => CORE_LIBRARY_PATH . 'Benchmark.php',
35
-			'Browser' => CORE_LIBRARY_PATH . 'Browser.php',
36
-			'Cookie' => CORE_LIBRARY_PATH . 'Cookie.php',
37
-			'Email' => CORE_LIBRARY_PATH . 'Email.php',
38
-			'Form' => CORE_LIBRARY_PATH . 'Form.php',
39
-			'FormValidation' => CORE_LIBRARY_PATH . 'FormValidation.php',
40
-			'Html' => CORE_LIBRARY_PATH . 'Html.php',
41
-			'Pagination' => CORE_LIBRARY_PATH . 'Pagination.php',
42
-			'PDF' => CORE_LIBRARY_PATH . 'PDF.php',
43
-			'StringHash' => CORE_LIBRARY_PATH . 'StringHash.php',
44
-			'Upload' => CORE_LIBRARY_PATH . 'Upload.php',
45
-		);
46
-		if(isset($classesMap[$class])){
47
-			if(file_exists($classesMap[$class])){
48
-				require_once $classesMap[$class];
49
-			}
50
-			else{
51
-				echo 'File for class ' . $class . ' not found';
52
-			}
53
-		}
54
-	}
55 2
\ No newline at end of file
3
+    //Autoload function
4
+    function tests_autoload($class){
5
+        $classesMap = array(
6
+            //Caches
7
+            'ApcCache' => CORE_CLASSES_CACHE_PATH . 'ApcCache.php',
8
+            'CacheInterface' => CORE_CLASSES_CACHE_PATH . 'CacheInterface.php',
9
+            'FileCache' => CORE_CLASSES_CACHE_PATH . 'FileCache.php',
10
+            //models
11
+            'DBSessionHandlerModel' => CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php',
12
+            'Model' => CORE_CLASSES_MODEL_PATH . 'Model.php',
13
+            //Core classes
14
+            'Config' => CORE_CLASSES_PATH . 'Config.php',
15
+            'Controller' => CORE_CLASSES_PATH . 'Controller.php',
16
+            'Database' => CORE_CLASSES_DATABASE_PATH . 'Database.php',
17
+            'DatabaseQueryBuilder' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryBuilder.php',
18
+            'DatabaseQueryResult' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryResult.php',
19
+            'DatabaseQueryRunner' => CORE_CLASSES_DATABASE_PATH . 'DatabaseQueryRunner.php',
20
+            'DBSessionHandler' => CORE_CLASSES_PATH . 'DBSessionHandler.php',
21
+            'EventInfo' => CORE_CLASSES_PATH . 'EventInfo.php',
22
+            'EventDispatcher' => CORE_CLASSES_PATH . 'EventDispatcher.php',
23
+            'Lang' => CORE_CLASSES_PATH . 'Lang.php',
24
+            'Loader' => CORE_CLASSES_PATH . 'Loader.php',
25
+            'Log' => CORE_CLASSES_PATH . 'Log.php',
26
+            'Module' => CORE_CLASSES_PATH . 'Module.php',
27
+            'Request' => CORE_CLASSES_PATH . 'Request.php',
28
+            'Response' => CORE_CLASSES_PATH . 'Response.php',
29
+            'Router' => CORE_CLASSES_PATH . 'Router.php',
30
+            'Security' => CORE_CLASSES_PATH . 'Security.php',
31
+            'Session' => CORE_CLASSES_PATH . 'Session.php',
32
+            'Url' => CORE_CLASSES_PATH . 'Url.php',
33
+            //Core libraries
34
+            'Assets' => CORE_LIBRARY_PATH . 'Assets.php',
35
+            'Benchmark' => CORE_LIBRARY_PATH . 'Benchmark.php',
36
+            'Browser' => CORE_LIBRARY_PATH . 'Browser.php',
37
+            'Cookie' => CORE_LIBRARY_PATH . 'Cookie.php',
38
+            'Email' => CORE_LIBRARY_PATH . 'Email.php',
39
+            'Form' => CORE_LIBRARY_PATH . 'Form.php',
40
+            'FormValidation' => CORE_LIBRARY_PATH . 'FormValidation.php',
41
+            'Html' => CORE_LIBRARY_PATH . 'Html.php',
42
+            'Pagination' => CORE_LIBRARY_PATH . 'Pagination.php',
43
+            'PDF' => CORE_LIBRARY_PATH . 'PDF.php',
44
+            'StringHash' => CORE_LIBRARY_PATH . 'StringHash.php',
45
+            'Upload' => CORE_LIBRARY_PATH . 'Upload.php',
46
+        );
47
+        if(isset($classesMap[$class])){
48
+            if(file_exists($classesMap[$class])){
49
+                require_once $classesMap[$class];
50
+            }
51
+            else{
52
+                echo 'File for class ' . $class . ' not found';
53
+            }
54
+        }
55
+    }
56 56
\ No newline at end of file
Please login to merge, or discard this patch.
core/common.php 3 patches
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -53,14 +53,14 @@  discard block
 block discarded – undo
53 53
 		//put the first letter of class to upper case 
54 54
 		$class = ucfirst($class);
55 55
 		static $classes = array();
56
-		if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log'){
56
+		if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log') {
57 57
 			return $classes[$class];
58 58
 		}
59 59
 		$found = false;
60 60
 		foreach (array(ROOT_PATH, CORE_PATH) as $path) {
61 61
 			$file = $path . $dir . '/' . $class . '.php';
62
-			if (file_exists($file)){
63
-				if (class_exists($class, false) === false){
62
+			if (file_exists($file)) {
63
+				if (class_exists($class, false) === false) {
64 64
 					require_once $file;
65 65
 				}
66 66
 				//already found
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 				break;
69 69
 			}
70 70
 		}
71
-		if (! $found){
71
+		if (!$found) {
72 72
 			//can't use show_error() at this time because some dependencies not yet loaded
73 73
 			set_http_status_header(503);
74 74
 			echo 'Cannot find the class [' . $class . ']';
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 		/*
79 79
 		   TODO use the best method to get the Log instance
80 80
 		 */
81
-		if ($class == 'Log'){
81
+		if ($class == 'Log') {
82 82
 			//can't use the instruction like "return new Log()" 
83 83
 			//because we need return the reference instance of the loaded class.
84 84
 			$log = new Log();
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 	 */
103 103
 	function & class_loaded($class = null){
104 104
 		static $list = array();
105
-		if ($class !== null){
105
+		if ($class !== null) {
106 106
 			$list[strtolower($class)] = $class;
107 107
 		}
108 108
 		return $list;
@@ -117,14 +117,14 @@  discard block
 block discarded – undo
117 117
 	 */
118 118
 	function & load_configurations(array $overwrite_values = array()){
119 119
 		static $config;
120
-		if (empty($config)){
120
+		if (empty($config)) {
121 121
 			$file = CONFIG_PATH . 'config.php';
122 122
 			$found = false;
123
-			if (file_exists($file)){
123
+			if (file_exists($file)) {
124 124
 				require_once $file;
125 125
 				$found = true;
126 126
 			}
127
-			if (! $found){
127
+			if (!$found) {
128 128
 				set_http_status_header(503);
129 129
 				echo 'Unable to find the configuration file [' . $file . ']';
130 130
 				die();
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 	 * 
145 145
 	 * @return mixed          the config value
146 146
 	 */
147
-	function get_config($key, $default = null){
147
+	function get_config($key, $default = null) {
148 148
 		static $cfg;
149
-		if (empty($cfg)){
149
+		if (empty($cfg)) {
150 150
 			$cfg[0] = & load_configurations();
151 151
 		}
152 152
 		return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
@@ -160,9 +160,9 @@  discard block
 block discarded – undo
160 160
 	 * 
161 161
 	 * @codeCoverageIgnore
162 162
 	 */
163
-	function save_to_log($level, $message, $logger = null){
164
-		$log =& class_loader('Log', 'classes');
165
-		if ($logger){
163
+	function save_to_log($level, $message, $logger = null) {
164
+		$log = & class_loader('Log', 'classes');
165
+		if ($logger) {
166 166
 			$log->setLogger($logger);
167 167
 		}
168 168
 		$log->writeLog($message, $level);
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
 	 * 
176 176
 	 * @codeCoverageIgnore
177 177
 	 */
178
-	function set_http_status_header($code = 200, $text = null){
179
-		if (empty($text)){
178
+	function set_http_status_header($code = 200, $text = null) {
179
+		if (empty($text)) {
180 180
 			$http_status = array(
181 181
 								100 => 'Continue',
182 182
 								101 => 'Switching Protocols',
@@ -224,18 +224,18 @@  discard block
 block discarded – undo
224 224
 								504 => 'Gateway Timeout',
225 225
 								505 => 'HTTP Version Not Supported',
226 226
 							);
227
-			if (isset($http_status[$code])){
227
+			if (isset($http_status[$code])) {
228 228
 				$text = $http_status[$code];
229 229
 			}
230
-			else{
230
+			else {
231 231
 				show_error('No HTTP status text found for your code please check it.');
232 232
 			}
233 233
 		}
234 234
 		
235
-		if (strpos(php_sapi_name(), 'cgi') === 0){
235
+		if (strpos(php_sapi_name(), 'cgi') === 0) {
236 236
 			header('Status: ' . $code . ' ' . $text, TRUE);
237 237
 		}
238
-		else{
238
+		else {
239 239
 			$proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240 240
 			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241 241
 		}
@@ -250,13 +250,13 @@  discard block
 block discarded – undo
250 250
 	 *  
251 251
 	 *  @codeCoverageIgnore
252 252
 	 */
253
-	function show_error($msg, $title = 'error', $logging = true){
253
+	function show_error($msg, $title = 'error', $logging = true) {
254 254
 		$title = strtoupper($title);
255 255
 		$data = array();
256 256
 		$data['error'] = $msg;
257 257
 		$data['title'] = $title;
258
-		if ($logging){
259
-			save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
258
+		if ($logging) {
259
+			save_to_log('error', '[' . $title . '] ' . strip_tags($msg), 'GLOBAL::ERROR');
260 260
 		}
261 261
 		$response = & class_loader('Response', 'classes');
262 262
 		$response->sendError($data);
@@ -270,18 +270,18 @@  discard block
 block discarded – undo
270 270
 	 *  
271 271
 	 *  @return boolean true if the web server uses the https protocol, false if not.
272 272
 	 */
273
-	function is_https(){
273
+	function is_https() {
274 274
 		/*
275 275
 		* some servers pass the "HTTPS" parameter in the server variable,
276 276
 		* if is the case, check if the value is "on", "true", "1".
277 277
 		*/
278
-		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
278
+		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
279 279
 			return true;
280 280
 		}
281
-		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
281
+		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
282 282
 			return true;
283 283
 		}
284
-		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
284
+		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
285 285
 			return true;
286 286
 		}
287 287
 		return false;
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 	 *  
297 297
 	 *  @return boolean true if is a valid URL address or false.
298 298
 	 */
299
-	function is_url($url){
299
+	function is_url($url) {
300 300
 		return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
301 301
 	}
302 302
 	
@@ -306,8 +306,8 @@  discard block
 block discarded – undo
306 306
 	 *  @param string $controllerClass the controller class name to be loaded
307 307
 	 *  @codeCoverageIgnore
308 308
 	 */
309
-	function autoload_controller($controllerClass){
310
-		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
309
+	function autoload_controller($controllerClass) {
310
+		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')) {
311 311
 			require_once $path;
312 312
 		}
313 313
 	}
@@ -321,11 +321,11 @@  discard block
 block discarded – undo
321 321
 	 *  
322 322
 	 *  @return boolean
323 323
 	 */
324
-	function php_exception_handler($ex){
325
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326
-			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
324
+	function php_exception_handler($ex) {
325
+		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
326
+			show_error('An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327 327
 		}
328
-		else{
328
+		else {
329 329
 			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330 330
 		}
331 331
 		return true;
@@ -342,16 +342,16 @@  discard block
 block discarded – undo
342 342
 	 *  
343 343
 	 *  @return boolean	
344 344
 	 */
345
-	function php_error_handler($errno , $errstr, $errfile , $errline){
345
+	function php_error_handler($errno, $errstr, $errfile, $errline) {
346 346
 		$isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
347
-		if ($isError){
347
+		if ($isError) {
348 348
 			set_http_status_header(500);
349 349
 		}
350
-		if (! (error_reporting() & $errno)) {
350
+		if (!(error_reporting() & $errno)) {
351 351
 			save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
352 352
 			return;
353 353
 		}
354
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
354
+		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) {
355 355
 			$errorType = 'error';
356 356
 			switch ($errno) {
357 357
 				case E_USER_ERROR:
@@ -367,9 +367,9 @@  discard block
 block discarded – undo
367 367
 					$errorType = 'error';
368 368
 					break;
369 369
 			}
370
-			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
370
+			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline . '</b> raison : ' . $errstr, 'PHP ' . $errorType);
371 371
 		}
372
-		if ($isError){
372
+		if ($isError) {
373 373
 			die();
374 374
 		}
375 375
 		return true;
@@ -379,10 +379,10 @@  discard block
 block discarded – undo
379 379
 	 * This function is used to run in shutdown situation of the script
380 380
 	 * @codeCoverageIgnore
381 381
 	 */
382
-	function php_shudown_handler(){
382
+	function php_shudown_handler() {
383 383
 		$lastError = error_get_last();
384 384
 		if (isset($lastError) &&
385
-			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
385
+			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))) {
386 386
 			php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
387 387
 		}
388 388
 	}
@@ -400,11 +400,11 @@  discard block
 block discarded – undo
400 400
 	 *   
401 401
 	 *  @return string string of the HTML attribute.
402 402
 	 */
403
-	function attributes_to_string(array $attributes){
403
+	function attributes_to_string(array $attributes) {
404 404
 		$str = ' ';
405 405
 		//we check that the array passed as an argument is not empty.
406
-		if (! empty($attributes)){
407
-			foreach($attributes as $key => $value){
406
+		if (!empty($attributes)) {
407
+			foreach ($attributes as $key => $value) {
408 408
 				$key = trim(htmlspecialchars($key));
409 409
 				$value = trim(htmlspecialchars($value));
410 410
 				/*
@@ -414,10 +414,10 @@  discard block
 block discarded – undo
414 414
 				* 	$attr = array('placeholder' => 'I am a "puple"')
415 415
 				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
416 416
 				 */
417
-				if ($value && strpos('"', $value) !== false){
417
+				if ($value && strpos('"', $value) !== false) {
418 418
 					$value = addslashes($value);
419 419
 				}
420
-				$str .= $key.' = "'.$value.'" ';
420
+				$str .= $key . ' = "' . $value . '" ';
421 421
 			}
422 422
 		}
423 423
 		//remove the space after using rtrim()
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 	*
434 434
 	* @return string the stringfy value
435 435
 	*/
436
-	function stringfy_vars($var){
436
+	function stringfy_vars($var) {
437 437
 		return print_r($var, true);
438 438
 	}
439 439
 
@@ -444,18 +444,18 @@  discard block
 block discarded – undo
444 444
 	 * 
445 445
 	 * @return mixed   the sanitize value
446 446
 	 */
447
-	function clean_input($str){
448
-		if (is_array($str)){
447
+	function clean_input($str) {
448
+		if (is_array($str)) {
449 449
 			$str = array_map('clean_input', $str);
450 450
 		}
451
-		else if (is_object($str)){
451
+		else if (is_object($str)) {
452 452
 			$obj = $str;
453 453
 			foreach ($str as $var => $value) {
454 454
 				$obj->$var = clean_input($value);
455 455
 			}
456 456
 			$str = $obj;
457 457
 		}
458
-		else{
458
+		else {
459 459
 			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460 460
 		}
461 461
 		return $str;
@@ -473,11 +473,11 @@  discard block
 block discarded – undo
473 473
 	 * 
474 474
 	 * @return string the string with the hidden part.
475 475
 	 */
476
-	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
476
+	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*') {
477 477
 		//get the string length
478 478
 		$len = strlen($str);
479 479
 		//if str is empty
480
-		if ($len <= 0){
480
+		if ($len <= 0) {
481 481
 			return str_repeat($hiddenChar, 6);
482 482
 		}
483 483
 		//if the length is less than startCount and endCount
@@ -485,14 +485,14 @@  discard block
 block discarded – undo
485 485
 		//or startCount is negative or endCount is negative
486 486
 		//return the full string hidden
487 487
 		
488
-		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
488
+		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)) {
489 489
 			return str_repeat($hiddenChar, $len);
490 490
 		}
491 491
 		//the start non hidden string
492 492
 		$startNonHiddenStr = substr($str, 0, $startCount);
493 493
 		//the end non hidden string
494 494
 		$endNonHiddenStr = null;
495
-		if ($endCount > 0){
495
+		if ($endCount > 0) {
496 496
 			$endNonHiddenStr = substr($str, - $endCount);
497 497
 		}
498 498
 		//the hidden string
@@ -505,40 +505,40 @@  discard block
 block discarded – undo
505 505
 	 * This function is used to set the initial session config regarding the configuration
506 506
 	 * @codeCoverageIgnore
507 507
 	 */
508
-	function set_session_config(){
508
+	function set_session_config() {
509 509
 		//$_SESSION is not available on cli mode 
510
-		if (! IS_CLI){
511
-			$logger =& class_loader('Log', 'classes');
510
+		if (!IS_CLI) {
511
+			$logger = & class_loader('Log', 'classes');
512 512
 			$logger->setLogger('PHPSession');
513 513
 			//set session params
514 514
 			$sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
515 515
 			$sessionName = get_config('session_name');
516
-			if ($sessionName){
516
+			if ($sessionName) {
517 517
 				session_name($sessionName);
518 518
 			}
519 519
 			$logger->info('Session handler: ' . $sessionHandler);
520 520
 			$logger->info('Session name: ' . $sessionName);
521 521
 
522
-			if ($sessionHandler == 'files'){
522
+			if ($sessionHandler == 'files') {
523 523
 				$sessionSavePath = get_config('session_save_path');
524
-				if ($sessionSavePath){
525
-					if (! is_dir($sessionSavePath)){
524
+				if ($sessionSavePath) {
525
+					if (!is_dir($sessionSavePath)) {
526 526
 						mkdir($sessionSavePath, 1773);
527 527
 					}
528 528
 					session_save_path($sessionSavePath);
529 529
 					$logger->info('Session save path: ' . $sessionSavePath);
530 530
 				}
531 531
 			}
532
-			else if ($sessionHandler == 'database'){
532
+			else if ($sessionHandler == 'database') {
533 533
 				//load database session handle library
534 534
 				//Database Session handler Model
535 535
 				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
536 536
 
537
-				$DBS =& class_loader('DBSessionHandler', 'classes');
537
+				$DBS = & class_loader('DBSessionHandler', 'classes');
538 538
 				session_set_save_handler($DBS, true);
539 539
 				$logger->info('session save path: ' . get_config('session_save_path'));
540 540
 			}
541
-			else{
541
+			else {
542 542
 				show_error('Invalid session handler configuration');
543 543
 			}
544 544
 			$lifetime = get_config('session_cookie_lifetime', 0);
@@ -561,9 +561,9 @@  discard block
 block discarded – undo
561 561
 			$logger->info('Session lifetime: ' . $lifetime);
562 562
 			$logger->info('Session cookie path: ' . $path);
563 563
 			$logger->info('Session domain: ' . $domain);
564
-			$logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
564
+			$logger->info('Session is secure: ' . ($secure ? 'TRUE' : 'FALSE'));
565 565
 			
566
-			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
566
+			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
567 567
 				$logger->info('Session not yet start, start it now');
568 568
 				session_start();
569 569
 			}
Please login to merge, or discard this patch.
Braces   +9 added lines, -18 removed lines patch added patch discarded remove patch
@@ -226,16 +226,14 @@  discard block
 block discarded – undo
226 226
 							);
227 227
 			if (isset($http_status[$code])){
228 228
 				$text = $http_status[$code];
229
-			}
230
-			else{
229
+			} else{
231 230
 				show_error('No HTTP status text found for your code please check it.');
232 231
 			}
233 232
 		}
234 233
 		
235 234
 		if (strpos(php_sapi_name(), 'cgi') === 0){
236 235
 			header('Status: ' . $code . ' ' . $text, TRUE);
237
-		}
238
-		else{
236
+		} else{
239 237
 			$proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240 238
 			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241 239
 		}
@@ -277,11 +275,9 @@  discard block
 block discarded – undo
277 275
 		*/
278 276
 		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
279 277
 			return true;
280
-		}
281
-		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
278
+		} else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
282 279
 			return true;
283
-		}
284
-		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
280
+		} else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
285 281
 			return true;
286 282
 		}
287 283
 		return false;
@@ -324,8 +320,7 @@  discard block
 block discarded – undo
324 320
 	function php_exception_handler($ex){
325 321
 		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326 322
 			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327
-		}
328
-		else{
323
+		} else{
329 324
 			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330 325
 		}
331 326
 		return true;
@@ -447,15 +442,13 @@  discard block
 block discarded – undo
447 442
 	function clean_input($str){
448 443
 		if (is_array($str)){
449 444
 			$str = array_map('clean_input', $str);
450
-		}
451
-		else if (is_object($str)){
445
+		} else if (is_object($str)){
452 446
 			$obj = $str;
453 447
 			foreach ($str as $var => $value) {
454 448
 				$obj->$var = clean_input($value);
455 449
 			}
456 450
 			$str = $obj;
457
-		}
458
-		else{
451
+		} else{
459 452
 			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460 453
 		}
461 454
 		return $str;
@@ -528,8 +521,7 @@  discard block
 block discarded – undo
528 521
 					session_save_path($sessionSavePath);
529 522
 					$logger->info('Session save path: ' . $sessionSavePath);
530 523
 				}
531
-			}
532
-			else if ($sessionHandler == 'database'){
524
+			} else if ($sessionHandler == 'database'){
533 525
 				//load database session handle library
534 526
 				//Database Session handler Model
535 527
 				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
@@ -537,8 +529,7 @@  discard block
 block discarded – undo
537 529
 				$DBS =& class_loader('DBSessionHandler', 'classes');
538 530
 				session_set_save_handler($DBS, true);
539 531
 				$logger->info('session save path: ' . get_config('session_save_path'));
540
-			}
541
-			else{
532
+			} else{
542 533
 				show_error('Invalid session handler configuration');
543 534
 			}
544 535
 			$lifetime = get_config('session_cookie_lifetime', 0);
Please login to merge, or discard this patch.
Indentation   +536 added lines, -536 removed lines patch added patch discarded remove patch
@@ -1,585 +1,585 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') || exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') || exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	/**
28
-	 *  @file common.php
29
-	 *  
30
-	 *  Contains most of the commons functions used by the system
31
-	 *  
32
-	 *  @package	core
33
-	 *  @author	Tony NGUEREZA
34
-	 *  @copyright	Copyright (c) 2017
35
-	 *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
-	 *  @link	http://www.iacademy.cf
37
-	 *  @version 1.0.0
38
-	 *  @filesource
39
-	 */
27
+    /**
28
+     *  @file common.php
29
+     *  
30
+     *  Contains most of the commons functions used by the system
31
+     *  
32
+     *  @package	core
33
+     *  @author	Tony NGUEREZA
34
+     *  @copyright	Copyright (c) 2017
35
+     *  @license	https://opensource.org/licenses/gpl-3.0.html GNU GPL License (GPL)
36
+     *  @link	http://www.iacademy.cf
37
+     *  @version 1.0.0
38
+     *  @filesource
39
+     */
40 40
 	
41 41
 
42
-	/**
43
-	 * This function is the class loader helper is used if the library "Loader" not yet loaded
44
-	 * he load the class once
45
-	 * @param  string $class  the class name to be loaded
46
-	 * @param  string $dir    the directory where to find the class
47
-	 * @param  mixed $params the parameter to pass as argument to the constructor of the class
48
-	 * @codeCoverageIgnore
49
-	 * 
50
-	 * @return object         the instance of the loaded class
51
-	 */
52
-	function & class_loader($class, $dir = 'libraries', $params = null){
53
-		//put the first letter of class to upper case 
54
-		$class = ucfirst($class);
55
-		static $classes = array();
56
-		if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log'){
57
-			return $classes[$class];
58
-		}
59
-		$found = false;
60
-		foreach (array(ROOT_PATH, CORE_PATH) as $path) {
61
-			$file = $path . $dir . '/' . $class . '.php';
62
-			if (file_exists($file)){
63
-				if (class_exists($class, false) === false){
64
-					require_once $file;
65
-				}
66
-				//already found
67
-				$found = true;
68
-				break;
69
-			}
70
-		}
71
-		if (! $found){
72
-			//can't use show_error() at this time because some dependencies not yet loaded
73
-			set_http_status_header(503);
74
-			echo 'Cannot find the class [' . $class . ']';
75
-			die();
76
-		}
42
+    /**
43
+     * This function is the class loader helper is used if the library "Loader" not yet loaded
44
+     * he load the class once
45
+     * @param  string $class  the class name to be loaded
46
+     * @param  string $dir    the directory where to find the class
47
+     * @param  mixed $params the parameter to pass as argument to the constructor of the class
48
+     * @codeCoverageIgnore
49
+     * 
50
+     * @return object         the instance of the loaded class
51
+     */
52
+    function & class_loader($class, $dir = 'libraries', $params = null){
53
+        //put the first letter of class to upper case 
54
+        $class = ucfirst($class);
55
+        static $classes = array();
56
+        if (isset($classes[$class]) /*hack for duplicate log Logger name*/ && $class != 'Log'){
57
+            return $classes[$class];
58
+        }
59
+        $found = false;
60
+        foreach (array(ROOT_PATH, CORE_PATH) as $path) {
61
+            $file = $path . $dir . '/' . $class . '.php';
62
+            if (file_exists($file)){
63
+                if (class_exists($class, false) === false){
64
+                    require_once $file;
65
+                }
66
+                //already found
67
+                $found = true;
68
+                break;
69
+            }
70
+        }
71
+        if (! $found){
72
+            //can't use show_error() at this time because some dependencies not yet loaded
73
+            set_http_status_header(503);
74
+            echo 'Cannot find the class [' . $class . ']';
75
+            die();
76
+        }
77 77
 		
78
-		/*
78
+        /*
79 79
 		   TODO use the best method to get the Log instance
80 80
 		 */
81
-		if ($class == 'Log'){
82
-			//can't use the instruction like "return new Log()" 
83
-			//because we need return the reference instance of the loaded class.
84
-			$log = new Log();
85
-			return $log;
86
-		}
87
-		//track of loaded classes
88
-		class_loaded($class);
81
+        if ($class == 'Log'){
82
+            //can't use the instruction like "return new Log()" 
83
+            //because we need return the reference instance of the loaded class.
84
+            $log = new Log();
85
+            return $log;
86
+        }
87
+        //track of loaded classes
88
+        class_loaded($class);
89 89
 		
90
-		//record the class instance
91
-		$classes[$class] = isset($params) ? new $class($params) : new $class();
90
+        //record the class instance
91
+        $classes[$class] = isset($params) ? new $class($params) : new $class();
92 92
 		
93
-		return $classes[$class];
94
-	}
93
+        return $classes[$class];
94
+    }
95 95
 
96
-	/**
97
-	 * This function is the helper to record the loaded classes
98
-	 * @param  string $class the loaded class name
99
-	 * @codeCoverageIgnore
100
-	 * 
101
-	 * @return array        the list of the loaded classes
102
-	 */
103
-	function & class_loaded($class = null){
104
-		static $list = array();
105
-		if ($class !== null){
106
-			$list[strtolower($class)] = $class;
107
-		}
108
-		return $list;
109
-	}
96
+    /**
97
+     * This function is the helper to record the loaded classes
98
+     * @param  string $class the loaded class name
99
+     * @codeCoverageIgnore
100
+     * 
101
+     * @return array        the list of the loaded classes
102
+     */
103
+    function & class_loaded($class = null){
104
+        static $list = array();
105
+        if ($class !== null){
106
+            $list[strtolower($class)] = $class;
107
+        }
108
+        return $list;
109
+    }
110 110
 
111
-	/**
112
-	 * This function is used to load the configurations in the case the "Config" library not yet loaded
113
-	 * @param  array  $overwrite_values if need overwrite the existing configuration
114
-	 * @codeCoverageIgnore
115
-	 * 
116
-	 * @return array                   the configurations values
117
-	 */
118
-	function & load_configurations(array $overwrite_values = array()){
119
-		static $config;
120
-		if (empty($config)){
121
-			$file = CONFIG_PATH . 'config.php';
122
-			$found = false;
123
-			if (file_exists($file)){
124
-				require_once $file;
125
-				$found = true;
126
-			}
127
-			if (! $found){
128
-				set_http_status_header(503);
129
-				echo 'Unable to find the configuration file [' . $file . ']';
130
-				die();
131
-			}
132
-		}
133
-		foreach ($overwrite_values as $key => $value) {
134
-			$config[$key] = $value;
135
-		}
136
-		return $config;
137
-	}
111
+    /**
112
+     * This function is used to load the configurations in the case the "Config" library not yet loaded
113
+     * @param  array  $overwrite_values if need overwrite the existing configuration
114
+     * @codeCoverageIgnore
115
+     * 
116
+     * @return array                   the configurations values
117
+     */
118
+    function & load_configurations(array $overwrite_values = array()){
119
+        static $config;
120
+        if (empty($config)){
121
+            $file = CONFIG_PATH . 'config.php';
122
+            $found = false;
123
+            if (file_exists($file)){
124
+                require_once $file;
125
+                $found = true;
126
+            }
127
+            if (! $found){
128
+                set_http_status_header(503);
129
+                echo 'Unable to find the configuration file [' . $file . ']';
130
+                die();
131
+            }
132
+        }
133
+        foreach ($overwrite_values as $key => $value) {
134
+            $config[$key] = $value;
135
+        }
136
+        return $config;
137
+    }
138 138
 
139
-	/**
140
-	 * This function is the helper to get the config value in case the "Config" library not yet loaded
141
-	 * @param  string $key     the config item to get the vale
142
-	 * @param  mixed $default the default value to return if can't find the config item in the configuration
143
-	 * @test
144
-	 * 
145
-	 * @return mixed          the config value
146
-	 */
147
-	function get_config($key, $default = null){
148
-		static $cfg;
149
-		if (empty($cfg)){
150
-			$cfg[0] = & load_configurations();
151
-		}
152
-		return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
153
-	}
139
+    /**
140
+     * This function is the helper to get the config value in case the "Config" library not yet loaded
141
+     * @param  string $key     the config item to get the vale
142
+     * @param  mixed $default the default value to return if can't find the config item in the configuration
143
+     * @test
144
+     * 
145
+     * @return mixed          the config value
146
+     */
147
+    function get_config($key, $default = null){
148
+        static $cfg;
149
+        if (empty($cfg)){
150
+            $cfg[0] = & load_configurations();
151
+        }
152
+        return array_key_exists($key, $cfg[0]) ? $cfg[0][$key] : $default;
153
+    }
154 154
 
155
-	/**
156
-	 * This function is a helper to logging message
157
-	 * @param  string $level   the log level "ERROR", "DEBUG", "INFO", etc.
158
-	 * @param  string $message the log message to be saved
159
-	 * @param  string $logger  the logger to use if is set
160
-	 * 
161
-	 * @codeCoverageIgnore
162
-	 */
163
-	function save_to_log($level, $message, $logger = null){
164
-		$log =& class_loader('Log', 'classes');
165
-		if ($logger){
166
-			$log->setLogger($logger);
167
-		}
168
-		$log->writeLog($message, $level);
169
-	}
155
+    /**
156
+     * This function is a helper to logging message
157
+     * @param  string $level   the log level "ERROR", "DEBUG", "INFO", etc.
158
+     * @param  string $message the log message to be saved
159
+     * @param  string $logger  the logger to use if is set
160
+     * 
161
+     * @codeCoverageIgnore
162
+     */
163
+    function save_to_log($level, $message, $logger = null){
164
+        $log =& class_loader('Log', 'classes');
165
+        if ($logger){
166
+            $log->setLogger($logger);
167
+        }
168
+        $log->writeLog($message, $level);
169
+    }
170 170
 
171
-	/**
172
-	 * Set the HTTP status header
173
-	 * @param integer $code the HTTP status code
174
-	 * @param string  $text the HTTP status text
175
-	 * 
176
-	 * @codeCoverageIgnore
177
-	 */
178
-	function set_http_status_header($code = 200, $text = null){
179
-		if (empty($text)){
180
-			$http_status = array(
181
-								100 => 'Continue',
182
-								101 => 'Switching Protocols',
171
+    /**
172
+     * Set the HTTP status header
173
+     * @param integer $code the HTTP status code
174
+     * @param string  $text the HTTP status text
175
+     * 
176
+     * @codeCoverageIgnore
177
+     */
178
+    function set_http_status_header($code = 200, $text = null){
179
+        if (empty($text)){
180
+            $http_status = array(
181
+                                100 => 'Continue',
182
+                                101 => 'Switching Protocols',
183 183
 
184
-								200 => 'OK',
185
-								201 => 'Created',
186
-								202 => 'Accepted',
187
-								203 => 'Non-Authoritative Information',
188
-								204 => 'No Content',
189
-								205 => 'Reset Content',
190
-								206 => 'Partial Content',
184
+                                200 => 'OK',
185
+                                201 => 'Created',
186
+                                202 => 'Accepted',
187
+                                203 => 'Non-Authoritative Information',
188
+                                204 => 'No Content',
189
+                                205 => 'Reset Content',
190
+                                206 => 'Partial Content',
191 191
 
192
-								300 => 'Multiple Choices',
193
-								301 => 'Moved Permanently',
194
-								302 => 'Found',
195
-								303 => 'See Other',
196
-								304 => 'Not Modified',
197
-								305 => 'Use Proxy',
198
-								307 => 'Temporary Redirect',
192
+                                300 => 'Multiple Choices',
193
+                                301 => 'Moved Permanently',
194
+                                302 => 'Found',
195
+                                303 => 'See Other',
196
+                                304 => 'Not Modified',
197
+                                305 => 'Use Proxy',
198
+                                307 => 'Temporary Redirect',
199 199
 
200
-								400 => 'Bad Request',
201
-								401 => 'Unauthorized',
202
-								402 => 'Payment Required',
203
-								403 => 'Forbidden',
204
-								404 => 'Not Found',
205
-								405 => 'Method Not Allowed',
206
-								406 => 'Not Acceptable',
207
-								407 => 'Proxy Authentication Required',
208
-								408 => 'Request Timeout',
209
-								409 => 'Conflict',
210
-								410 => 'Gone',
211
-								411 => 'Length Required',
212
-								412 => 'Precondition Failed',
213
-								413 => 'Request Entity Too Large',
214
-								414 => 'Request-URI Too Long',
215
-								415 => 'Unsupported Media Type',
216
-								416 => 'Requested Range Not Satisfiable',
217
-								417 => 'Expectation Failed',
218
-								418 => 'I\'m a teapot',
200
+                                400 => 'Bad Request',
201
+                                401 => 'Unauthorized',
202
+                                402 => 'Payment Required',
203
+                                403 => 'Forbidden',
204
+                                404 => 'Not Found',
205
+                                405 => 'Method Not Allowed',
206
+                                406 => 'Not Acceptable',
207
+                                407 => 'Proxy Authentication Required',
208
+                                408 => 'Request Timeout',
209
+                                409 => 'Conflict',
210
+                                410 => 'Gone',
211
+                                411 => 'Length Required',
212
+                                412 => 'Precondition Failed',
213
+                                413 => 'Request Entity Too Large',
214
+                                414 => 'Request-URI Too Long',
215
+                                415 => 'Unsupported Media Type',
216
+                                416 => 'Requested Range Not Satisfiable',
217
+                                417 => 'Expectation Failed',
218
+                                418 => 'I\'m a teapot',
219 219
 
220
-								500 => 'Internal Server Error',
221
-								501 => 'Not Implemented',
222
-								502 => 'Bad Gateway',
223
-								503 => 'Service Unavailable',
224
-								504 => 'Gateway Timeout',
225
-								505 => 'HTTP Version Not Supported',
226
-							);
227
-			if (isset($http_status[$code])){
228
-				$text = $http_status[$code];
229
-			}
230
-			else{
231
-				show_error('No HTTP status text found for your code please check it.');
232
-			}
233
-		}
220
+                                500 => 'Internal Server Error',
221
+                                501 => 'Not Implemented',
222
+                                502 => 'Bad Gateway',
223
+                                503 => 'Service Unavailable',
224
+                                504 => 'Gateway Timeout',
225
+                                505 => 'HTTP Version Not Supported',
226
+                            );
227
+            if (isset($http_status[$code])){
228
+                $text = $http_status[$code];
229
+            }
230
+            else{
231
+                show_error('No HTTP status text found for your code please check it.');
232
+            }
233
+        }
234 234
 		
235
-		if (strpos(php_sapi_name(), 'cgi') === 0){
236
-			header('Status: ' . $code . ' ' . $text, TRUE);
237
-		}
238
-		else{
239
-			$proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240
-			header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241
-		}
242
-	}
235
+        if (strpos(php_sapi_name(), 'cgi') === 0){
236
+            header('Status: ' . $code . ' ' . $text, TRUE);
237
+        }
238
+        else{
239
+            $proto = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
240
+            header($proto . ' ' . $code . ' ' . $text, TRUE, $code);
241
+        }
242
+    }
243 243
 
244
-	/**
245
-	 *  This function displays an error message to the user and ends the execution of the script.
246
-	 *  
247
-	 *  @param string $msg the message to display
248
-	 *  @param string $title the message title: "error", "info", "warning", etc.
249
-	 *  @param boolean $logging either to save error in log
250
-	 *  
251
-	 *  @codeCoverageIgnore
252
-	 */
253
-	function show_error($msg, $title = 'error', $logging = true){
254
-		$title = strtoupper($title);
255
-		$data = array();
256
-		$data['error'] = $msg;
257
-		$data['title'] = $title;
258
-		if ($logging){
259
-			save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
260
-		}
261
-		$response = & class_loader('Response', 'classes');
262
-		$response->sendError($data);
263
-		die();
264
-	}
244
+    /**
245
+     *  This function displays an error message to the user and ends the execution of the script.
246
+     *  
247
+     *  @param string $msg the message to display
248
+     *  @param string $title the message title: "error", "info", "warning", etc.
249
+     *  @param boolean $logging either to save error in log
250
+     *  
251
+     *  @codeCoverageIgnore
252
+     */
253
+    function show_error($msg, $title = 'error', $logging = true){
254
+        $title = strtoupper($title);
255
+        $data = array();
256
+        $data['error'] = $msg;
257
+        $data['title'] = $title;
258
+        if ($logging){
259
+            save_to_log('error', '['.$title.'] '.strip_tags($msg), 'GLOBAL::ERROR');
260
+        }
261
+        $response = & class_loader('Response', 'classes');
262
+        $response->sendError($data);
263
+        die();
264
+    }
265 265
 
266
-	/**
267
-	 *  Check whether the protocol used is "https" or not
268
-	 *  That is, the web server is configured to use a secure connection.
269
-	 *  @codeCoverageIgnore
270
-	 *  
271
-	 *  @return boolean true if the web server uses the https protocol, false if not.
272
-	 */
273
-	function is_https(){
274
-		/*
266
+    /**
267
+     *  Check whether the protocol used is "https" or not
268
+     *  That is, the web server is configured to use a secure connection.
269
+     *  @codeCoverageIgnore
270
+     *  
271
+     *  @return boolean true if the web server uses the https protocol, false if not.
272
+     */
273
+    function is_https(){
274
+        /*
275 275
 		* some servers pass the "HTTPS" parameter in the server variable,
276 276
 		* if is the case, check if the value is "on", "true", "1".
277 277
 		*/
278
-		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
279
-			return true;
280
-		}
281
-		else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
282
-			return true;
283
-		}
284
-		else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
285
-			return true;
286
-		}
287
-		return false;
288
-	}
278
+        if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off'){
279
+            return true;
280
+        }
281
+        else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'){
282
+            return true;
283
+        }
284
+        else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off'){
285
+            return true;
286
+        }
287
+        return false;
288
+    }
289 289
 	
290
-	/**
291
-	 *  This function is used to check the URL format of the given string argument. 
292
-	 *  The address is valid if the protocol is http, https, ftp, etc.
293
-	 *
294
-	 *  @param string $url the URL address to check
295
-	 *  @test
296
-	 *  
297
-	 *  @return boolean true if is a valid URL address or false.
298
-	 */
299
-	function is_url($url){
300
-		return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
301
-	}
290
+    /**
291
+     *  This function is used to check the URL format of the given string argument. 
292
+     *  The address is valid if the protocol is http, https, ftp, etc.
293
+     *
294
+     *  @param string $url the URL address to check
295
+     *  @test
296
+     *  
297
+     *  @return boolean true if is a valid URL address or false.
298
+     */
299
+    function is_url($url){
300
+        return preg_match('/^(http|https|ftp):\/\/(.*)/', $url) == 1;
301
+    }
302 302
 	
303
-	/**
304
-	 *  Function defined to load controller
305
-	 *  
306
-	 *  @param string $controllerClass the controller class name to be loaded
307
-	 *  @codeCoverageIgnore
308
-	 */
309
-	function autoload_controller($controllerClass){
310
-		if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
311
-			require_once $path;
312
-		}
313
-	}
303
+    /**
304
+     *  Function defined to load controller
305
+     *  
306
+     *  @param string $controllerClass the controller class name to be loaded
307
+     *  @codeCoverageIgnore
308
+     */
309
+    function autoload_controller($controllerClass){
310
+        if (file_exists($path = APPS_CONTROLLER_PATH . $controllerClass . '.php')){
311
+            require_once $path;
312
+        }
313
+    }
314 314
 	
315
-	/**
316
-	 *  Function defined for handling PHP exception error message, 
317
-	 *  it displays an error message using the function "show_error"
318
-	 *  
319
-	 *  @param object $ex instance of the "Exception" class or a derived class
320
-	 *  @codeCoverageIgnore
321
-	 *  
322
-	 *  @return boolean
323
-	 */
324
-	function php_exception_handler($ex){
325
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326
-			show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327
-		}
328
-		else{
329
-			save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330
-		}
331
-		return true;
332
-	}
315
+    /**
316
+     *  Function defined for handling PHP exception error message, 
317
+     *  it displays an error message using the function "show_error"
318
+     *  
319
+     *  @param object $ex instance of the "Exception" class or a derived class
320
+     *  @codeCoverageIgnore
321
+     *  
322
+     *  @return boolean
323
+     */
324
+    function php_exception_handler($ex){
325
+        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
326
+            show_error('An exception is occured in file '. $ex->getFile() .' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception #' . $ex->getCode());
327
+        }
328
+        else{
329
+            save_to_log('error', 'An exception is occured in file ' . $ex->getFile() . ' at line ' . $ex->getLine() . ' raison : ' . $ex->getMessage(), 'PHP Exception');
330
+        }
331
+        return true;
332
+    }
333 333
 	
334
-	/**
335
-	 *  Function defined for PHP error message handling
336
-	 *  			
337
-	 *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
338
-	 *  @param string $errstr the error message
339
-	 *  @param string $errfile the file where the error occurred
340
-	 *  @param int $errline the line number where the error occurred
341
-	 *  @codeCoverageIgnore
342
-	 *  
343
-	 *  @return boolean	
344
-	 */
345
-	function php_error_handler($errno , $errstr, $errfile , $errline){
346
-		$isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
347
-		if ($isError){
348
-			set_http_status_header(500);
349
-		}
350
-		if (! (error_reporting() & $errno)) {
351
-			save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
352
-			return;
353
-		}
354
-		if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
355
-			$errorType = 'error';
356
-			switch ($errno) {
357
-				case E_USER_ERROR:
358
-					$errorType = 'error';
359
-					break;
360
-				case E_USER_WARNING:
361
-					$errorType = 'warning';
362
-					break;
363
-				case E_USER_NOTICE:
364
-					$errorType = 'notice';
365
-					break;
366
-				default:
367
-					$errorType = 'error';
368
-					break;
369
-			}
370
-			show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
371
-		}
372
-		if ($isError){
373
-			die();
374
-		}
375
-		return true;
376
-	}
334
+    /**
335
+     *  Function defined for PHP error message handling
336
+     *  			
337
+     *  @param int $errno the type of error for example: E_USER_ERROR, E_USER_WARNING, etc.
338
+     *  @param string $errstr the error message
339
+     *  @param string $errfile the file where the error occurred
340
+     *  @param int $errline the line number where the error occurred
341
+     *  @codeCoverageIgnore
342
+     *  
343
+     *  @return boolean	
344
+     */
345
+    function php_error_handler($errno , $errstr, $errfile , $errline){
346
+        $isError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errno) === $errno);
347
+        if ($isError){
348
+            set_http_status_header(500);
349
+        }
350
+        if (! (error_reporting() & $errno)) {
351
+            save_to_log('error', 'An error is occurred in the file ' . $errfile . ' at line ' . $errline . ' raison : ' . $errstr, 'PHP ERROR');
352
+            return;
353
+        }
354
+        if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
355
+            $errorType = 'error';
356
+            switch ($errno) {
357
+                case E_USER_ERROR:
358
+                    $errorType = 'error';
359
+                    break;
360
+                case E_USER_WARNING:
361
+                    $errorType = 'warning';
362
+                    break;
363
+                case E_USER_NOTICE:
364
+                    $errorType = 'notice';
365
+                    break;
366
+                default:
367
+                    $errorType = 'error';
368
+                    break;
369
+            }
370
+            show_error('An error is occurred in the file <b>' . $errfile . '</b> at line <b>' . $errline .'</b> raison : ' . $errstr, 'PHP ' . $errorType);
371
+        }
372
+        if ($isError){
373
+            die();
374
+        }
375
+        return true;
376
+    }
377 377
 
378
-	/**
379
-	 * This function is used to run in shutdown situation of the script
380
-	 * @codeCoverageIgnore
381
-	 */
382
-	function php_shudown_handler(){
383
-		$lastError = error_get_last();
384
-		if (isset($lastError) &&
385
-			($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
386
-			php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
387
-		}
388
-	}
378
+    /**
379
+     * This function is used to run in shutdown situation of the script
380
+     * @codeCoverageIgnore
381
+     */
382
+    function php_shudown_handler(){
383
+        $lastError = error_get_last();
384
+        if (isset($lastError) &&
385
+            ($lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))){
386
+            php_error_handler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
387
+        }
388
+    }
389 389
 
390 390
 
391
-	/**
392
-	 *  Convert array attributes to string
393
-	 *
394
-	 *  This function converts an associative array into HTML attributes.
395
-	 *  For example :
396
-	 *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
397
-	 *  name = "Foo" type = "text"
398
-	 *
399
-	 *  @param array $attributes associative array to convert to a string attribute.
400
-	 *   
401
-	 *  @return string string of the HTML attribute.
402
-	 */
403
-	function attributes_to_string(array $attributes){
404
-		$str = ' ';
405
-		//we check that the array passed as an argument is not empty.
406
-		if (! empty($attributes)){
407
-			foreach($attributes as $key => $value){
408
-				$key = trim(htmlspecialchars($key));
409
-				$value = trim(htmlspecialchars($value));
410
-				/*
391
+    /**
392
+     *  Convert array attributes to string
393
+     *
394
+     *  This function converts an associative array into HTML attributes.
395
+     *  For example :
396
+     *  $a = array('name' => 'Foo', 'type' => 'text'); => produces the following string:
397
+     *  name = "Foo" type = "text"
398
+     *
399
+     *  @param array $attributes associative array to convert to a string attribute.
400
+     *   
401
+     *  @return string string of the HTML attribute.
402
+     */
403
+    function attributes_to_string(array $attributes){
404
+        $str = ' ';
405
+        //we check that the array passed as an argument is not empty.
406
+        if (! empty($attributes)){
407
+            foreach($attributes as $key => $value){
408
+                $key = trim(htmlspecialchars($key));
409
+                $value = trim(htmlspecialchars($value));
410
+                /*
411 411
 				* To predict the case where the string to convert contains the character "
412 412
 				* we check if this is the case we add a slash to solve this problem.
413 413
 				* For example:
414 414
 				* 	$attr = array('placeholder' => 'I am a "puple"')
415 415
 				* 	$str = attributes_to_string($attr); => placeholder = "I am a \"puple\""
416 416
 				 */
417
-				if ($value && strpos('"', $value) !== false){
418
-					$value = addslashes($value);
419
-				}
420
-				$str .= $key.' = "'.$value.'" ';
421
-			}
422
-		}
423
-		//remove the space after using rtrim()
424
-		return rtrim($str);
425
-	}
417
+                if ($value && strpos('"', $value) !== false){
418
+                    $value = addslashes($value);
419
+                }
420
+                $str .= $key.' = "'.$value.'" ';
421
+            }
422
+        }
423
+        //remove the space after using rtrim()
424
+        return rtrim($str);
425
+    }
426 426
 
427 427
 
428
-	/**
429
-	* Function to stringfy PHP variable, useful in debug situation
430
-	*
431
-	* @param mixed $var the variable to stringfy
432
-	* @codeCoverageIgnore
433
-	*
434
-	* @return string the stringfy value
435
-	*/
436
-	function stringfy_vars($var){
437
-		return print_r($var, true);
438
-	}
428
+    /**
429
+     * Function to stringfy PHP variable, useful in debug situation
430
+     *
431
+     * @param mixed $var the variable to stringfy
432
+     * @codeCoverageIgnore
433
+     *
434
+     * @return string the stringfy value
435
+     */
436
+    function stringfy_vars($var){
437
+        return print_r($var, true);
438
+    }
439 439
 
440
-	/**
441
-	 * Clean the user input
442
-	 * @param  mixed $str the value to clean
443
-	 * @test
444
-	 * 
445
-	 * @return mixed   the sanitize value
446
-	 */
447
-	function clean_input($str){
448
-		if (is_array($str)){
449
-			$str = array_map('clean_input', $str);
450
-		}
451
-		else if (is_object($str)){
452
-			$obj = $str;
453
-			foreach ($str as $var => $value) {
454
-				$obj->$var = clean_input($value);
455
-			}
456
-			$str = $obj;
457
-		}
458
-		else{
459
-			$str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460
-		}
461
-		return $str;
462
-	}
440
+    /**
441
+     * Clean the user input
442
+     * @param  mixed $str the value to clean
443
+     * @test
444
+     * 
445
+     * @return mixed   the sanitize value
446
+     */
447
+    function clean_input($str){
448
+        if (is_array($str)){
449
+            $str = array_map('clean_input', $str);
450
+        }
451
+        else if (is_object($str)){
452
+            $obj = $str;
453
+            foreach ($str as $var => $value) {
454
+                $obj->$var = clean_input($value);
455
+            }
456
+            $str = $obj;
457
+        }
458
+        else{
459
+            $str = htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
460
+        }
461
+        return $str;
462
+    }
463 463
 	
464
-	/**
465
-	 * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
466
-	 * Information like credit card number, password, etc.
467
-	 *
468
-	 * @param  string $str the string you want to hide some part
469
-	 * @param  int $startCount the length of non hidden for the beginning char
470
-	 * @param  int $endCount the length of non hidden for the ending char
471
-	 * @param  string $hiddenChar the char used to hide the given string
472
-	 * @test
473
-	 * 
474
-	 * @return string the string with the hidden part.
475
-	 */
476
-	function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
477
-		//get the string length
478
-		$len = strlen($str);
479
-		//if str is empty
480
-		if ($len <= 0){
481
-			return str_repeat($hiddenChar, 6);
482
-		}
483
-		//if the length is less than startCount and endCount
484
-		//or the startCount and endCount length is 0
485
-		//or startCount is negative or endCount is negative
486
-		//return the full string hidden
464
+    /**
465
+     * This function is used to hidden some part of the given string. Helpful if you need hide some confidential 
466
+     * Information like credit card number, password, etc.
467
+     *
468
+     * @param  string $str the string you want to hide some part
469
+     * @param  int $startCount the length of non hidden for the beginning char
470
+     * @param  int $endCount the length of non hidden for the ending char
471
+     * @param  string $hiddenChar the char used to hide the given string
472
+     * @test
473
+     * 
474
+     * @return string the string with the hidden part.
475
+     */
476
+    function string_hidden($str, $startCount = 0, $endCount = 0, $hiddenChar = '*'){
477
+        //get the string length
478
+        $len = strlen($str);
479
+        //if str is empty
480
+        if ($len <= 0){
481
+            return str_repeat($hiddenChar, 6);
482
+        }
483
+        //if the length is less than startCount and endCount
484
+        //or the startCount and endCount length is 0
485
+        //or startCount is negative or endCount is negative
486
+        //return the full string hidden
487 487
 		
488
-		if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
489
-			return str_repeat($hiddenChar, $len);
490
-		}
491
-		//the start non hidden string
492
-		$startNonHiddenStr = substr($str, 0, $startCount);
493
-		//the end non hidden string
494
-		$endNonHiddenStr = null;
495
-		if ($endCount > 0){
496
-			$endNonHiddenStr = substr($str, - $endCount);
497
-		}
498
-		//the hidden string
499
-		$hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
488
+        if ((($startCount + $endCount) > $len) || ($startCount == 0 && $endCount == 0) || ($startCount < 0 || $endCount < 0)){
489
+            return str_repeat($hiddenChar, $len);
490
+        }
491
+        //the start non hidden string
492
+        $startNonHiddenStr = substr($str, 0, $startCount);
493
+        //the end non hidden string
494
+        $endNonHiddenStr = null;
495
+        if ($endCount > 0){
496
+            $endNonHiddenStr = substr($str, - $endCount);
497
+        }
498
+        //the hidden string
499
+        $hiddenStr = str_repeat($hiddenChar, $len - ($startCount + $endCount));
500 500
 		
501
-		return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
502
-	}
501
+        return $startNonHiddenStr . $hiddenStr . $endNonHiddenStr;
502
+    }
503 503
 	
504
-	/**
505
-	 * This function is used to set the initial session config regarding the configuration
506
-	 * @codeCoverageIgnore
507
-	 */
508
-	function set_session_config(){
509
-		//$_SESSION is not available on cli mode 
510
-		if (! IS_CLI){
511
-			$logger =& class_loader('Log', 'classes');
512
-			$logger->setLogger('PHPSession');
513
-			//set session params
514
-			$sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
515
-			$sessionName = get_config('session_name');
516
-			if ($sessionName){
517
-				session_name($sessionName);
518
-			}
519
-			$logger->info('Session handler: ' . $sessionHandler);
520
-			$logger->info('Session name: ' . $sessionName);
504
+    /**
505
+     * This function is used to set the initial session config regarding the configuration
506
+     * @codeCoverageIgnore
507
+     */
508
+    function set_session_config(){
509
+        //$_SESSION is not available on cli mode 
510
+        if (! IS_CLI){
511
+            $logger =& class_loader('Log', 'classes');
512
+            $logger->setLogger('PHPSession');
513
+            //set session params
514
+            $sessionHandler = get_config('session_handler', 'files'); //the default is to store in the files
515
+            $sessionName = get_config('session_name');
516
+            if ($sessionName){
517
+                session_name($sessionName);
518
+            }
519
+            $logger->info('Session handler: ' . $sessionHandler);
520
+            $logger->info('Session name: ' . $sessionName);
521 521
 
522
-			if ($sessionHandler == 'files'){
523
-				$sessionSavePath = get_config('session_save_path');
524
-				if ($sessionSavePath){
525
-					if (! is_dir($sessionSavePath)){
526
-						mkdir($sessionSavePath, 1773);
527
-					}
528
-					session_save_path($sessionSavePath);
529
-					$logger->info('Session save path: ' . $sessionSavePath);
530
-				}
531
-			}
532
-			else if ($sessionHandler == 'database'){
533
-				//load database session handle library
534
-				//Database Session handler Model
535
-				require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
522
+            if ($sessionHandler == 'files'){
523
+                $sessionSavePath = get_config('session_save_path');
524
+                if ($sessionSavePath){
525
+                    if (! is_dir($sessionSavePath)){
526
+                        mkdir($sessionSavePath, 1773);
527
+                    }
528
+                    session_save_path($sessionSavePath);
529
+                    $logger->info('Session save path: ' . $sessionSavePath);
530
+                }
531
+            }
532
+            else if ($sessionHandler == 'database'){
533
+                //load database session handle library
534
+                //Database Session handler Model
535
+                require_once CORE_CLASSES_MODEL_PATH . 'DBSessionHandlerModel.php';
536 536
 
537
-				$DBS =& class_loader('DBSessionHandler', 'classes');
538
-				session_set_save_handler($DBS, true);
539
-				$logger->info('session save path: ' . get_config('session_save_path'));
540
-			}
541
-			else{
542
-				show_error('Invalid session handler configuration');
543
-			}
544
-			$lifetime = get_config('session_cookie_lifetime', 0);
545
-			$path = get_config('session_cookie_path', '/');
546
-			$domain = get_config('session_cookie_domain', '');
547
-			$secure = get_config('session_cookie_secure', false);
548
-			session_set_cookie_params(
549
-				$lifetime,
550
-				$path,
551
-				$domain,
552
-				$secure,
553
-				$httponly = true /*for security for access to cookie via javascript or XSS attack*/
554
-			);
555
-			//to prevent attack of Session Fixation 
556
-			//thank to https://www.phparch.com/2018/01/php-sessions-in-depth/
557
-			ini_set('session.use_strict_mode ', 1);
558
-			ini_set('session.use_only_cookies', 1);
559
-			ini_set('session.use_trans_sid ', 0);
537
+                $DBS =& class_loader('DBSessionHandler', 'classes');
538
+                session_set_save_handler($DBS, true);
539
+                $logger->info('session save path: ' . get_config('session_save_path'));
540
+            }
541
+            else{
542
+                show_error('Invalid session handler configuration');
543
+            }
544
+            $lifetime = get_config('session_cookie_lifetime', 0);
545
+            $path = get_config('session_cookie_path', '/');
546
+            $domain = get_config('session_cookie_domain', '');
547
+            $secure = get_config('session_cookie_secure', false);
548
+            session_set_cookie_params(
549
+                $lifetime,
550
+                $path,
551
+                $domain,
552
+                $secure,
553
+                $httponly = true /*for security for access to cookie via javascript or XSS attack*/
554
+            );
555
+            //to prevent attack of Session Fixation 
556
+            //thank to https://www.phparch.com/2018/01/php-sessions-in-depth/
557
+            ini_set('session.use_strict_mode ', 1);
558
+            ini_set('session.use_only_cookies', 1);
559
+            ini_set('session.use_trans_sid ', 0);
560 560
 			
561
-			$logger->info('Session lifetime: ' . $lifetime);
562
-			$logger->info('Session cookie path: ' . $path);
563
-			$logger->info('Session domain: ' . $domain);
564
-			$logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
561
+            $logger->info('Session lifetime: ' . $lifetime);
562
+            $logger->info('Session cookie path: ' . $path);
563
+            $logger->info('Session domain: ' . $domain);
564
+            $logger->info('Session is secure: ' . ($secure ? 'TRUE':'FALSE'));
565 565
 			
566
-			if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
567
-				$logger->info('Session not yet start, start it now');
568
-				session_start();
569
-			}
570
-		}
571
-	}
566
+            if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()){
567
+                $logger->info('Session not yet start, start it now');
568
+                session_start();
569
+            }
570
+        }
571
+    }
572 572
 	
573
-	/**
574
-	* This function is very useful, it allows to recover the instance of the global controller.
575
-	* Note this function always returns the address of the super instance.
576
-	* For example :
577
-	* $obj = & get_instance();
578
-	* 
579
-	* @codeCoverageIgnore
580
-	*  
581
-	* @return object the instance of the "Controller" class
582
-	*/
583
-	function & get_instance(){
584
-		return Controller::get_instance();
585
-	}
573
+    /**
574
+     * This function is very useful, it allows to recover the instance of the global controller.
575
+     * Note this function always returns the address of the super instance.
576
+     * For example :
577
+     * $obj = & get_instance();
578
+     * 
579
+     * @codeCoverageIgnore
580
+     *  
581
+     * @return object the instance of the "Controller" class
582
+     */
583
+    function & get_instance(){
584
+        return Controller::get_instance();
585
+    }
Please login to merge, or discard this patch.
core/classes/model/Model.php 3 patches
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
      * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34 34
      */
35 35
 
36
-    class Model{
36
+    class Model {
37 37
 
38 38
         /* --------------------------------------------------------------
39 39
          * VARIABLES
@@ -140,13 +140,13 @@  discard block
 block discarded – undo
140 140
          * Initialise the model, tie into the CodeIgniter superobject and
141 141
          * try our best to guess the table name.
142 142
          */
143
-        public function __construct(Database $db = null){
144
-            if (is_object($db)){
143
+        public function __construct(Database $db = null) {
144
+            if (is_object($db)) {
145 145
                 $this->setDatabaseInstance($db);
146 146
             }
147
-            else{
147
+            else {
148 148
                 $obj = & get_instance();
149
-        		if (isset($obj->database) && is_object($obj->database)){
149
+        		if (isset($obj->database) && is_object($obj->database)) {
150 150
                     /**
151 151
                     * NOTE: Need use "clone" because some Model need have the personal instance of the database library
152 152
                     * to prevent duplication
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 
183 183
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
184 184
             {
185
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
185
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
186 186
             }
187 187
     		$this->_set_where($where);
188 188
 
@@ -224,9 +224,9 @@  discard block
 block discarded – undo
224 224
             $this->trigger('before_get');
225 225
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
226 226
             {
227
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
227
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
228 228
             }
229
-			$type = $this->_temporary_return_type == 'array' ? 'array':false;
229
+			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
230 230
             $this->getQueryBuilder()->from($this->_table);
231 231
 			$result = $this->_database->getAll($type);
232 232
             $this->_temporary_return_type = $this->return_type;
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
                 $insert_id = $this->_database->insertId();
260 260
                 $this->trigger('after_create', $insert_id);
261 261
 				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
262
-				return ! $insert_id ? true : $insert_id;
262
+				return !$insert_id ? true : $insert_id;
263 263
             }
264 264
             else
265 265
             {
@@ -336,13 +336,13 @@  discard block
 block discarded – undo
336 336
         {
337 337
             $args = func_get_args();
338 338
             $data = array();
339
-            if (count($args) == 2){
340
-                if (is_array($args[1])){
339
+            if (count($args) == 2) {
340
+                if (is_array($args[1])) {
341 341
                     $data = array_pop($args);
342 342
                 }
343 343
             }
344
-            else if (count($args) == 3){
345
-                if (is_array($args[2])){
344
+            else if (count($args) == 3) {
345
+                if (is_array($args[2])) {
346 346
                     $data = array_pop($args);
347 347
                 }
348 348
             }
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
             if ($this->soft_delete)
385 385
             {
386 386
                 $this->getQueryBuilder()->from($this->_table);	
387
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
387
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
388 388
             }
389 389
             else
390 390
             {
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
             if ($this->soft_delete)
409 409
             {
410 410
                 $this->getQueryBuilder()->from($this->_table);	
411
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
411
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
412 412
             }
413 413
             else
414 414
             {
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
             if ($this->soft_delete)
431 431
             {
432 432
                 $this->getQueryBuilder()->from($this->_table);	
433
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
433
+				$result = $this->_database->update(array($this->soft_delete_key => TRUE));
434 434
             }
435 435
             else
436 436
             {
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
                 $key = $this->primary_key;
501 501
                 $value = $args[0];
502 502
             }
503
-            $this->trigger('before_dropdown', array( $key, $value ));
503
+            $this->trigger('before_dropdown', array($key, $value));
504 504
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
505 505
             {
506 506
                 $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
         {
526 526
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
527 527
             {
528
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
528
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
529 529
             }
530 530
             $where = func_get_args();
531 531
             $this->_set_where($where);
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
         {
542 542
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
543 543
             {
544
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
544
+                $this->getQueryBuilder()->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
545 545
             }
546 546
 			$this->getQueryBuilder()->from($this->_table);
547 547
 			$this->_database->getAll();
@@ -551,8 +551,8 @@  discard block
 block discarded – undo
551 551
 		/**
552 552
 		* Enabled cache temporary
553 553
 		*/
554
-		public function cached($ttl = 0){
555
-		  if ($ttl > 0){
554
+		public function cached($ttl = 0) {
555
+		  if ($ttl > 0) {
556 556
 			$this->_database = $this->_database->cached($ttl);
557 557
 		  }
558 558
 		  return $this;
@@ -706,13 +706,13 @@  discard block
 block discarded – undo
706 706
             {
707 707
                 if (is_object($row))
708 708
                 {
709
-					if (isset($row->$attr)){
709
+					if (isset($row->$attr)) {
710 710
 						unset($row->$attr);
711 711
 					}
712 712
                 }
713 713
                 else
714 714
                 {
715
-					if (isset($row[$attr])){
715
+					if (isset($row[$attr])) {
716 716
 						unset($row[$attr]);
717 717
 					}
718 718
                 }
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
          * Return the database instance
725 725
          * @return Database the database instance
726 726
          */
727
-        public function getDatabaseInstance(){
727
+        public function getDatabaseInstance() {
728 728
             return $this->_database;
729 729
         }
730 730
 
@@ -732,9 +732,9 @@  discard block
 block discarded – undo
732 732
          * set the Database instance for future use
733 733
          * @param Database $db the database object
734 734
          */
735
-         public function setDatabaseInstance($db){
735
+         public function setDatabaseInstance($db) {
736 736
             $this->_database = $db;
737
-            if ($this->dbCacheTime > 0){
737
+            if ($this->dbCacheTime > 0) {
738 738
                 $this->_database->setCache($this->dbCacheTime);
739 739
             }
740 740
             return $this;
@@ -744,7 +744,7 @@  discard block
 block discarded – undo
744 744
          * Return the loader instance
745 745
          * @return Loader the loader instance
746 746
          */
747
-        public function getLoader(){
747
+        public function getLoader() {
748 748
             return $this->loaderInstance;
749 749
         }
750 750
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
          * @param Loader $loader the loader object
754 754
 		 * @return object
755 755
          */
756
-         public function setLoader($loader){
756
+         public function setLoader($loader) {
757 757
             $this->loaderInstance = $loader;
758 758
             return $this;
759 759
         }
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
          * Return the queryBuilder instance this is the shortcut to database queryBuilder
763 763
          * @return object the DatabaseQueryBuilder instance
764 764
          */
765
-        public function getQueryBuilder(){
765
+        public function getQueryBuilder() {
766 766
             return $this->_database->getQueryBuilder();
767 767
         }
768 768
 
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
          * @param object $queryBuilder the DatabaseQueryBuilder object
772 772
 		 * @return object
773 773
          */
774
-         public function setQueryBuilder($queryBuilder){
774
+         public function setQueryBuilder($queryBuilder) {
775 775
             $this->_database->setQueryBuilder($queryBuilder);
776 776
             return $this;
777 777
         }
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
          * Return the FormValidation instance
782 782
          * @return FormValidation the form validation instance
783 783
          */
784
-        public function getFormValidation(){
784
+        public function getFormValidation() {
785 785
             return $this->formValidationInstance;
786 786
         }
787 787
 
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
          * @param FormValidation $fv the form validation object
791 791
 		 * @return object
792 792
          */
793
-         public function setFormValidation($fv){
793
+         public function setFormValidation($fv) {
794 794
             $this->formValidationInstance = $fv;
795 795
             return $this;
796 796
         }
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
          */
805 805
         public function order_by($criteria, $order = 'ASC')
806 806
         {
807
-            if ( is_array($criteria) )
807
+            if (is_array($criteria))
808 808
             {
809 809
                 foreach ($criteria as $key => $value)
810 810
                 {
@@ -835,13 +835,13 @@  discard block
 block discarded – undo
835 835
 		* relate for the relation "belongs_to"
836 836
 		* @return mixed
837 837
 		*/
838
-		protected function relateBelongsTo($row){
838
+		protected function relateBelongsTo($row) {
839 839
 			foreach ($this->belongs_to as $key => $value)
840 840
             {
841 841
                 if (is_string($value))
842 842
                 {
843 843
                     $relationship = $value;
844
-                    $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
844
+                    $options = array('primary_key' => $value . '_id', 'model' => $value . '_model');
845 845
                 }
846 846
                 else
847 847
                 {
@@ -851,10 +851,10 @@  discard block
 block discarded – undo
851 851
 
852 852
                 if (in_array($relationship, $this->_with))
853 853
                 {
854
-                    if (is_object($this->loaderInstance)){
854
+                    if (is_object($this->loaderInstance)) {
855 855
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
856 856
                     }
857
-                    else{
857
+                    else {
858 858
                         Loader::model($options['model'], $relationship . '_model');    
859 859
                     }
860 860
                     if (is_object($row))
@@ -874,13 +874,13 @@  discard block
 block discarded – undo
874 874
 		* relate for the relation "has_many"
875 875
 		* @return mixed
876 876
 		*/
877
-		protected function relateHasMany($row){
877
+		protected function relateHasMany($row) {
878 878
 			foreach ($this->has_many as $key => $value)
879 879
             {
880 880
                 if (is_string($value))
881 881
                 {
882 882
                     $relationship = $value;
883
-                    $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
883
+                    $options = array('primary_key' => $this->_table . '_id', 'model' => $value . '_model');
884 884
                 }
885 885
                 else
886 886
                 {
@@ -890,10 +890,10 @@  discard block
 block discarded – undo
890 890
 
891 891
                 if (in_array($relationship, $this->_with))
892 892
                 {
893
-                    if (is_object($this->loaderInstance)){
893
+                    if (is_object($this->loaderInstance)) {
894 894
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
895 895
                     }
896
-                    else{
896
+                    else {
897 897
                         Loader::model($options['model'], $relationship . '_model');    
898 898
                     }
899 899
                     if (is_object($row))
@@ -944,10 +944,10 @@  discard block
 block discarded – undo
944 944
             if (!empty($this->validate))
945 945
             {
946 946
                 $fv = null;
947
-                if (is_object($this->formValidationInstance)){
947
+                if (is_object($this->formValidationInstance)) {
948 948
                     $fv = $this->formValidationInstance;
949 949
                 }
950
-                else{
950
+                else {
951 951
                     Loader::library('FormValidation');
952 952
                     $fv = $this->formvalidation;
953 953
                     $this->setFormValidation($fv);
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
 		* Set WHERE parameters, when is array
977 977
 		* @param array $params
978 978
 		*/
979
-		protected function _set_where_array(array $params){
979
+		protected function _set_where_array(array $params) {
980 980
 			foreach ($params as $field => $filter)
981 981
 			{
982 982
 				if (is_array($filter))
@@ -1042,7 +1042,7 @@  discard block
 block discarded – undo
1042 1042
         /**
1043 1043
             Shortcut to controller
1044 1044
         */
1045
-        public function __get($key){
1045
+        public function __get($key) {
1046 1046
             return get_instance()->{$key};
1047 1047
         }
1048 1048
 
Please login to merge, or discard this patch.
Braces   +32 added lines, -64 removed lines patch added patch discarded remove patch
@@ -143,8 +143,7 @@  discard block
 block discarded – undo
143 143
         public function __construct(Database $db = null){
144 144
             if (is_object($db)){
145 145
                 $this->setDatabaseInstance($db);
146
-            }
147
-            else{
146
+            } else{
148 147
                 $obj = & get_instance();
149 148
         		if (isset($obj->database) && is_object($obj->database)){
150 149
                     /**
@@ -260,8 +259,7 @@  discard block
 block discarded – undo
260 259
                 $this->trigger('after_create', $insert_id);
261 260
 				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
262 261
 				return ! $insert_id ? true : $insert_id;
263
-            }
264
-            else
262
+            } else
265 263
             {
266 264
                 return FALSE;
267 265
             }
@@ -298,8 +296,7 @@  discard block
 block discarded – undo
298 296
                 $result = $this->_database->update($data, $escape);
299 297
                 $this->trigger('after_update', array($data, $result));
300 298
                 return $result;
301
-            }
302
-            else
299
+            } else
303 300
             {
304 301
                 return FALSE;
305 302
             }
@@ -322,8 +319,7 @@  discard block
 block discarded – undo
322 319
 				$result = $this->_database->update($data, $escape);
323 320
                 $this->trigger('after_update', array($data, $result));
324 321
                 return $result;
325
-            }
326
-            else
322
+            } else
327 323
             {
328 324
                 return FALSE;
329 325
             }
@@ -340,8 +336,7 @@  discard block
 block discarded – undo
340 336
                 if (is_array($args[1])){
341 337
                     $data = array_pop($args);
342 338
                 }
343
-            }
344
-            else if (count($args) == 3){
339
+            } else if (count($args) == 3){
345 340
                 if (is_array($args[2])){
346 341
                     $data = array_pop($args);
347 342
                 }
@@ -354,8 +349,7 @@  discard block
 block discarded – undo
354 349
 				$result = $this->_database->update($data);
355 350
                 $this->trigger('after_update', array($data, $result));
356 351
                 return $result;
357
-            }
358
-            else
352
+            } else
359 353
             {
360 354
                 return FALSE;
361 355
             }
@@ -385,8 +379,7 @@  discard block
 block discarded – undo
385 379
             {
386 380
                 $this->getQueryBuilder()->from($this->_table);	
387 381
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
388
-            }
389
-            else
382
+            } else
390 383
             {
391 384
                 $this->getQueryBuilder()->from($this->_table); 
392 385
 				$result = $this->_database->delete();
@@ -409,8 +402,7 @@  discard block
 block discarded – undo
409 402
             {
410 403
                 $this->getQueryBuilder()->from($this->_table);	
411 404
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
412
-            }
413
-            else
405
+            } else
414 406
             {
415 407
                 $this->getQueryBuilder()->from($this->_table); 
416 408
 				$result = $this->_database->delete();
@@ -431,8 +423,7 @@  discard block
 block discarded – undo
431 423
             {
432 424
                 $this->getQueryBuilder()->from($this->_table);	
433 425
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
434
-            }
435
-            else
426
+            } else
436 427
             {
437 428
                 $this->getQueryBuilder()->from($this->_table); 
438 429
 				$result = $this->_database->delete();
@@ -494,8 +485,7 @@  discard block
 block discarded – undo
494 485
             if (count($args) == 2)
495 486
             {
496 487
                 list($key, $value) = $args;
497
-            }
498
-            else
488
+            } else
499 489
             {
500 490
                 $key = $this->primary_key;
501 491
                 $value = $args[0];
@@ -647,8 +637,7 @@  discard block
 block discarded – undo
647 637
             if (is_object($row))
648 638
             {
649 639
                 $row->created_at = date('Y-m-d H:i:s');
650
-            }
651
-            else
640
+            } else
652 641
             {
653 642
                 $row['created_at'] = date('Y-m-d H:i:s');
654 643
             }
@@ -660,8 +649,7 @@  discard block
 block discarded – undo
660 649
             if (is_object($row))
661 650
             {
662 651
                 $row->updated_at = date('Y-m-d H:i:s');
663
-            }
664
-            else
652
+            } else
665 653
             {
666 654
                 $row['updated_at'] = date('Y-m-d H:i:s');
667 655
             }
@@ -688,8 +676,7 @@  discard block
 block discarded – undo
688 676
                 if (is_array($row))
689 677
                 {
690 678
                     $row[$column] = unserialize($row[$column]);
691
-                }
692
-                else
679
+                } else
693 680
                 {
694 681
                     $row->$column = unserialize($row->$column);
695 682
                 }
@@ -709,8 +696,7 @@  discard block
 block discarded – undo
709 696
 					if (isset($row->$attr)){
710 697
 						unset($row->$attr);
711 698
 					}
712
-                }
713
-                else
699
+                } else
714 700
                 {
715 701
 					if (isset($row[$attr])){
716 702
 						unset($row[$attr]);
@@ -810,8 +796,7 @@  discard block
 block discarded – undo
810 796
                 {
811 797
                     $this->getQueryBuilder()->orderBy($key, $value);
812 798
                 }
813
-            }
814
-            else
799
+            } else
815 800
             {
816 801
                 $this->getQueryBuilder()->orderBy($criteria, $order);
817 802
             }
@@ -842,8 +827,7 @@  discard block
 block discarded – undo
842 827
                 {
843 828
                     $relationship = $value;
844 829
                     $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
845
-                }
846
-                else
830
+                } else
847 831
                 {
848 832
                     $relationship = $key;
849 833
                     $options = $value;
@@ -853,15 +837,13 @@  discard block
 block discarded – undo
853 837
                 {
854 838
                     if (is_object($this->loaderInstance)){
855 839
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
856
-                    }
857
-                    else{
840
+                    } else{
858 841
                         Loader::model($options['model'], $relationship . '_model');    
859 842
                     }
860 843
                     if (is_object($row))
861 844
                     {
862 845
                         $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
863
-                    }
864
-                    else
846
+                    } else
865 847
                     {
866 848
                         $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
867 849
                     }
@@ -881,8 +863,7 @@  discard block
 block discarded – undo
881 863
                 {
882 864
                     $relationship = $value;
883 865
                     $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
884
-                }
885
-                else
866
+                } else
886 867
                 {
887 868
                     $relationship = $key;
888 869
                     $options = $value;
@@ -892,15 +873,13 @@  discard block
 block discarded – undo
892 873
                 {
893 874
                     if (is_object($this->loaderInstance)){
894 875
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
895
-                    }
896
-                    else{
876
+                    } else{
897 877
                         Loader::model($options['model'], $relationship . '_model');    
898 878
                     }
899 879
                     if (is_object($row))
900 880
                     {
901 881
                         $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
902
-                    }
903
-                    else
882
+                    } else
904 883
                     {
905 884
                         $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
906 885
                     }
@@ -946,8 +925,7 @@  discard block
 block discarded – undo
946 925
                 $fv = null;
947 926
                 if (is_object($this->formValidationInstance)){
948 927
                     $fv = $this->formValidationInstance;
949
-                }
950
-                else{
928
+                } else{
951 929
                     Loader::library('FormValidation');
952 930
                     $fv = $this->formvalidation;
953 931
                     $this->setFormValidation($fv);
@@ -959,13 +937,11 @@  discard block
 block discarded – undo
959 937
                 if ($fv->run())
960 938
                 {
961 939
                     return $data;
962
-                }
963
-                else
940
+                } else
964 941
                 {
965 942
                     return FALSE;
966 943
                 }
967
-            }
968
-            else
944
+            } else
969 945
             {
970 946
                 return $data;
971 947
             }
@@ -982,14 +958,12 @@  discard block
 block discarded – undo
982 958
 				if (is_array($filter))
983 959
 				{
984 960
 					$this->getQueryBuilder()->in($field, $filter);
985
-				}
986
-				else
961
+				} else
987 962
 				{
988 963
 					if (is_int($field))
989 964
 					{
990 965
 						$this->getQueryBuilder()->where($filter);
991
-					}
992
-					else
966
+					} else
993 967
 					{
994 968
 						$this->getQueryBuilder()->where($field, $filter);
995 969
 					}
@@ -1006,33 +980,27 @@  discard block
 block discarded – undo
1006 980
             if (count($params) == 1 && is_array($params[0]))
1007 981
             {
1008 982
                 $this->_set_where_array($params[0]);
1009
-            }
1010
-            else if (count($params) == 1)
983
+            } else if (count($params) == 1)
1011 984
             {
1012 985
                 $this->getQueryBuilder()->where($params[0]);
1013
-            }
1014
-        	else if (count($params) == 2)
986
+            } else if (count($params) == 2)
1015 987
     		{
1016 988
                 if (is_array($params[1]))
1017 989
                 {
1018 990
                     $this->getQueryBuilder()->in($params[0], $params[1]);
1019
-                }
1020
-                else
991
+                } else
1021 992
                 {
1022 993
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1023 994
                 }
1024
-    		}
1025
-    		else if (count($params) == 3)
995
+    		} else if (count($params) == 3)
1026 996
     		{
1027 997
     			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1028
-    		}
1029
-            else
998
+    		} else
1030 999
             {
1031 1000
                 if (is_array($params[1]))
1032 1001
                 {
1033 1002
                     $this->getQueryBuilder()->in($params[0], $params[1]);
1034
-                }
1035
-                else
1003
+                } else
1036 1004
                 {
1037 1005
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1038 1006
                 }
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
      * You should have received a copy of the GNU General Public License
23 23
      * along with this program; if not, write to the Free Software
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
25
+     */
26 26
 
27 27
 
28 28
     /**
@@ -120,10 +120,10 @@  discard block
 block discarded – undo
120 120
         protected $_temporary_return_type = NULL;
121 121
     	
122 122
     	
123
-    	/**
123
+        /**
124 124
     		The database cache time 
125
-    	*/
126
-    	protected $dbCacheTime = 0;
125
+         */
126
+        protected $dbCacheTime = 0;
127 127
 
128 128
         /**
129 129
          * Instance of the Loader class
@@ -151,12 +151,12 @@  discard block
 block discarded – undo
151 151
             }
152 152
             else{
153 153
                 $obj = & get_instance();
154
-        		if (isset($obj->database) && is_object($obj->database)){
154
+                if (isset($obj->database) && is_object($obj->database)){
155 155
                     /**
156
-                    * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157
-                    * to prevent duplication
158
-                    */
159
-        			$this->setDatabaseInstance(clone $obj->database);
156
+                     * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157
+                     * to prevent duplication
158
+                     */
159
+                    $this->setDatabaseInstance(clone $obj->database);
160 160
                 }
161 161
             }
162 162
 
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
          */
175 175
         public function get($primary_value)
176 176
         {
177
-    		return $this->get_by($this->primary_key, $primary_value);
177
+            return $this->get_by($this->primary_key, $primary_value);
178 178
         }
179 179
 
180 180
         /**
@@ -189,12 +189,12 @@  discard block
 block discarded – undo
189 189
             {
190 190
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
191 191
             }
192
-    		$this->_set_where($where);
192
+            $this->_set_where($where);
193 193
 
194 194
             $this->trigger('before_get');
195
-			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
195
+            $type = $this->_temporary_return_type == 'array' ? 'array' : false;
196 196
             $this->getQueryBuilder()->from($this->_table);
197
-			$row = $this->_database->get($type);
197
+            $row = $this->_database->get($type);
198 198
             $this->_temporary_return_type = $this->return_type;
199 199
             $row = $this->trigger('after_get', $row);
200 200
             $this->_with = array();
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
             {
232 232
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
233 233
             }
234
-			$type = $this->_temporary_return_type == 'array' ? 'array':false;
234
+            $type = $this->_temporary_return_type == 'array' ? 'array':false;
235 235
             $this->getQueryBuilder()->from($this->_table);
236
-			$result = $this->_database->getAll($type);
236
+            $result = $this->_database->getAll($type);
237 237
             $this->_temporary_return_type = $this->return_type;
238 238
 
239 239
             foreach ($result as $key => &$row)
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
         /**
248 248
          * Insert a new row into the table. $data should be an associative array
249 249
          * of data to be inserted. Returns newly created ID.
250
-		 * @see Database::insert
250
+         * @see Database::insert
251 251
          */
252 252
         public function insert($data = array(), $skip_validation = FALSE, $escape = true)
253 253
         {
@@ -260,11 +260,11 @@  discard block
 block discarded – undo
260 260
             {
261 261
                 $data = $this->trigger('before_create', $data);
262 262
                 $this->getQueryBuilder()->from($this->_table);
263
-				$this->_database->insert($data, $escape);
263
+                $this->_database->insert($data, $escape);
264 264
                 $insert_id = $this->_database->insertId();
265 265
                 $this->trigger('after_create', $insert_id);
266
-				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
267
-				return ! $insert_id ? true : $insert_id;
266
+                //if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
267
+                return ! $insert_id ? true : $insert_id;
268 268
             }
269 269
             else
270 270
             {
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
             {
325 325
                 $this->getQueryBuilder()->in($this->primary_key, $primary_values)
326 326
                                         ->from($this->_table);
327
-				$result = $this->_database->update($data, $escape);
327
+                $result = $this->_database->update($data, $escape);
328 328
                 $this->trigger('after_update', array($data, $result));
329 329
                 return $result;
330 330
             }
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
             {
357 357
                 $this->_set_where($args);
358 358
                 $this->getQueryBuilder()->from($this->_table);
359
-				$result = $this->_database->update($data);
359
+                $result = $this->_database->update($data);
360 360
                 $this->trigger('after_update', array($data, $result));
361 361
                 return $result;
362 362
             }
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
         {
374 374
             $data = $this->trigger('before_update', $data);
375 375
             $this->getQueryBuilder()->from($this->_table);
376
-			$result = $this->_database->update($data, $escape);
376
+            $result = $this->_database->update($data, $escape);
377 377
             $this->trigger('after_update', array($data, $result));
378 378
             return $result;
379 379
         }
@@ -385,16 +385,16 @@  discard block
 block discarded – undo
385 385
         {
386 386
             $this->trigger('before_delete', $id);
387 387
             $this->getQueryBuilder()->where($this->primary_key, $id);
388
-			$result = false;
388
+            $result = false;
389 389
             if ($this->soft_delete)
390 390
             {
391 391
                 $this->getQueryBuilder()->from($this->_table);	
392
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
392
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
393 393
             }
394 394
             else
395 395
             {
396 396
                 $this->getQueryBuilder()->from($this->_table); 
397
-				$result = $this->_database->delete();
397
+                $result = $this->_database->delete();
398 398
             }
399 399
 
400 400
             $this->trigger('after_delete', $result);
@@ -407,18 +407,18 @@  discard block
 block discarded – undo
407 407
         public function delete_by()
408 408
         {
409 409
             $where = func_get_args();
410
-    	    $where = $this->trigger('before_delete', $where);
410
+            $where = $this->trigger('before_delete', $where);
411 411
             $this->_set_where($where);
412
-			$result = false;
412
+            $result = false;
413 413
             if ($this->soft_delete)
414 414
             {
415 415
                 $this->getQueryBuilder()->from($this->_table);	
416
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
416
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
417 417
             }
418 418
             else
419 419
             {
420 420
                 $this->getQueryBuilder()->from($this->_table); 
421
-				$result = $this->_database->delete();
421
+                $result = $this->_database->delete();
422 422
             }
423 423
             $this->trigger('after_delete', $result);
424 424
             return $result;
@@ -431,16 +431,16 @@  discard block
 block discarded – undo
431 431
         {
432 432
             $primary_values = $this->trigger('before_delete', $primary_values);
433 433
             $this->getQueryBuilder()->in($this->primary_key, $primary_values);
434
-			$result = false;
434
+            $result = false;
435 435
             if ($this->soft_delete)
436 436
             {
437 437
                 $this->getQueryBuilder()->from($this->_table);	
438
-				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
438
+                $result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
439 439
             }
440 440
             else
441 441
             {
442 442
                 $this->getQueryBuilder()->from($this->_table); 
443
-				$result = $this->_database->delete();
443
+                $result = $this->_database->delete();
444 444
             }
445 445
             $this->trigger('after_delete', $result);
446 446
             return $result;
@@ -452,8 +452,8 @@  discard block
 block discarded – undo
452 452
          */
453 453
         public function truncate()
454 454
         {
455
-			$this->getQueryBuilder()->from($this->_table); 
456
-			$result = $this->_database->delete();
455
+            $this->getQueryBuilder()->from($this->_table); 
456
+            $result = $this->_database->delete();
457 457
             return $result;
458 458
         }
459 459
 
@@ -471,14 +471,14 @@  discard block
 block discarded – undo
471 471
             return $this;
472 472
         }
473 473
 		
474
-		/**
475
-		* Relationship
476
-		*/
474
+        /**
475
+         * Relationship
476
+         */
477 477
         public function relate($row)
478 478
         {
479
-    		if (empty($row))
479
+            if (empty($row))
480 480
             {
481
-    		    return $row;
481
+                return $row;
482 482
             }
483 483
 
484 484
             $row = $this->relateBelongsTo($row);
@@ -511,9 +511,9 @@  discard block
 block discarded – undo
511 511
                 $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
512 512
             }
513 513
             $this->getQueryBuilder()
514
-									 ->select(array($key, $value))
515
-									 ->from($this->_table);
516
-			$result = $this->_database->getAll();
514
+                                        ->select(array($key, $value))
515
+                                        ->from($this->_table);
516
+            $result = $this->_database->getAll();
517 517
             $options = array();
518 518
             foreach ($result as $row)
519 519
             {
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
             $where = func_get_args();
536 536
             $this->_set_where($where);
537 537
             $this->getQueryBuilder()->from($this->_table);
538
-			$this->_database->getAll();
538
+            $this->_database->getAll();
539 539
             return $this->_database->numRows();
540 540
         }
541 541
 
@@ -548,20 +548,20 @@  discard block
 block discarded – undo
548 548
             {
549 549
                 $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
550 550
             }
551
-			$this->getQueryBuilder()->from($this->_table);
552
-			$this->_database->getAll();
551
+            $this->getQueryBuilder()->from($this->_table);
552
+            $this->_database->getAll();
553 553
             return $this->_database->numRows();
554 554
         }
555 555
 		
556
-		/**
557
-		* Enabled cache temporary
558
-		*/
559
-		public function cached($ttl = 0){
560
-		  if ($ttl > 0){
561
-			$this->_database = $this->_database->cached($ttl);
562
-		  }
563
-		  return $this;
564
-		}
556
+        /**
557
+         * Enabled cache temporary
558
+         */
559
+        public function cached($ttl = 0){
560
+            if ($ttl > 0){
561
+            $this->_database = $this->_database->cached($ttl);
562
+            }
563
+            return $this;
564
+        }
565 565
 
566 566
         /**
567 567
          * Tell the class to skip the insert validation
@@ -585,10 +585,10 @@  discard block
 block discarded – undo
585 585
          */
586 586
         public function get_next_id()
587 587
         {
588
-			$this->getQueryBuilder()->select('AUTO_INCREMENT')
589
-									->from('information_schema.TABLES')
590
-									->where('TABLE_NAME', $this->_table)
591
-									->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
588
+            $this->getQueryBuilder()->select('AUTO_INCREMENT')
589
+                                    ->from('information_schema.TABLES')
590
+                                    ->where('TABLE_NAME', $this->_table)
591
+                                    ->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
592 592
             return (int) $this->_database->get()->AUTO_INCREMENT;
593 593
         }
594 594
 
@@ -711,24 +711,24 @@  discard block
 block discarded – undo
711 711
             {
712 712
                 if (is_object($row))
713 713
                 {
714
-					if (isset($row->$attr)){
715
-						unset($row->$attr);
716
-					}
714
+                    if (isset($row->$attr)){
715
+                        unset($row->$attr);
716
+                    }
717 717
                 }
718 718
                 else
719 719
                 {
720
-					if (isset($row[$attr])){
721
-						unset($row[$attr]);
722
-					}
720
+                    if (isset($row[$attr])){
721
+                        unset($row[$attr]);
722
+                    }
723 723
                 }
724 724
             }
725 725
             return $row;
726 726
         }
727 727
 		
728
-		 /**
729
-         * Return the database instance
730
-         * @return Database the database instance
731
-         */
728
+            /**
729
+             * Return the database instance
730
+             * @return Database the database instance
731
+             */
732 732
         public function getDatabaseInstance(){
733 733
             return $this->_database;
734 734
         }
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
          * set the Database instance for future use
738 738
          * @param Database $db the database object
739 739
          */
740
-         public function setDatabaseInstance($db){
740
+            public function setDatabaseInstance($db){
741 741
             $this->_database = $db;
742 742
             if ($this->dbCacheTime > 0){
743 743
                 $this->_database->setCache($this->dbCacheTime);
@@ -756,14 +756,14 @@  discard block
 block discarded – undo
756 756
         /**
757 757
          * Set the loader instance for future use
758 758
          * @param Loader $loader the loader object
759
-		 * @return object
759
+         * @return object
760 760
          */
761
-         public function setLoader($loader){
761
+            public function setLoader($loader){
762 762
             $this->loaderInstance = $loader;
763 763
             return $this;
764 764
         }
765 765
 
766
-		/**
766
+        /**
767 767
          * Return the queryBuilder instance this is the shortcut to database queryBuilder
768 768
          * @return object the DatabaseQueryBuilder instance
769 769
          */
@@ -774,9 +774,9 @@  discard block
 block discarded – undo
774 774
         /**
775 775
          * Set the DatabaseQueryBuilder instance for future use
776 776
          * @param object $queryBuilder the DatabaseQueryBuilder object
777
-		 * @return object
777
+         * @return object
778 778
          */
779
-         public function setQueryBuilder($queryBuilder){
779
+            public function setQueryBuilder($queryBuilder){
780 780
             $this->_database->setQueryBuilder($queryBuilder);
781 781
             return $this;
782 782
         }
@@ -793,9 +793,9 @@  discard block
 block discarded – undo
793 793
         /**
794 794
          * Set the form validation instance for future use
795 795
          * @param FormValidation $fv the form validation object
796
-		 * @return object
796
+         * @return object
797 797
          */
798
-         public function setFormValidation($fv){
798
+            public function setFormValidation($fv){
799 799
             $this->formValidationInstance = $fv;
800 800
             return $this;
801 801
         }
@@ -836,12 +836,12 @@  discard block
 block discarded – undo
836 836
          * INTERNAL METHODS
837 837
          * ------------------------------------------------------------ */
838 838
 
839
-		/**
840
-		* relate for the relation "belongs_to"
841
-		* @return mixed
842
-		*/
843
-		protected function relateBelongsTo($row){
844
-			foreach ($this->belongs_to as $key => $value)
839
+        /**
840
+         * relate for the relation "belongs_to"
841
+         * @return mixed
842
+         */
843
+        protected function relateBelongsTo($row){
844
+            foreach ($this->belongs_to as $key => $value)
845 845
             {
846 846
                 if (is_string($value))
847 847
                 {
@@ -872,15 +872,15 @@  discard block
 block discarded – undo
872 872
                     }
873 873
                 }
874 874
             }
875
-			return $row;
876
-		}
877
-
878
-		/**
879
-		* relate for the relation "has_many"
880
-		* @return mixed
881
-		*/
882
-		protected function relateHasMany($row){
883
-			foreach ($this->has_many as $key => $value)
875
+            return $row;
876
+        }
877
+
878
+        /**
879
+         * relate for the relation "has_many"
880
+         * @return mixed
881
+         */
882
+        protected function relateHasMany($row){
883
+            foreach ($this->has_many as $key => $value)
884 884
             {
885 885
                 if (is_string($value))
886 886
                 {
@@ -911,8 +911,8 @@  discard block
 block discarded – undo
911 911
                     }
912 912
                 }
913 913
             }
914
-			return $row;
915
-		}
914
+            return $row;
915
+        }
916 916
 		
917 917
         /**
918 918
          * Trigger an event and call its observers. Pass through the event name
@@ -977,30 +977,30 @@  discard block
 block discarded – undo
977 977
         }
978 978
 		
979 979
 		
980
-		/**
981
-		* Set WHERE parameters, when is array
982
-		* @param array $params
983
-		*/
984
-		protected function _set_where_array(array $params){
985
-			foreach ($params as $field => $filter)
986
-			{
987
-				if (is_array($filter))
988
-				{
989
-					$this->getQueryBuilder()->in($field, $filter);
990
-				}
991
-				else
992
-				{
993
-					if (is_int($field))
994
-					{
995
-						$this->getQueryBuilder()->where($filter);
996
-					}
997
-					else
998
-					{
999
-						$this->getQueryBuilder()->where($field, $filter);
1000
-					}
1001
-				}
1002
-			}
1003
-		}
980
+        /**
981
+         * Set WHERE parameters, when is array
982
+         * @param array $params
983
+         */
984
+        protected function _set_where_array(array $params){
985
+            foreach ($params as $field => $filter)
986
+            {
987
+                if (is_array($filter))
988
+                {
989
+                    $this->getQueryBuilder()->in($field, $filter);
990
+                }
991
+                else
992
+                {
993
+                    if (is_int($field))
994
+                    {
995
+                        $this->getQueryBuilder()->where($filter);
996
+                    }
997
+                    else
998
+                    {
999
+                        $this->getQueryBuilder()->where($field, $filter);
1000
+                    }
1001
+                }
1002
+            }
1003
+        }
1004 1004
 
1005 1005
 
1006 1006
         /**
@@ -1016,8 +1016,8 @@  discard block
 block discarded – undo
1016 1016
             {
1017 1017
                 $this->getQueryBuilder()->where($params[0]);
1018 1018
             }
1019
-        	else if (count($params) == 2)
1020
-    		{
1019
+            else if (count($params) == 2)
1020
+            {
1021 1021
                 if (is_array($params[1]))
1022 1022
                 {
1023 1023
                     $this->getQueryBuilder()->in($params[0], $params[1]);
@@ -1026,11 +1026,11 @@  discard block
 block discarded – undo
1026 1026
                 {
1027 1027
                     $this->getQueryBuilder()->where($params[0], $params[1]);
1028 1028
                 }
1029
-    		}
1030
-    		else if (count($params) == 3)
1031
-    		{
1032
-    			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1033
-    		}
1029
+            }
1030
+            else if (count($params) == 3)
1031
+            {
1032
+                $this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1033
+            }
1034 1034
             else
1035 1035
             {
1036 1036
                 if (is_array($params[1]))
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 
1047 1047
         /**
1048 1048
             Shortcut to controller
1049
-        */
1049
+         */
1050 1050
         public function __get($key){
1051 1051
             return get_instance()->{$key};
1052 1052
         }
Please login to merge, or discard this patch.
core/classes/Response.php 3 patches
Spacing   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Response{
27
+	class Response {
28 28
 
29 29
 		/**
30 30
 		 * The list of request header to send with response
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Construct new response instance
67 67
 		 */
68
-		public function __construct(){
69
-			$this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
-					. (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
68
+		public function __construct() {
69
+			$this->_currentUrl = (!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '')
70
+					. (!empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '');
71 71
 					
72 72
 			$this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
@@ -82,9 +82,9 @@  discard block
 block discarded – undo
82 82
 		 * Get the logger singleton instance
83 83
 		 * @return Log the logger instance
84 84
 		 */
85
-		private static function getLogger(){
86
-			if(self::$logger == null){
87
-				self::$logger[0] =& class_loader('Log', 'classes');
85
+		private static function getLogger() {
86
+			if (self::$logger == null) {
87
+				self::$logger[0] = & class_loader('Log', 'classes');
88 88
 				self::$logger[0]->setLogger('Library::Response');
89 89
 			}
90 90
 			return self::$logger[0];
@@ -95,12 +95,12 @@  discard block
 block discarded – undo
95 95
 		 * @param  integer $httpCode the HTTP status code
96 96
 		 * @param  array   $headers   the additional headers to add to the existing headers list
97 97
 		 */
98
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
98
+		public static function sendHeaders($httpCode = 200, array $headers = array()) {
99 99
 			set_http_status_header($httpCode);
100 100
 			self::setHeaders($headers);
101
-			if(! headers_sent()){
102
-				foreach(self::getHeaders() as $key => $value){
103
-					header($key .': '.$value);
101
+			if (!headers_sent()) {
102
+				foreach (self::getHeaders() as $key => $value) {
103
+					header($key . ': ' . $value);
104 104
 				}
105 105
 			}
106 106
 		}
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		 * Get the list of the headers
110 110
 		 * @return array the headers list
111 111
 		 */
112
-		public static function getHeaders(){
112
+		public static function getHeaders() {
113 113
 			return self::$headers;
114 114
 		}
115 115
 
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 		 * @param  string $name the header name
119 119
 		 * @return string       the header value
120 120
 		 */
121
-		public static function getHeader($name){
121
+		public static function getHeader($name) {
122 122
 			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123 123
 		}
124 124
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		 * @param string $name  the header name
129 129
 		 * @param string $value the header value to be set
130 130
 		 */
131
-		public static function setHeader($name, $value){
131
+		public static function setHeader($name, $value) {
132 132
 			self::$headers[$name] = $value;
133 133
 		}
134 134
 
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 		 * @param array $headers the list of the headers to set. 
138 138
 		 * Note: this will merge with the existing headers
139 139
 		 */
140
-		public static function setHeaders(array $headers){
140
+		public static function setHeaders(array $headers) {
141 141
 			self::$headers = array_merge(self::getHeaders(), $headers);
142 142
 		}
143 143
 		
@@ -145,17 +145,17 @@  discard block
 block discarded – undo
145 145
 		 * Redirect user in the specified page
146 146
 		 * @param  string $path the URL or URI to be redirect to
147 147
 		 */
148
-		public static function redirect($path = ''){
148
+		public static function redirect($path = '') {
149 149
 			$logger = self::getLogger();
150 150
 			$url = Url::site_url($path);
151
-			$logger->info('Redirect to URL [' .$url. ']');
152
-			if(! headers_sent()){
153
-				header('Location: '.$url);
151
+			$logger->info('Redirect to URL [' . $url . ']');
152
+			if (!headers_sent()) {
153
+				header('Location: ' . $url);
154 154
 				exit;
155 155
 			}
156
-			else{
156
+			else {
157 157
 				echo '<script>
158
-						location.href = "'.$url.'";
158
+						location.href = "'.$url . '";
159 159
 					</script>';
160 160
 			}
161 161
 		}
@@ -168,10 +168,10 @@  discard block
 block discarded – undo
168 168
 		 * @return void|string          if $return is true will return the view content otherwise
169 169
 		 * will display the view content.
170 170
 		 */
171
-		public function render($view, $data = null, $return = false){
171
+		public function render($view, $data = null, $return = false) {
172 172
 			$logger = self::getLogger();
173 173
 			//convert data to an array
174
-			$data = ! is_array($data) ? (array) $data : $data;
174
+			$data = !is_array($data) ? (array) $data : $data;
175 175
 			$view = str_ireplace('.php', '', $view);
176 176
 			$view = trim($view, '/\\');
177 177
 			$viewFile = $view . '.php';
@@ -180,42 +180,42 @@  discard block
 block discarded – undo
180 180
 			//super instance
181 181
 			$obj = & get_instance();
182 182
 			
183
-			if(Module::hasModule()){
183
+			if (Module::hasModule()) {
184 184
 				//check in module first
185 185
 				$logger->debug('Checking the view [' . $view . '] from module list ...');
186 186
 				$mod = null;
187 187
 				//check if the request class contains module name
188
-				if(strpos($view, '/') !== false){
188
+				if (strpos($view, '/') !== false) {
189 189
 					$viewPath = explode('/', $view);
190
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
190
+					if (isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())) {
191 191
 						$mod = $viewPath[0];
192 192
 						array_shift($viewPath);
193 193
 						$view = implode('/', $viewPath);
194 194
 						$viewFile = $view . '.php';
195 195
 					}
196 196
 				}
197
-				if(! $mod && !empty($obj->moduleName)){
197
+				if (!$mod && !empty($obj->moduleName)) {
198 198
 					$mod = $obj->moduleName;
199 199
 				}
200
-				if($mod){
200
+				if ($mod) {
201 201
 					$moduleViewPath = Module::findViewFullPath($view, $mod);
202
-					if($moduleViewPath){
202
+					if ($moduleViewPath) {
203 203
 						$path = $moduleViewPath;
204
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
204
+						$logger->info('Found view [' . $view . '] in module [' . $mod . '], the file path is [' . $moduleViewPath . '] we will used it');
205 205
 					}
206
-					else{
207
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
206
+					else {
207
+						$logger->info('Cannot find view [' . $view . '] in module [' . $mod . '] using the default location');
208 208
 					}
209 209
 				}
210
-				else{
210
+				else {
211 211
 					$logger->info('The current request does not use module using the default location.');
212 212
 				}
213 213
 			}
214 214
 			$logger->info('The view file path to be loaded is [' . $path . ']');
215 215
 			$found = false;
216
-			if(file_exists($path)){
217
-				foreach(get_object_vars($obj) as $key => $value){
218
-					if(! isset($this->{$key})){
216
+			if (file_exists($path)) {
217
+				foreach (get_object_vars($obj) as $key => $value) {
218
+					if (!isset($this->{$key})) {
219 219
 						$this->{$key} = & $obj->{$key};
220 220
 					}
221 221
 				}
@@ -224,44 +224,44 @@  discard block
 block discarded – undo
224 224
 				//need use require() instead of require_once because can load this view many time
225 225
 				require $path;
226 226
 				$content = ob_get_clean();
227
-				if($return){
227
+				if ($return) {
228 228
 					return $content;
229 229
 				}
230 230
 				$this->_pageRender .= $content;
231 231
 				$found = true;
232 232
 			}
233
-			if(! $found){
234
-				show_error('Unable to find view [' .$view . ']');
233
+			if (!$found) {
234
+				show_error('Unable to find view [' . $view . ']');
235 235
 			}
236 236
 		}
237 237
 		
238 238
 		/**
239 239
 		* Send the final page output to user
240 240
 		*/
241
-		public function renderFinalPage(){
241
+		public function renderFinalPage() {
242 242
 			$logger = self::getLogger();
243 243
 			$obj = & get_instance();
244 244
 			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245 245
 			$dispatcher = $obj->eventdispatcher;
246 246
 			$content = $this->_pageRender;
247
-			if(! $content){
247
+			if (!$content) {
248 248
 				$logger->warning('The final view content is empty.');
249 249
 				return;
250 250
 			}
251 251
 			//dispatch
252 252
 			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
-			$content = ! empty($event->payload) ? $event->payload : null;
254
-			if(empty($content)){
253
+			$content = !empty($event->payload) ? $event->payload : null;
254
+			if (empty($content)) {
255 255
 				$logger->warning('The view content is empty after dispatch to event listeners.');
256 256
 			}
257 257
 			
258 258
 			//check whether need save the page into cache.
259
-			if($cachePageStatus){
259
+			if ($cachePageStatus) {
260 260
 				//current page URL
261 261
 				$url = $this->_currentUrl;
262 262
 				//Cache view Time to live in second
263 263
 				$viewCacheTtl = get_config('cache_ttl');
264
-				if (!empty($obj->view_cache_ttl)){
264
+				if (!empty($obj->view_cache_ttl)) {
265 265
 					$viewCacheTtl = $obj->view_cache_ttl;
266 266
 				}
267 267
 				//the cache handler instance
@@ -274,14 +274,14 @@  discard block
 block discarded – undo
274 274
 				
275 275
 				//get the cache information to prepare header to send to browser
276 276
 				$cacheInfo = $cacheInstance->getInfo($cacheKey);
277
-				if($cacheInfo){
277
+				if ($cacheInfo) {
278 278
 					$lastModified = $cacheInfo['mtime'];
279 279
 					$expire = $cacheInfo['expire'];
280 280
 					$maxAge = $expire - time();
281 281
 					self::setHeader('Pragma', 'public');
282 282
 					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
283
+					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
284
+					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');	
285 285
 				}
286 286
 			}
287 287
 			
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 			
294 294
 			//compress the output if is available
295 295
 			$type = null;
296
-			if (self::$_canCompressOutput){
296
+			if (self::$_canCompressOutput) {
297 297
 				$type = 'ob_gzhandler';
298 298
 			}
299 299
 			ob_start($type);
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 		/**
306 306
 		* Send the final page output to user if is cached
307 307
 		*/
308
-		public function renderFinalPageFromCache(&$cache){
308
+		public function renderFinalPageFromCache(&$cache) {
309 309
 			$logger = self::getLogger();
310 310
 			$url = $this->_currentUrl;					
311 311
 			//the current page cache key for identification
@@ -314,25 +314,25 @@  discard block
 block discarded – undo
314 314
 			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315 315
 			//get the cache information to prepare header to send to browser
316 316
 			$cacheInfo = $cache->getInfo($pageCacheKey);
317
-			if($cacheInfo){
317
+			if ($cacheInfo) {
318 318
 				$lastModified = $cacheInfo['mtime'];
319 319
 				$expire = $cacheInfo['expire'];
320 320
 				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
321 321
 				self::setHeader('Pragma', 'public');
322 322
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
323
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
324
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
325
+				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
326 326
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327 327
 					self::sendHeaders(304);
328 328
 					return;
329 329
 				}
330
-				else{
330
+				else {
331 331
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332 332
 					self::sendHeaders(200);
333 333
 					//get the cache content
334 334
 					$content = $cache->get($pageCacheKey);
335
-					if($content){
335
+					if ($content) {
336 336
 						$logger->info('The page content for the URL [' . $url . '] already cached just display it');
337 337
 						//load benchmark class
338 338
 						$benchmark = & class_loader('Benchmark');
@@ -345,17 +345,17 @@  discard block
 block discarded – undo
345 345
 						
346 346
 						///display the final output
347 347
 						//compress the output if is available
348
-						if (self::$_canCompressOutput){
348
+						if (self::$_canCompressOutput) {
349 349
 							ob_start('ob_gzhandler');
350 350
 						}
351
-						else{
351
+						else {
352 352
 							ob_start();
353 353
 						}
354 354
 						echo $content;
355 355
 						ob_end_flush();
356 356
 						return;
357 357
 					}
358
-					else{
358
+					else {
359 359
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360 360
 						$cache->delete($pageCacheKey);
361 361
 					}
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		* Get the final page to be rendered
368 368
 		* @return string
369 369
 		*/
370
-		public function getFinalPageRendered(){
370
+		public function getFinalPageRendered() {
371 371
 			return $this->_pageRender;
372 372
 		}
373 373
 
@@ -375,14 +375,14 @@  discard block
 block discarded – undo
375 375
 		 * Send the HTTP 404 error if can not found the 
376 376
 		 * routing information for the current request
377 377
 		 */
378
-		public static function send404(){
378
+		public static function send404() {
379 379
 			/********* for logs **************/
380 380
 			//can't use $obj = & get_instance()  here because the global super object will be available until
381 381
 			//the main controller is loaded even for Loader::library('xxxx');
382 382
 			$logger = self::getLogger();
383
-			$request =& class_loader('Request', 'classes');
384
-			$userAgent =& class_loader('Browser');
385
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
383
+			$request = & class_loader('Request', 'classes');
384
+			$userAgent = & class_loader('Browser');
385
+			$browser = $userAgent->getPlatform() . ', ' . $userAgent->getBrowser() . ' ' . $userAgent->getVersion();
386 386
 			
387 387
 			//here can't use Loader::functions just include the helper manually
388 388
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
@@ -392,12 +392,12 @@  discard block
 block discarded – undo
392 392
 			$logger->error($str);
393 393
 			/***********************************/
394 394
 			$path = CORE_VIEWS_PATH . '404.php';
395
-			if(file_exists($path)){
395
+			if (file_exists($path)) {
396 396
 				//compress the output if is available
397
-				if (self::$_canCompressOutput){
397
+				if (self::$_canCompressOutput) {
398 398
 					ob_start('ob_gzhandler');
399 399
 				}
400
-				else{
400
+				else {
401 401
 					ob_start();
402 402
 				}
403 403
 				require_once $path;
@@ -405,8 +405,8 @@  discard block
 block discarded – undo
405 405
 				self::sendHeaders(404);
406 406
 				echo $output;
407 407
 			}
408
-			else{
409
-				show_error('The 404 view [' .$path. '] does not exist');
408
+			else {
409
+				show_error('The 404 view [' . $path . '] does not exist');
410 410
 			}
411 411
 		}
412 412
 
@@ -414,14 +414,14 @@  discard block
 block discarded – undo
414 414
 		 * Display the error to user
415 415
 		 * @param  array  $data the error information
416 416
 		 */
417
-		public static function sendError(array $data = array()){
417
+		public static function sendError(array $data = array()) {
418 418
 			$path = CORE_VIEWS_PATH . 'errors.php';
419
-			if(file_exists($path)){
419
+			if (file_exists($path)) {
420 420
 				//compress the output if exists
421
-				if (self::$_canCompressOutput){
421
+				if (self::$_canCompressOutput) {
422 422
 					ob_start('ob_gzhandler');
423 423
 				}
424
-				else{
424
+				else {
425 425
 					ob_start();
426 426
 				}
427 427
 				extract($data);
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 				self::sendHeaders(503);
431 431
 				echo $output;
432 432
 			}
433
-			else{
433
+			else {
434 434
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435 435
 				set_http_status_header(503);
436 436
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Braces   +10 added lines, -20 removed lines patch added patch discarded remove patch
@@ -152,8 +152,7 @@  discard block
 block discarded – undo
152 152
 			if(! headers_sent()){
153 153
 				header('Location: '.$url);
154 154
 				exit;
155
-			}
156
-			else{
155
+			} else{
157 156
 				echo '<script>
158 157
 						location.href = "'.$url.'";
159 158
 					</script>';
@@ -202,12 +201,10 @@  discard block
 block discarded – undo
202 201
 					if($moduleViewPath){
203 202
 						$path = $moduleViewPath;
204 203
 						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
-					}
206
-					else{
204
+					} else{
207 205
 						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208 206
 					}
209
-				}
210
-				else{
207
+				} else{
211 208
 					$logger->info('The current request does not use module using the default location.');
212 209
 				}
213 210
 			}
@@ -326,8 +323,7 @@  discard block
 block discarded – undo
326 323
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327 324
 					self::sendHeaders(304);
328 325
 					return;
329
-				}
330
-				else{
326
+				} else{
331 327
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332 328
 					self::sendHeaders(200);
333 329
 					//get the cache content
@@ -347,15 +343,13 @@  discard block
 block discarded – undo
347 343
 						//compress the output if is available
348 344
 						if (self::$_canCompressOutput){
349 345
 							ob_start('ob_gzhandler');
350
-						}
351
-						else{
346
+						} else{
352 347
 							ob_start();
353 348
 						}
354 349
 						echo $content;
355 350
 						ob_end_flush();
356 351
 						return;
357
-					}
358
-					else{
352
+					} else{
359 353
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360 354
 						$cache->delete($pageCacheKey);
361 355
 					}
@@ -396,16 +390,14 @@  discard block
 block discarded – undo
396 390
 				//compress the output if is available
397 391
 				if (self::$_canCompressOutput){
398 392
 					ob_start('ob_gzhandler');
399
-				}
400
-				else{
393
+				} else{
401 394
 					ob_start();
402 395
 				}
403 396
 				require_once $path;
404 397
 				$output = ob_get_clean();
405 398
 				self::sendHeaders(404);
406 399
 				echo $output;
407
-			}
408
-			else{
400
+			} else{
409 401
 				show_error('The 404 view [' .$path. '] does not exist');
410 402
 			}
411 403
 		}
@@ -420,8 +412,7 @@  discard block
 block discarded – undo
420 412
 				//compress the output if exists
421 413
 				if (self::$_canCompressOutput){
422 414
 					ob_start('ob_gzhandler');
423
-				}
424
-				else{
415
+				} else{
425 416
 					ob_start();
426 417
 				}
427 418
 				extract($data);
@@ -429,8 +420,7 @@  discard block
 block discarded – undo
429 420
 				$output = ob_get_clean();
430 421
 				self::sendHeaders(503);
431 422
 				echo $output;
432
-			}
433
-			else{
423
+			} else{
434 424
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435 425
 				set_http_status_header(503);
436 426
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Indentation   +400 added lines, -400 removed lines patch added patch discarded remove patch
@@ -1,439 +1,439 @@
 block discarded – undo
1 1
 <?php
2
-	defined('ROOT_PATH') or exit('Access denied');
3
-	/**
4
-	 * TNH Framework
5
-	 *
6
-	 * A simple PHP framework using HMVC architecture
7
-	 *
8
-	 * This content is released under the GNU GPL License (GPL)
9
-	 *
10
-	 * Copyright (C) 2017 Tony NGUEREZA
11
-	 *
12
-	 * This program is free software; you can redistribute it and/or
13
-	 * modify it under the terms of the GNU General Public License
14
-	 * as published by the Free Software Foundation; either version 3
15
-	 * of the License, or (at your option) any later version.
16
-	 *
17
-	 * This program is distributed in the hope that it will be useful,
18
-	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-	 * GNU General Public License for more details.
21
-	 *
22
-	 * You should have received a copy of the GNU General Public License
23
-	 * along with this program; if not, write to the Free Software
24
-	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
2
+    defined('ROOT_PATH') or exit('Access denied');
3
+    /**
4
+     * TNH Framework
5
+     *
6
+     * A simple PHP framework using HMVC architecture
7
+     *
8
+     * This content is released under the GNU GPL License (GPL)
9
+     *
10
+     * Copyright (C) 2017 Tony NGUEREZA
11
+     *
12
+     * This program is free software; you can redistribute it and/or
13
+     * modify it under the terms of the GNU General Public License
14
+     * as published by the Free Software Foundation; either version 3
15
+     * of the License, or (at your option) any later version.
16
+     *
17
+     * This program is distributed in the hope that it will be useful,
18
+     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+     * GNU General Public License for more details.
21
+     *
22
+     * You should have received a copy of the GNU General Public License
23
+     * along with this program; if not, write to the Free Software
24
+     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+     */
26 26
 
27
-	class Response{
27
+    class Response{
28 28
 
29
-		/**
30
-		 * The list of request header to send with response
31
-		 * @var array
32
-		 */
33
-		private static $headers = array();
29
+        /**
30
+         * The list of request header to send with response
31
+         * @var array
32
+         */
33
+        private static $headers = array();
34 34
 
35
-		/**
36
-		 * The logger instance
37
-		 * @var Log
38
-		 */
39
-		private static $logger;
35
+        /**
36
+         * The logger instance
37
+         * @var Log
38
+         */
39
+        private static $logger;
40 40
 		
41
-		/**
42
-		 * The final page content to display to user
43
-		 * @var string
44
-		 */
45
-		private $_pageRender = null;
41
+        /**
42
+         * The final page content to display to user
43
+         * @var string
44
+         */
45
+        private $_pageRender = null;
46 46
 		
47
-		/**
48
-		 * The current request URL
49
-		 * @var string
50
-		 */
51
-		private $_currentUrl = null;
47
+        /**
48
+         * The current request URL
49
+         * @var string
50
+         */
51
+        private $_currentUrl = null;
52 52
 		
53
-		/**
54
-		 * The current request URL cache key
55
-		 * @var string
56
-		 */
57
-		private $_currentUrlCacheKey = null;
53
+        /**
54
+         * The current request URL cache key
55
+         * @var string
56
+         */
57
+        private $_currentUrlCacheKey = null;
58 58
 		
59
-		/**
60
-		* Whether we can compress the output using Gzip
61
-		* @var boolean
62
-		*/
63
-		private static $_canCompressOutput = false;
59
+        /**
60
+         * Whether we can compress the output using Gzip
61
+         * @var boolean
62
+         */
63
+        private static $_canCompressOutput = false;
64 64
 		
65
-		/**
66
-		 * Construct new response instance
67
-		 */
68
-		public function __construct(){
69
-			$this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
-					. (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
65
+        /**
66
+         * Construct new response instance
67
+         */
68
+        public function __construct(){
69
+            $this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
+                    . (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
71 71
 					
72
-			$this->_currentUrlCacheKey = md5($this->_currentUrl);
72
+            $this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
74
-			self::$_canCompressOutput = get_config('compress_output')
75
-										  && isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
76
-										  && stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false 
77
-										  && extension_loaded('zlib')
78
-										  && (bool) ini_get('zlib.output_compression') === false;
79
-		}
74
+            self::$_canCompressOutput = get_config('compress_output')
75
+                                          && isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
76
+                                          && stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false 
77
+                                          && extension_loaded('zlib')
78
+                                          && (bool) ini_get('zlib.output_compression') === false;
79
+        }
80 80
 
81
-		/**
82
-		 * Get the logger singleton instance
83
-		 * @return Log the logger instance
84
-		 */
85
-		private static function getLogger(){
86
-			if(self::$logger == null){
87
-				self::$logger[0] =& class_loader('Log', 'classes');
88
-				self::$logger[0]->setLogger('Library::Response');
89
-			}
90
-			return self::$logger[0];
91
-		}
81
+        /**
82
+         * Get the logger singleton instance
83
+         * @return Log the logger instance
84
+         */
85
+        private static function getLogger(){
86
+            if(self::$logger == null){
87
+                self::$logger[0] =& class_loader('Log', 'classes');
88
+                self::$logger[0]->setLogger('Library::Response');
89
+            }
90
+            return self::$logger[0];
91
+        }
92 92
 
93
-		/**
94
-		 * Send the HTTP Response headers
95
-		 * @param  integer $httpCode the HTTP status code
96
-		 * @param  array   $headers   the additional headers to add to the existing headers list
97
-		 */
98
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
99
-			set_http_status_header($httpCode);
100
-			self::setHeaders($headers);
101
-			if(! headers_sent()){
102
-				foreach(self::getHeaders() as $key => $value){
103
-					header($key .': '.$value);
104
-				}
105
-			}
106
-		}
93
+        /**
94
+         * Send the HTTP Response headers
95
+         * @param  integer $httpCode the HTTP status code
96
+         * @param  array   $headers   the additional headers to add to the existing headers list
97
+         */
98
+        public static function sendHeaders($httpCode = 200, array $headers = array()){
99
+            set_http_status_header($httpCode);
100
+            self::setHeaders($headers);
101
+            if(! headers_sent()){
102
+                foreach(self::getHeaders() as $key => $value){
103
+                    header($key .': '.$value);
104
+                }
105
+            }
106
+        }
107 107
 
108
-		/**
109
-		 * Get the list of the headers
110
-		 * @return array the headers list
111
-		 */
112
-		public static function getHeaders(){
113
-			return self::$headers;
114
-		}
108
+        /**
109
+         * Get the list of the headers
110
+         * @return array the headers list
111
+         */
112
+        public static function getHeaders(){
113
+            return self::$headers;
114
+        }
115 115
 
116
-		/**
117
-		 * Get the header value for the given name
118
-		 * @param  string $name the header name
119
-		 * @return string       the header value
120
-		 */
121
-		public static function getHeader($name){
122
-			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123
-		}
116
+        /**
117
+         * Get the header value for the given name
118
+         * @param  string $name the header name
119
+         * @return string       the header value
120
+         */
121
+        public static function getHeader($name){
122
+            return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123
+        }
124 124
 
125 125
 
126
-		/**
127
-		 * Set the header value for the specified name
128
-		 * @param string $name  the header name
129
-		 * @param string $value the header value to be set
130
-		 */
131
-		public static function setHeader($name, $value){
132
-			self::$headers[$name] = $value;
133
-		}
126
+        /**
127
+         * Set the header value for the specified name
128
+         * @param string $name  the header name
129
+         * @param string $value the header value to be set
130
+         */
131
+        public static function setHeader($name, $value){
132
+            self::$headers[$name] = $value;
133
+        }
134 134
 
135
-		/**
136
-		 * Set the headers using array
137
-		 * @param array $headers the list of the headers to set. 
138
-		 * Note: this will merge with the existing headers
139
-		 */
140
-		public static function setHeaders(array $headers){
141
-			self::$headers = array_merge(self::getHeaders(), $headers);
142
-		}
135
+        /**
136
+         * Set the headers using array
137
+         * @param array $headers the list of the headers to set. 
138
+         * Note: this will merge with the existing headers
139
+         */
140
+        public static function setHeaders(array $headers){
141
+            self::$headers = array_merge(self::getHeaders(), $headers);
142
+        }
143 143
 		
144
-		/**
145
-		 * Redirect user in the specified page
146
-		 * @param  string $path the URL or URI to be redirect to
147
-		 */
148
-		public static function redirect($path = ''){
149
-			$logger = self::getLogger();
150
-			$url = Url::site_url($path);
151
-			$logger->info('Redirect to URL [' .$url. ']');
152
-			if(! headers_sent()){
153
-				header('Location: '.$url);
154
-				exit;
155
-			}
156
-			else{
157
-				echo '<script>
144
+        /**
145
+         * Redirect user in the specified page
146
+         * @param  string $path the URL or URI to be redirect to
147
+         */
148
+        public static function redirect($path = ''){
149
+            $logger = self::getLogger();
150
+            $url = Url::site_url($path);
151
+            $logger->info('Redirect to URL [' .$url. ']');
152
+            if(! headers_sent()){
153
+                header('Location: '.$url);
154
+                exit;
155
+            }
156
+            else{
157
+                echo '<script>
158 158
 						location.href = "'.$url.'";
159 159
 					</script>';
160
-			}
161
-		}
160
+            }
161
+        }
162 162
 
163
-		/**
164
-		 * Render the view to display later or return the content
165
-		 * @param  string  $view   the view name or path
166
-		 * @param  array|object   $data   the variable data to use in the view
167
-		 * @param  boolean $return whether to return the view generated content or display it directly
168
-		 * @return void|string          if $return is true will return the view content otherwise
169
-		 * will display the view content.
170
-		 */
171
-		public function render($view, $data = null, $return = false){
172
-			$logger = self::getLogger();
173
-			//convert data to an array
174
-			$data = ! is_array($data) ? (array) $data : $data;
175
-			$view = str_ireplace('.php', '', $view);
176
-			$view = trim($view, '/\\');
177
-			$viewFile = $view . '.php';
178
-			$path = APPS_VIEWS_PATH . $viewFile;
163
+        /**
164
+         * Render the view to display later or return the content
165
+         * @param  string  $view   the view name or path
166
+         * @param  array|object   $data   the variable data to use in the view
167
+         * @param  boolean $return whether to return the view generated content or display it directly
168
+         * @return void|string          if $return is true will return the view content otherwise
169
+         * will display the view content.
170
+         */
171
+        public function render($view, $data = null, $return = false){
172
+            $logger = self::getLogger();
173
+            //convert data to an array
174
+            $data = ! is_array($data) ? (array) $data : $data;
175
+            $view = str_ireplace('.php', '', $view);
176
+            $view = trim($view, '/\\');
177
+            $viewFile = $view . '.php';
178
+            $path = APPS_VIEWS_PATH . $viewFile;
179 179
 			
180
-			//super instance
181
-			$obj = & get_instance();
180
+            //super instance
181
+            $obj = & get_instance();
182 182
 			
183
-			if(Module::hasModule()){
184
-				//check in module first
185
-				$logger->debug('Checking the view [' . $view . '] from module list ...');
186
-				$mod = null;
187
-				//check if the request class contains module name
188
-				if(strpos($view, '/') !== false){
189
-					$viewPath = explode('/', $view);
190
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
191
-						$mod = $viewPath[0];
192
-						array_shift($viewPath);
193
-						$view = implode('/', $viewPath);
194
-						$viewFile = $view . '.php';
195
-					}
196
-				}
197
-				if(! $mod && !empty($obj->moduleName)){
198
-					$mod = $obj->moduleName;
199
-				}
200
-				if($mod){
201
-					$moduleViewPath = Module::findViewFullPath($view, $mod);
202
-					if($moduleViewPath){
203
-						$path = $moduleViewPath;
204
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
-					}
206
-					else{
207
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208
-					}
209
-				}
210
-				else{
211
-					$logger->info('The current request does not use module using the default location.');
212
-				}
213
-			}
214
-			$logger->info('The view file path to be loaded is [' . $path . ']');
215
-			$found = false;
216
-			if(file_exists($path)){
217
-				foreach(get_object_vars($obj) as $key => $value){
218
-					if(! isset($this->{$key})){
219
-						$this->{$key} = & $obj->{$key};
220
-					}
221
-				}
222
-				ob_start();
223
-				extract($data);
224
-				//need use require() instead of require_once because can load this view many time
225
-				require $path;
226
-				$content = ob_get_clean();
227
-				if($return){
228
-					return $content;
229
-				}
230
-				$this->_pageRender .= $content;
231
-				$found = true;
232
-			}
233
-			if(! $found){
234
-				show_error('Unable to find view [' .$view . ']');
235
-			}
236
-		}
183
+            if(Module::hasModule()){
184
+                //check in module first
185
+                $logger->debug('Checking the view [' . $view . '] from module list ...');
186
+                $mod = null;
187
+                //check if the request class contains module name
188
+                if(strpos($view, '/') !== false){
189
+                    $viewPath = explode('/', $view);
190
+                    if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
191
+                        $mod = $viewPath[0];
192
+                        array_shift($viewPath);
193
+                        $view = implode('/', $viewPath);
194
+                        $viewFile = $view . '.php';
195
+                    }
196
+                }
197
+                if(! $mod && !empty($obj->moduleName)){
198
+                    $mod = $obj->moduleName;
199
+                }
200
+                if($mod){
201
+                    $moduleViewPath = Module::findViewFullPath($view, $mod);
202
+                    if($moduleViewPath){
203
+                        $path = $moduleViewPath;
204
+                        $logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
+                    }
206
+                    else{
207
+                        $logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208
+                    }
209
+                }
210
+                else{
211
+                    $logger->info('The current request does not use module using the default location.');
212
+                }
213
+            }
214
+            $logger->info('The view file path to be loaded is [' . $path . ']');
215
+            $found = false;
216
+            if(file_exists($path)){
217
+                foreach(get_object_vars($obj) as $key => $value){
218
+                    if(! isset($this->{$key})){
219
+                        $this->{$key} = & $obj->{$key};
220
+                    }
221
+                }
222
+                ob_start();
223
+                extract($data);
224
+                //need use require() instead of require_once because can load this view many time
225
+                require $path;
226
+                $content = ob_get_clean();
227
+                if($return){
228
+                    return $content;
229
+                }
230
+                $this->_pageRender .= $content;
231
+                $found = true;
232
+            }
233
+            if(! $found){
234
+                show_error('Unable to find view [' .$view . ']');
235
+            }
236
+        }
237 237
 		
238
-		/**
239
-		* Send the final page output to user
240
-		*/
241
-		public function renderFinalPage(){
242
-			$logger = self::getLogger();
243
-			$obj = & get_instance();
244
-			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245
-			$dispatcher = $obj->eventdispatcher;
246
-			$content = $this->_pageRender;
247
-			if(! $content){
248
-				$logger->warning('The final view content is empty.');
249
-				return;
250
-			}
251
-			//dispatch
252
-			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
-			$content = ! empty($event->payload) ? $event->payload : null;
254
-			if(empty($content)){
255
-				$logger->warning('The view content is empty after dispatch to event listeners.');
256
-			}
238
+        /**
239
+         * Send the final page output to user
240
+         */
241
+        public function renderFinalPage(){
242
+            $logger = self::getLogger();
243
+            $obj = & get_instance();
244
+            $cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245
+            $dispatcher = $obj->eventdispatcher;
246
+            $content = $this->_pageRender;
247
+            if(! $content){
248
+                $logger->warning('The final view content is empty.');
249
+                return;
250
+            }
251
+            //dispatch
252
+            $event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
+            $content = ! empty($event->payload) ? $event->payload : null;
254
+            if(empty($content)){
255
+                $logger->warning('The view content is empty after dispatch to event listeners.');
256
+            }
257 257
 			
258
-			//check whether need save the page into cache.
259
-			if($cachePageStatus){
260
-				//current page URL
261
-				$url = $this->_currentUrl;
262
-				//Cache view Time to live in second
263
-				$viewCacheTtl = get_config('cache_ttl');
264
-				if (!empty($obj->view_cache_ttl)){
265
-					$viewCacheTtl = $obj->view_cache_ttl;
266
-				}
267
-				//the cache handler instance
268
-				$cacheInstance = $obj->cache;
269
-				//the current page cache key for identification
270
-				$cacheKey = $this->_currentUrlCacheKey;
258
+            //check whether need save the page into cache.
259
+            if($cachePageStatus){
260
+                //current page URL
261
+                $url = $this->_currentUrl;
262
+                //Cache view Time to live in second
263
+                $viewCacheTtl = get_config('cache_ttl');
264
+                if (!empty($obj->view_cache_ttl)){
265
+                    $viewCacheTtl = $obj->view_cache_ttl;
266
+                }
267
+                //the cache handler instance
268
+                $cacheInstance = $obj->cache;
269
+                //the current page cache key for identification
270
+                $cacheKey = $this->_currentUrlCacheKey;
271 271
 				
272
-				$logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
273
-				$cacheInstance->set($cacheKey, $content, $viewCacheTtl);
272
+                $logger->debug('Save the page content for URL [' . $url . '] into the cache ...');
273
+                $cacheInstance->set($cacheKey, $content, $viewCacheTtl);
274 274
 				
275
-				//get the cache information to prepare header to send to browser
276
-				$cacheInfo = $cacheInstance->getInfo($cacheKey);
277
-				if($cacheInfo){
278
-					$lastModified = $cacheInfo['mtime'];
279
-					$expire = $cacheInfo['expire'];
280
-					$maxAge = $expire - time();
281
-					self::setHeader('Pragma', 'public');
282
-					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
285
-				}
286
-			}
275
+                //get the cache information to prepare header to send to browser
276
+                $cacheInfo = $cacheInstance->getInfo($cacheKey);
277
+                if($cacheInfo){
278
+                    $lastModified = $cacheInfo['mtime'];
279
+                    $expire = $cacheInfo['expire'];
280
+                    $maxAge = $expire - time();
281
+                    self::setHeader('Pragma', 'public');
282
+                    self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
+                    self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
+                    self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
285
+                }
286
+            }
287 287
 			
288
-			// Parse out the elapsed time and memory usage,
289
-			// then swap the pseudo-variables with the data
290
-			$elapsedTime = $obj->benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
291
-			$memoryUsage	= round($obj->benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
292
-			$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
288
+            // Parse out the elapsed time and memory usage,
289
+            // then swap the pseudo-variables with the data
290
+            $elapsedTime = $obj->benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
291
+            $memoryUsage	= round($obj->benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
292
+            $content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
293 293
 			
294
-			//compress the output if is available
295
-			$type = null;
296
-			if (self::$_canCompressOutput){
297
-				$type = 'ob_gzhandler';
298
-			}
299
-			ob_start($type);
300
-			self::sendHeaders(200);
301
-			echo $content;
302
-			ob_end_flush();
303
-		}
294
+            //compress the output if is available
295
+            $type = null;
296
+            if (self::$_canCompressOutput){
297
+                $type = 'ob_gzhandler';
298
+            }
299
+            ob_start($type);
300
+            self::sendHeaders(200);
301
+            echo $content;
302
+            ob_end_flush();
303
+        }
304 304
 		
305
-		/**
306
-		* Send the final page output to user if is cached
307
-		*/
308
-		public function renderFinalPageFromCache(&$cache){
309
-			$logger = self::getLogger();
310
-			$url = $this->_currentUrl;					
311
-			//the current page cache key for identification
312
-			$pageCacheKey = $this->_currentUrlCacheKey;
305
+        /**
306
+         * Send the final page output to user if is cached
307
+         */
308
+        public function renderFinalPageFromCache(&$cache){
309
+            $logger = self::getLogger();
310
+            $url = $this->_currentUrl;					
311
+            //the current page cache key for identification
312
+            $pageCacheKey = $this->_currentUrlCacheKey;
313 313
 			
314
-			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315
-			//get the cache information to prepare header to send to browser
316
-			$cacheInfo = $cache->getInfo($pageCacheKey);
317
-			if($cacheInfo){
318
-				$lastModified = $cacheInfo['mtime'];
319
-				$expire = $cacheInfo['expire'];
320
-				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
321
-				self::setHeader('Pragma', 'public');
322
-				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
326
-					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327
-					self::sendHeaders(304);
328
-					return;
329
-				}
330
-				else{
331
-					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332
-					self::sendHeaders(200);
333
-					//get the cache content
334
-					$content = $cache->get($pageCacheKey);
335
-					if($content){
336
-						$logger->info('The page content for the URL [' . $url . '] already cached just display it');
337
-						//load benchmark class
338
-						$benchmark = & class_loader('Benchmark');
314
+            $logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315
+            //get the cache information to prepare header to send to browser
316
+            $cacheInfo = $cache->getInfo($pageCacheKey);
317
+            if($cacheInfo){
318
+                $lastModified = $cacheInfo['mtime'];
319
+                $expire = $cacheInfo['expire'];
320
+                $maxAge = $expire - $_SERVER['REQUEST_TIME'];
321
+                self::setHeader('Pragma', 'public');
322
+                self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
+                self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
+                self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
+                if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
326
+                    $logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327
+                    self::sendHeaders(304);
328
+                    return;
329
+                }
330
+                else{
331
+                    $logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332
+                    self::sendHeaders(200);
333
+                    //get the cache content
334
+                    $content = $cache->get($pageCacheKey);
335
+                    if($content){
336
+                        $logger->info('The page content for the URL [' . $url . '] already cached just display it');
337
+                        //load benchmark class
338
+                        $benchmark = & class_loader('Benchmark');
339 339
 						
340
-						// Parse out the elapsed time and memory usage,
341
-						// then swap the pseudo-variables with the data
342
-						$elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
343
-						$memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
344
-						$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
340
+                        // Parse out the elapsed time and memory usage,
341
+                        // then swap the pseudo-variables with the data
342
+                        $elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END');
343
+                        $memoryUsage	= round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB';
344
+                        $content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
345 345
 						
346
-						///display the final output
347
-						//compress the output if is available
348
-						if (self::$_canCompressOutput){
349
-							ob_start('ob_gzhandler');
350
-						}
351
-						else{
352
-							ob_start();
353
-						}
354
-						echo $content;
355
-						ob_end_flush();
356
-						return;
357
-					}
358
-					else{
359
-						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360
-						$cache->delete($pageCacheKey);
361
-					}
362
-				}
363
-			}
364
-		}
346
+                        ///display the final output
347
+                        //compress the output if is available
348
+                        if (self::$_canCompressOutput){
349
+                            ob_start('ob_gzhandler');
350
+                        }
351
+                        else{
352
+                            ob_start();
353
+                        }
354
+                        echo $content;
355
+                        ob_end_flush();
356
+                        return;
357
+                    }
358
+                    else{
359
+                        $logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360
+                        $cache->delete($pageCacheKey);
361
+                    }
362
+                }
363
+            }
364
+        }
365 365
 		
366
-		/**
367
-		* Get the final page to be rendered
368
-		* @return string
369
-		*/
370
-		public function getFinalPageRendered(){
371
-			return $this->_pageRender;
372
-		}
366
+        /**
367
+         * Get the final page to be rendered
368
+         * @return string
369
+         */
370
+        public function getFinalPageRendered(){
371
+            return $this->_pageRender;
372
+        }
373 373
 
374
-		/**
375
-		 * Send the HTTP 404 error if can not found the 
376
-		 * routing information for the current request
377
-		 */
378
-		public static function send404(){
379
-			/********* for logs **************/
380
-			//can't use $obj = & get_instance()  here because the global super object will be available until
381
-			//the main controller is loaded even for Loader::library('xxxx');
382
-			$logger = self::getLogger();
383
-			$request =& class_loader('Request', 'classes');
384
-			$userAgent =& class_loader('Browser');
385
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
374
+        /**
375
+         * Send the HTTP 404 error if can not found the 
376
+         * routing information for the current request
377
+         */
378
+        public static function send404(){
379
+            /********* for logs **************/
380
+            //can't use $obj = & get_instance()  here because the global super object will be available until
381
+            //the main controller is loaded even for Loader::library('xxxx');
382
+            $logger = self::getLogger();
383
+            $request =& class_loader('Request', 'classes');
384
+            $userAgent =& class_loader('Browser');
385
+            $browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
386 386
 			
387
-			//here can't use Loader::functions just include the helper manually
388
-			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
387
+            //here can't use Loader::functions just include the helper manually
388
+            require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
389 389
 
390
-			$str = '[404 page not found] : ';
391
-			$str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
392
-			$logger->error($str);
393
-			/***********************************/
394
-			$path = CORE_VIEWS_PATH . '404.php';
395
-			if(file_exists($path)){
396
-				//compress the output if is available
397
-				if (self::$_canCompressOutput){
398
-					ob_start('ob_gzhandler');
399
-				}
400
-				else{
401
-					ob_start();
402
-				}
403
-				require_once $path;
404
-				$output = ob_get_clean();
405
-				self::sendHeaders(404);
406
-				echo $output;
407
-			}
408
-			else{
409
-				show_error('The 404 view [' .$path. '] does not exist');
410
-			}
411
-		}
390
+            $str = '[404 page not found] : ';
391
+            $str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']';
392
+            $logger->error($str);
393
+            /***********************************/
394
+            $path = CORE_VIEWS_PATH . '404.php';
395
+            if(file_exists($path)){
396
+                //compress the output if is available
397
+                if (self::$_canCompressOutput){
398
+                    ob_start('ob_gzhandler');
399
+                }
400
+                else{
401
+                    ob_start();
402
+                }
403
+                require_once $path;
404
+                $output = ob_get_clean();
405
+                self::sendHeaders(404);
406
+                echo $output;
407
+            }
408
+            else{
409
+                show_error('The 404 view [' .$path. '] does not exist');
410
+            }
411
+        }
412 412
 
413
-		/**
414
-		 * Display the error to user
415
-		 * @param  array  $data the error information
416
-		 */
417
-		public static function sendError(array $data = array()){
418
-			$path = CORE_VIEWS_PATH . 'errors.php';
419
-			if(file_exists($path)){
420
-				//compress the output if exists
421
-				if (self::$_canCompressOutput){
422
-					ob_start('ob_gzhandler');
423
-				}
424
-				else{
425
-					ob_start();
426
-				}
427
-				extract($data);
428
-				require_once $path;
429
-				$output = ob_get_clean();
430
-				self::sendHeaders(503);
431
-				echo $output;
432
-			}
433
-			else{
434
-				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435
-				set_http_status_header(503);
436
-				echo 'The error view [' . $path . '] does not exist';
437
-			}
438
-		}
439
-	}
413
+        /**
414
+         * Display the error to user
415
+         * @param  array  $data the error information
416
+         */
417
+        public static function sendError(array $data = array()){
418
+            $path = CORE_VIEWS_PATH . 'errors.php';
419
+            if(file_exists($path)){
420
+                //compress the output if exists
421
+                if (self::$_canCompressOutput){
422
+                    ob_start('ob_gzhandler');
423
+                }
424
+                else{
425
+                    ob_start();
426
+                }
427
+                extract($data);
428
+                require_once $path;
429
+                $output = ob_get_clean();
430
+                self::sendHeaders(503);
431
+                echo $output;
432
+            }
433
+            else{
434
+                //can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435
+                set_http_status_header(503);
436
+                echo 'The error view [' . $path . '] does not exist';
437
+            }
438
+        }
439
+    }
Please login to merge, or discard this patch.