GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( 7d455c...f6fa23 )
by Lonnie
07:56
created
myth/Auth/AuthTrait.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 	 * @param null $uri
55 55
 	 * @param bool $return_only
56 56
 	 *
57
-	 * @return bool
57
+	 * @return boolean|null
58 58
 	 */
59 59
 	public function restrict($uri=null, $return_only=false)
60 60
 	{
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	 * @param mixed  $groups
105 105
 	 * @param string $uri   The URI to redirect to on fail.
106 106
 	 *
107
-	 * @return bool
107
+	 * @return boolean|null
108 108
 	 */
109 109
 	public function restrictToGroups($groups, $uri='')
110 110
 	{
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 	 * @param $permissions
146 146
 	 * @param string $uri   The URI to redirect to on fail.
147 147
 	 *
148
-	 * @return bool
148
+	 * @return boolean|null
149 149
 	 */
150 150
 	public function restrictWithPermissions($permissions, $uri='')
151 151
 	{
Please login to merge, or discard this patch.
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -1,34 +1,34 @@  discard block
 block discarded – undo
1 1
 <?php namespace Myth\Auth;
2 2
 /**
3
- * Sprint
4
- *
5
- * A set of power tools to enhance the CodeIgniter framework and provide consistent workflow.
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in
15
- * all copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
- * THE SOFTWARE.
24
- *
25
- * @package     Sprint
26
- * @author      Lonnie Ezell
27
- * @copyright   Copyright 2014-2015, New Myth Media, LLC (http://newmythmedia.com)
28
- * @license     http://opensource.org/licenses/MIT  (MIT)
29
- * @link        http://sprintphp.com
30
- * @since       Version 1.0
31
- */
3
+	 * Sprint
4
+	 *
5
+	 * A set of power tools to enhance the CodeIgniter framework and provide consistent workflow.
6
+	 *
7
+	 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+	 * of this software and associated documentation files (the "Software"), to deal
9
+	 * in the Software without restriction, including without limitation the rights
10
+	 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+	 * copies of the Software, and to permit persons to whom the Software is
12
+	 * furnished to do so, subject to the following conditions:
13
+	 *
14
+	 * The above copyright notice and this permission notice shall be included in
15
+	 * all copies or substantial portions of the Software.
16
+	 *
17
+	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+	 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+	 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+	 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+	 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+	 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+	 * THE SOFTWARE.
24
+	 *
25
+	 * @package     Sprint
26
+	 * @author      Lonnie Ezell
27
+	 * @copyright   Copyright 2014-2015, New Myth Media, LLC (http://newmythmedia.com)
28
+	 * @license     http://opensource.org/licenses/MIT  (MIT)
29
+	 * @link        http://sprintphp.com
30
+	 * @since       Version 1.0
31
+	 */
32 32
 
33 33
 trait AuthTrait {
34 34
 
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	 */
59 59
 	public function restrict($uri=null, $return_only=false)
60 60
 	{
61
-	    $this->setupAuthClasses();
61
+		$this->setupAuthClasses();
62 62
 
63 63
 		if ($this->authenticate->isLoggedIn())
64 64
 		{
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	 */
109 109
 	public function restrictToGroups($groups, $uri='')
110 110
 	{
111
-	    $this->setupAuthClasses();
111
+		$this->setupAuthClasses();
112 112
 
113 113
 		if ($this->authenticate->isLoggedIn())
114 114
 		{
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 	 */
150 150
 	public function restrictWithPermissions($permissions, $uri='')
151 151
 	{
152
-	    $this->setupAuthClasses();
152
+		$this->setupAuthClasses();
153 153
 
154 154
 		if ($this->authenticate->isLoggedIn())
155 155
 		{
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	 *
57 57
 	 * @return bool
58 58
 	 */
59
-	public function restrict($uri=null, $return_only=false)
59
+	public function restrict($uri = null, $return_only = false)
60 60
 	{
61 61
 	    $this->setupAuthClasses();
62 62
 
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 
68 68
 		if (method_exists($this, 'setMessage'))
69 69
 		{
70
-			$this->setMessage( lang('auth.not_logged_in') );
70
+			$this->setMessage(lang('auth.not_logged_in'));
71 71
 		}
72 72
 
73 73
 		if ($return_only)
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 
78 78
 		if (empty($uri))
79 79
 		{
80
-			redirect( \Myth\Route::named('login') );
80
+			redirect(\Myth\Route::named('login'));
81 81
 		}
82 82
 
83 83
 		redirect($uri);
@@ -106,13 +106,13 @@  discard block
 block discarded – undo
106 106
 	 *
107 107
 	 * @return bool
108 108
 	 */
109
-	public function restrictToGroups($groups, $uri='')
109
+	public function restrictToGroups($groups, $uri = '')
110 110
 	{
111 111
 	    $this->setupAuthClasses();
112 112
 
113 113
 		if ($this->authenticate->isLoggedIn())
114 114
 		{
115
-			if ($this->authorize->inGroup($groups, $this->authenticate->id() ) )
115
+			if ($this->authorize->inGroup($groups, $this->authenticate->id()))
116 116
 			{
117 117
 				return true;
118 118
 			}
@@ -120,15 +120,15 @@  discard block
 block discarded – undo
120 120
 
121 121
 		if (method_exists($this, 'setMessage'))
122 122
 		{
123
-			$this->setMessage( lang('auth.not_enough_privilege') );
123
+			$this->setMessage(lang('auth.not_enough_privilege'));
124 124
 		}
125 125
 
126 126
 		if (empty($uri))
127 127
 		{
128
-			redirect( \Myth\Route::named('login') .'?request_uri='. current_url() );
128
+			redirect(\Myth\Route::named('login').'?request_uri='.current_url());
129 129
 		}
130 130
 
131
-		redirect($uri .'?request_uri='. current_url());
131
+		redirect($uri.'?request_uri='.current_url());
132 132
 	}
133 133
 
134 134
 	//--------------------------------------------------------------------
@@ -147,13 +147,13 @@  discard block
 block discarded – undo
147 147
 	 *
148 148
 	 * @return bool
149 149
 	 */
150
-	public function restrictWithPermissions($permissions, $uri='')
150
+	public function restrictWithPermissions($permissions, $uri = '')
151 151
 	{
152 152
 	    $this->setupAuthClasses();
153 153
 
154 154
 		if ($this->authenticate->isLoggedIn())
155 155
 		{
156
-			if ($this->authorize->hasPermission($permissions, $this->authenticate->id() ) )
156
+			if ($this->authorize->hasPermission($permissions, $this->authenticate->id()))
157 157
 			{
158 158
 				return true;
159 159
 			}
@@ -161,15 +161,15 @@  discard block
 block discarded – undo
161 161
 
162 162
 		if (method_exists($this, 'setMessage'))
163 163
 		{
164
-			$this->setMessage( lang('auth.not_enough_privilege') );
164
+			$this->setMessage(lang('auth.not_enough_privilege'));
165 165
 		}
166 166
 
167 167
 		if (empty($uri))
168 168
 		{
169
-			redirect( \Myth\Route::named('login') .'?request_uri='. current_url() );
169
+			redirect(\Myth\Route::named('login').'?request_uri='.current_url());
170 170
 		}
171 171
 
172
-		redirect($uri .'?request_uri='. current_url());
172
+		redirect($uri.'?request_uri='.current_url());
173 173
 	}
174 174
 
175 175
 	//--------------------------------------------------------------------
@@ -198,16 +198,16 @@  discard block
 block discarded – undo
198 198
 		$auth = config_item('auth.authenticate_lib');
199 199
 
200 200
 		if (empty($auth)) {
201
-			throw new \RuntimeException( lang('auth.no_authenticate') );
201
+			throw new \RuntimeException(lang('auth.no_authenticate'));
202 202
 		}
203 203
 
204
-		$this->authenticate = new $auth( get_instance() );
204
+		$this->authenticate = new $auth(get_instance());
205 205
 
206 206
 		get_instance()->load->model('auth/user_model', 'user_model', true);
207
-		$this->authenticate->useModel( get_instance()->user_model );
207
+		$this->authenticate->useModel(get_instance()->user_model);
208 208
 
209 209
 		// Try to log us in automatically.
210
-		if (! $this->authenticate->isLoggedIn())
210
+		if ( ! $this->authenticate->isLoggedIn())
211 211
 		{
212 212
 			$this->authenticate->viaRemember();
213 213
 		}
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 		$auth = config_item('auth.authorize_lib');
219 219
 
220 220
 		if (empty($auth)) {
221
-			throw new \RuntimeException( lang('auth.no_authenticate') );
221
+			throw new \RuntimeException(lang('auth.no_authenticate'));
222 222
 		}
223 223
 
224 224
 		$this->authorize = new $auth();
Please login to merge, or discard this patch.
myth/Auth/FlatAuthorization.php 3 patches
Doc Comments   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	 * model that should be used.
69 69
 	 *
70 70
 	 * @param $model
71
-	 * @return mixed
71
+	 * @return FlatAuthorization
72 72
 	 */
73 73
 	public function useModel($model)
74 74
 	{
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 	 *
93 93
 	 * @param $groups
94 94
 	 *
95
-	 * @return bool
95
+	 * @return null|boolean
96 96
 	 */
97 97
 	public function inGroup( $groups, $user_id )
98 98
 	{
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 	 * @param int|string $permission
146 146
 	 * @param int|string $user_id
147 147
 	 *
148
-	 * @return mixed
148
+	 * @return null|boolean
149 149
 	 */
150 150
 	public function hasPermission( $permission, $user_id )
151 151
 	{
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	 * @param $user_id
186 186
 	 * @param $group // Either ID or name
187 187
 	 *
188
-	 * @return bool
188
+	 * @return null|boolean
189 189
 	 */
190 190
 	public function addUserToGroup( $user_id, $group )
191 191
 	{
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 	 * @param $user_id
233 233
 	 * @param $group
234 234
 	 *
235
-	 * @return mixed
235
+	 * @return null|boolean
236 236
 	 */
237 237
 	public function removeUserFromGroup( $user_id, $group )
238 238
 	{
@@ -276,10 +276,10 @@  discard block
 block discarded – undo
276 276
 	/**
277 277
 	 * Adds a single permission to a single group.
278 278
 	 *
279
-	 * @param int|string $permission
280
-	 * @param int|string $group
279
+	 * @param string $permission
280
+	 * @param string $group
281 281
 	 *
282
-	 * @return mixed
282
+	 * @return boolean
283 283
 	 */
284 284
 	public function addPermissionToGroup( $permission, $group )
285 285
 	{
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 	 * @param int|string $permission
318 318
 	 * @param int|string $group
319 319
 	 *
320
-	 * @return mixed
320
+	 * @return boolean
321 321
 	 */
322 322
 	public function removePermissionFromGroup( $permission, $group )
323 323
 	{
@@ -455,8 +455,8 @@  discard block
 block discarded – undo
455 455
 	/**
456 456
 	 * Checks to see if a user has private permission assigned to it.
457 457
 	 *
458
-	 * @param $user_id
459
-	 * @param $permission
458
+	 * @param integer $user_id
459
+	 * @param integer $permission
460 460
 	 *
461 461
 	 * @return bool|null
462 462
 	 */
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	//--------------------------------------------------------------------
532 532
 
533 533
 	/**
534
-	 * @param $name
534
+	 * @param string $name
535 535
 	 * @param string $description
536 536
 	 *
537 537
 	 * @return mixed
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 	 * @param $name
586 586
 	 * @param string $description
587 587
 	 *
588
-	 * @return mixed
588
+	 * @return boolean
589 589
 	 */
590 590
 	public function updateGroup( $id, $name, $description = '' )
591 591
 	{
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
 	/**
678 678
 	 * Creates a single permission.
679 679
 	 *
680
-	 * @param $name
680
+	 * @param string $name
681 681
 	 * @param string $description
682 682
 	 *
683 683
 	 * @return mixed
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 	 *
709 709
 	 * @param $permission
710 710
 	 *
711
-	 * @return mixed
711
+	 * @return boolean
712 712
 	 */
713 713
 	public function deletePermission( $permission_id )
714 714
 	{
Please login to merge, or discard this patch.
Spacing   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 	public function __construct($groupModel = null, $permModel = null)
50 50
 	{
51 51
 		$this->groupModel      = ! empty($groupModel) ? $groupModel : new FlatGroupsModel();
52
-		$this->permissionModel = ! empty($permModel)  ? $permModel  : new FlatPermissionsModel();
52
+		$this->permissionModel = ! empty($permModel) ? $permModel : new FlatPermissionsModel();
53 53
 
54 54
 		get_instance()->load->language('auth/auth');
55 55
 	}
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	 */
73 73
 	public function useModel($model)
74 74
 	{
75
-		$this->user_model =& $model;
75
+		$this->user_model = & $model;
76 76
 
77 77
 		return $this;
78 78
 	}
@@ -94,11 +94,11 @@  discard block
 block discarded – undo
94 94
 	 *
95 95
 	 * @return bool
96 96
 	 */
97
-	public function inGroup( $groups, $user_id )
97
+	public function inGroup($groups, $user_id)
98 98
 	{
99
-		if ( ! is_array( $groups ) )
99
+		if ( ! is_array($groups))
100 100
 		{
101
-			$groups = [ $groups ];
101
+			$groups = [$groups];
102 102
 		}
103 103
 
104 104
 		if (empty($user_id))
@@ -106,14 +106,14 @@  discard block
 block discarded – undo
106 106
 			return null;
107 107
 		}
108 108
 
109
-		$user_groups = $this->groupModel->getGroupsForUser( (int) $user_id );
109
+		$user_groups = $this->groupModel->getGroupsForUser((int) $user_id);
110 110
 
111
-		if ( ! $user_groups )
111
+		if ( ! $user_groups)
112 112
 		{
113 113
 			return false;
114 114
 		}
115 115
 
116
-		foreach ( $groups as $group )
116
+		foreach ($groups as $group)
117 117
 		{
118 118
 			if (is_numeric($group))
119 119
 			{
@@ -147,9 +147,9 @@  discard block
 block discarded – undo
147 147
 	 *
148 148
 	 * @return mixed
149 149
 	 */
150
-	public function hasPermission( $permission, $user_id )
150
+	public function hasPermission($permission, $user_id)
151 151
 	{
152
-		if (empty($permission) || (! is_string($permission) && ! is_numeric($permission)) )
152
+		if (empty($permission) || ( ! is_string($permission) && ! is_numeric($permission)))
153 153
 		{
154 154
 			return null;
155 155
 		}
@@ -162,19 +162,19 @@  discard block
 block discarded – undo
162 162
 		// Get the Permission ID
163 163
 		$permission_id = $this->getPermissionID($permission);
164 164
 
165
-		if ( ! is_numeric( $permission_id ) )
165
+		if ( ! is_numeric($permission_id))
166 166
 		{
167 167
 			return false;
168 168
 		}
169 169
 
170 170
 		// First check the permission model. If that exists, then we're golden.
171
-		if ($this->permissionModel->doesUserHavePermission( (int)$user_id, (int)$permission_id ) )
171
+		if ($this->permissionModel->doesUserHavePermission((int) $user_id, (int) $permission_id))
172 172
 		{
173 173
 			return true;
174 174
 		}
175 175
 
176 176
 		// Still here? Then we have one last check to make - any user private permissions.
177
-		return $this->doesUserHavePermission( (int)$user_id, (int)$permission_id);
177
+		return $this->doesUserHavePermission((int) $user_id, (int) $permission_id);
178 178
 	}
179 179
 
180 180
 	//--------------------------------------------------------------------
@@ -187,19 +187,19 @@  discard block
 block discarded – undo
187 187
 	 *
188 188
 	 * @return bool
189 189
 	 */
190
-	public function addUserToGroup( $user_id, $group )
190
+	public function addUserToGroup($user_id, $group)
191 191
 	{
192 192
 		if (empty($user_id) || ! is_numeric($user_id))
193 193
 		{
194 194
 			return null;
195 195
 		}
196 196
 
197
-		if (empty($group) || (! is_numeric($group) && ! is_string($group) ) )
197
+		if (empty($group) || ( ! is_numeric($group) && ! is_string($group)))
198 198
 		{
199 199
 			return null;
200 200
 		}
201 201
 
202
-		if (! Events::trigger('beforeAddUserToGroup', [$user_id, $group]))
202
+		if ( ! Events::trigger('beforeAddUserToGroup', [$user_id, $group]))
203 203
 		{
204 204
 			return false;
205 205
 		}
@@ -207,12 +207,12 @@  discard block
 block discarded – undo
207 207
 		$group_id = $this->getGroupID($group);
208 208
 
209 209
 		// Group ID
210
-		if ( ! is_numeric( $group_id ) )
210
+		if ( ! is_numeric($group_id))
211 211
 		{
212 212
 			return null;
213 213
 		}
214 214
 
215
-		if ( ! $this->groupModel->addUserToGroup( (int)$user_id, (int)$group_id ) )
215
+		if ( ! $this->groupModel->addUserToGroup((int) $user_id, (int) $group_id))
216 216
 		{
217 217
 			$this->error = $this->groupModel->error();
218 218
 
@@ -234,19 +234,19 @@  discard block
 block discarded – undo
234 234
 	 *
235 235
 	 * @return mixed
236 236
 	 */
237
-	public function removeUserFromGroup( $user_id, $group )
237
+	public function removeUserFromGroup($user_id, $group)
238 238
 	{
239 239
 		if (empty($user_id) || ! is_numeric($user_id))
240 240
 		{
241 241
 			return null;
242 242
 		}
243 243
 
244
-		if (empty($group) || (! is_numeric($group) && ! is_string($group) ) )
244
+		if (empty($group) || ( ! is_numeric($group) && ! is_string($group)))
245 245
 		{
246 246
 			return null;
247 247
 		}
248 248
 
249
-		if (! Events::trigger('beforeRemoveUserFromGroup', [$user_id, $group]))
249
+		if ( ! Events::trigger('beforeRemoveUserFromGroup', [$user_id, $group]))
250 250
 		{
251 251
 			return false;
252 252
 		}
@@ -254,12 +254,12 @@  discard block
 block discarded – undo
254 254
 		$group_id = $this->getGroupID($group);
255 255
 
256 256
 		// Group ID
257
-		if ( ! is_numeric( $group_id ) )
257
+		if ( ! is_numeric($group_id))
258 258
 		{
259 259
 			return false;
260 260
 		}
261 261
 
262
-		if ( ! $this->groupModel->removeUserFromGroup( $user_id, $group_id ) )
262
+		if ( ! $this->groupModel->removeUserFromGroup($user_id, $group_id))
263 263
 		{
264 264
 			$this->error = $this->groupModel->error();
265 265
 
@@ -281,25 +281,25 @@  discard block
 block discarded – undo
281 281
 	 *
282 282
 	 * @return mixed
283 283
 	 */
284
-	public function addPermissionToGroup( $permission, $group )
284
+	public function addPermissionToGroup($permission, $group)
285 285
 	{
286 286
 		$permission_id = $this->getPermissionID($permission);
287 287
 		$group_id      = $this->getGroupID($group);
288 288
 
289 289
 		// Permission ID
290
-		if ( ! is_numeric( $permission_id ) )
290
+		if ( ! is_numeric($permission_id))
291 291
 		{
292 292
 			return false;
293 293
 		}
294 294
 
295 295
 		// Group ID
296
-		if ( ! is_numeric( $group_id ) )
296
+		if ( ! is_numeric($group_id))
297 297
 		{
298 298
 			return false;
299 299
 		}
300 300
 
301 301
 		// Remove it!
302
-		if ( ! $this->groupModel->addPermissionToGroup( $permission_id, $group_id ) )
302
+		if ( ! $this->groupModel->addPermissionToGroup($permission_id, $group_id))
303 303
 		{
304 304
 			$this->error = $this->groupModel->error();
305 305
 
@@ -319,25 +319,25 @@  discard block
 block discarded – undo
319 319
 	 *
320 320
 	 * @return mixed
321 321
 	 */
322
-	public function removePermissionFromGroup( $permission, $group )
322
+	public function removePermissionFromGroup($permission, $group)
323 323
 	{
324 324
 		$permission_id = $this->getPermissionID($permission);
325 325
 		$group_id      = $this->getGroupID($group);
326 326
 
327 327
 		// Permission ID
328
-		if ( ! is_numeric( $permission_id ) )
328
+		if ( ! is_numeric($permission_id))
329 329
 		{
330 330
 			return false;
331 331
 		}
332 332
 
333 333
 		// Group ID
334
-		if ( ! is_numeric( $group_id ) )
334
+		if ( ! is_numeric($group_id))
335 335
 		{
336 336
 			return false;
337 337
 		}
338 338
 
339 339
 		// Remove it!
340
-		if ( ! $this->groupModel->removePermissionFromGroup( $permission_id, $group_id ) )
340
+		if ( ! $this->groupModel->removePermissionFromGroup($permission_id, $group_id))
341 341
 		{
342 342
 			$this->error = $this->groupModel->error();
343 343
 
@@ -358,11 +358,11 @@  discard block
 block discarded – undo
358 358
 	 *
359 359
 	 * @return int|bool
360 360
 	 */
361
-	public function addPermissionToUser( $permission, $user_id )
361
+	public function addPermissionToUser($permission, $user_id)
362 362
 	{
363 363
 		$permission_id = $this->getPermissionID($permission);
364 364
 
365
-		if (! is_numeric($permission_id) )
365
+		if ( ! is_numeric($permission_id))
366 366
 		{
367 367
 			return null;
368 368
 		}
@@ -372,21 +372,21 @@  discard block
 block discarded – undo
372 372
 			return null;
373 373
 		}
374 374
 
375
-		$user_id = (int)$user_id;
375
+		$user_id = (int) $user_id;
376 376
 
377
-		if (! Events::trigger('beforeAddPermissionToUser', [$user_id, $permission]))
377
+		if ( ! Events::trigger('beforeAddPermissionToUser', [$user_id, $permission]))
378 378
 		{
379 379
 			return false;
380 380
 		}
381 381
 
382
-		$ci =& get_instance();
382
+		$ci = & get_instance();
383 383
 		$ci->load->model('User_model');
384 384
 
385 385
 		$permissions = $ci->user_model->getMetaItem($user_id, 'RBAC_permissions');
386 386
 
387 387
 		// If we already have permissions, unserialize them and add
388 388
 		// the new permission to it.
389
-		if (! empty($permissions))
389
+		if ( ! empty($permissions))
390 390
 		{
391 391
 			$permissions = unserialize($permissions);
392 392
 		}
@@ -411,11 +411,11 @@  discard block
 block discarded – undo
411 411
 	 * @param int/string $permission
412 412
 	 * @param int        $user_id
413 413
 	 */
414
-	public function removePermissionFromUser( $permission, $user_id )
414
+	public function removePermissionFromUser($permission, $user_id)
415 415
 	{
416 416
 		$permission_id = $this->getPermissionID($permission);
417 417
 
418
-		if (! is_numeric($permission_id) )
418
+		if ( ! is_numeric($permission_id))
419 419
 		{
420 420
 			return false;
421 421
 		}
@@ -425,26 +425,26 @@  discard block
 block discarded – undo
425 425
 			return null;
426 426
 		}
427 427
 
428
-		$user_id = (int)$user_id;
428
+		$user_id = (int) $user_id;
429 429
 
430
-		if (! Events::trigger('beforeRemovePermissionFromUser', [$user_id, $permission]))
430
+		if ( ! Events::trigger('beforeRemovePermissionFromUser', [$user_id, $permission]))
431 431
 		{
432 432
 			return false;
433 433
 		}
434 434
 
435 435
 		// Grab the existing permissions for this user, and remove
436 436
 		// the permission id from the list.
437
-		$ci =& get_instance();
437
+		$ci = & get_instance();
438 438
 		$ci->load->model('User_model');
439 439
 
440 440
 		$permissions = $ci->user_model->getMetaItem($user_id, 'RBAC_permissions');
441 441
 
442
-		if (! is_array($permissions))
442
+		if ( ! is_array($permissions))
443 443
 		{
444 444
 			$permissions = [];
445 445
 		}
446 446
 
447
-		unset($permissions[ array_search($permission_id, $permissions) ]);
447
+		unset($permissions[array_search($permission_id, $permissions)]);
448 448
 
449 449
 		// Save the updated permissions
450 450
 		return $ci->user_model->saveMetaToUser($user_id, 'RBAC_permissions', serialize($permissions));
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
 	{
465 465
 		$permission_id = $this->getPermissionID($permission);
466 466
 
467
-		if (! is_numeric($permission_id) )
467
+		if ( ! is_numeric($permission_id))
468 468
 		{
469 469
 			return false;
470 470
 		}
@@ -474,14 +474,14 @@  discard block
 block discarded – undo
474 474
 			return null;
475 475
 		}
476 476
 
477
-		$user_id = (int)$user_id;
477
+		$user_id = (int) $user_id;
478 478
 
479 479
 		$model = $this->user_model;
480 480
 
481 481
 		if (empty($model))
482 482
 		{
483
-			$ci =& get_instance();
484
-			$ci->load->model( 'User_model' );
483
+			$ci = & get_instance();
484
+			$ci->load->model('User_model');
485 485
 
486 486
 			$model = $ci->user_model;
487 487
 		}
@@ -506,14 +506,14 @@  discard block
 block discarded – undo
506 506
 	 *
507 507
 	 * @return object|null
508 508
 	 */
509
-	public function group( $group )
509
+	public function group($group)
510 510
 	{
511
-		if ( is_numeric( $group ) )
511
+		if (is_numeric($group))
512 512
 		{
513
-			return $this->groupModel->find( (int) $group );
513
+			return $this->groupModel->find((int) $group);
514 514
 		}
515 515
 
516
-		return $this->groupModel->find_by( 'name', $group );
516
+		return $this->groupModel->find_by('name', $group);
517 517
 	}
518 518
 
519 519
 	//--------------------------------------------------------------------
@@ -536,16 +536,16 @@  discard block
 block discarded – undo
536 536
 	 *
537 537
 	 * @return mixed
538 538
 	 */
539
-	public function createGroup( $name, $description = '' )
539
+	public function createGroup($name, $description = '')
540 540
 	{
541 541
 		$data = [
542 542
 			'name'        => $name,
543 543
 			'description' => $description
544 544
 		];
545 545
 
546
-		$id = $this->groupModel->insert( $data );
546
+		$id = $this->groupModel->insert($data);
547 547
 
548
-		if ( is_numeric( $id ) )
548
+		if (is_numeric($id))
549 549
 		{
550 550
 			return (int) $id;
551 551
 		}
@@ -564,9 +564,9 @@  discard block
 block discarded – undo
564 564
 	 *
565 565
 	 * @return bool
566 566
 	 */
567
-	public function deleteGroup( $group_id )
567
+	public function deleteGroup($group_id)
568 568
 	{
569
-		if ( ! $this->groupModel->delete( $group_id ) )
569
+		if ( ! $this->groupModel->delete($group_id))
570 570
 		{
571 571
 			$this->error = $this->groupModel->error();
572 572
 
@@ -587,18 +587,18 @@  discard block
 block discarded – undo
587 587
 	 *
588 588
 	 * @return mixed
589 589
 	 */
590
-	public function updateGroup( $id, $name, $description = '' )
590
+	public function updateGroup($id, $name, $description = '')
591 591
 	{
592 592
 		$data = [
593 593
 			'name' => $name
594 594
 		];
595 595
 
596
-		if ( ! empty( $description ) )
596
+		if ( ! empty($description))
597 597
 		{
598 598
 			$data['description'] = $description;
599 599
 		}
600 600
 
601
-		if ( ! $this->groupModel->update( (int) $id, $data ) )
601
+		if ( ! $this->groupModel->update((int) $id, $data))
602 602
 		{
603 603
 			$this->error = $this->groupModel->error();
604 604
 
@@ -618,23 +618,23 @@  discard block
 block discarded – undo
618 618
 	 *
619 619
 	 * @return int|false
620 620
 	 */
621
-	protected function getGroupID( $group )
621
+	protected function getGroupID($group)
622 622
 	{
623 623
 		if (is_numeric($group))
624 624
 		{
625
-			return (int)$group;
625
+			return (int) $group;
626 626
 		}
627 627
 
628
-		$g = $this->groupModel->find_by( 'name', $group );
628
+		$g = $this->groupModel->find_by('name', $group);
629 629
 
630
-		if ( ! $g )
630
+		if ( ! $g)
631 631
 		{
632 632
 			$this->error = lang('auth.group_not_found');
633 633
 
634 634
 			return FALSE;
635 635
 		}
636 636
 
637
-		return (int)$g->id;
637
+		return (int) $g->id;
638 638
 	}
639 639
 
640 640
 	//--------------------------------------------------------------------
@@ -650,14 +650,14 @@  discard block
 block discarded – undo
650 650
 	 *
651 651
 	 * @return object|null
652 652
 	 */
653
-	public function permission( $permission )
653
+	public function permission($permission)
654 654
 	{
655
-		if ( is_numeric( $permission ) )
655
+		if (is_numeric($permission))
656 656
 		{
657
-			return $this->permissionModel->find( (int) $permission );
657
+			return $this->permissionModel->find((int) $permission);
658 658
 		}
659 659
 
660
-		return $this->permissionModel->find_by( 'LOWER(name)', strtolower( $permission ) );
660
+		return $this->permissionModel->find_by('LOWER(name)', strtolower($permission));
661 661
 	}
662 662
 
663 663
 	//--------------------------------------------------------------------
@@ -682,16 +682,16 @@  discard block
 block discarded – undo
682 682
 	 *
683 683
 	 * @return mixed
684 684
 	 */
685
-	public function createPermission( $name, $description = '' )
685
+	public function createPermission($name, $description = '')
686 686
 	{
687 687
 		$data = [
688 688
 			'name'        => $name,
689 689
 			'description' => $description
690 690
 		];
691 691
 
692
-		$id = $this->permissionModel->insert( $data );
692
+		$id = $this->permissionModel->insert($data);
693 693
 
694
-		if ( is_numeric( $id ) )
694
+		if (is_numeric($id))
695 695
 		{
696 696
 			return (int) $id;
697 697
 		}
@@ -710,9 +710,9 @@  discard block
 block discarded – undo
710 710
 	 *
711 711
 	 * @return mixed
712 712
 	 */
713
-	public function deletePermission( $permission_id )
713
+	public function deletePermission($permission_id)
714 714
 	{
715
-		if ( ! $this->permissionModel->delete( $permission_id ) )
715
+		if ( ! $this->permissionModel->delete($permission_id))
716 716
 		{
717 717
 			$this->error = $this->permissionModel->error();
718 718
 
@@ -720,7 +720,7 @@  discard block
 block discarded – undo
720 720
 		}
721 721
 
722 722
 		// Remove the permission from all groups
723
-		$this->groupModel->removePermissionFromAllGroups( $permission_id );
723
+		$this->groupModel->removePermissionFromAllGroups($permission_id);
724 724
 
725 725
 		return TRUE;
726 726
 	}
@@ -736,18 +736,18 @@  discard block
 block discarded – undo
736 736
 	 *
737 737
 	 * @return bool
738 738
 	 */
739
-	public function updatePermission( $id, $name, $description = '' )
739
+	public function updatePermission($id, $name, $description = '')
740 740
 	{
741 741
 		$data = [
742 742
 			'name' => $name
743 743
 		];
744 744
 
745
-		if ( ! empty( $description ) )
745
+		if ( ! empty($description))
746 746
 		{
747 747
 			$data['description'] = $description;
748 748
 		}
749 749
 
750
-		if ( ! $this->permissionModel->update( (int) $id, $data ) )
750
+		if ( ! $this->permissionModel->update((int) $id, $data))
751 751
 		{
752 752
 			$this->error = $this->permissionModel->error();
753 753
 
@@ -767,25 +767,25 @@  discard block
 block discarded – undo
767 767
 	 *
768 768
 	 * @return int|null
769 769
 	 */
770
-	protected function getPermissionID( $permission )
770
+	protected function getPermissionID($permission)
771 771
 	{
772 772
 		// If it's a number, we're done here.
773 773
 		if (is_numeric($permission))
774 774
 		{
775
-			return (int)$permission;
775
+			return (int) $permission;
776 776
 		}
777 777
 
778 778
 		// Otherwise, pull it from the database.
779
-		$p = $this->permissionModel->find_by( 'name', $permission );
779
+		$p = $this->permissionModel->find_by('name', $permission);
780 780
 
781
-		if ( ! $p )
781
+		if ( ! $p)
782 782
 		{
783 783
 			$this->error = lang('auth.permission_not_found');
784 784
 
785 785
 			return FALSE;
786 786
 		}
787 787
 
788
-		return (int)$p->id;
788
+		return (int) $p->id;
789 789
 	}
790 790
 
791 791
 	//--------------------------------------------------------------------
Please login to merge, or discard this patch.
Braces   +2 added lines, -5 removed lines patch added patch discarded remove patch
@@ -122,9 +122,7 @@  discard block
 block discarded – undo
122 122
 				{
123 123
 					return true;
124 124
 				}
125
-			}
126
-
127
-			else if (is_string($group))
125
+			} else if (is_string($group))
128 126
 			{
129 127
 				$ids = array_column($user_groups, 'name');
130 128
 				if (in_array($group, $ids))
@@ -389,8 +387,7 @@  discard block
 block discarded – undo
389 387
 		if (! empty($permissions))
390 388
 		{
391 389
 			$permissions = unserialize($permissions);
392
-		}
393
-		else
390
+		} else
394 391
 		{
395 392
 			$permissions = [];
396 393
 		}
Please login to merge, or discard this patch.
myth/CIModules/auth/models/Login_model.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
      * string with letters and numbers.
196 196
      *
197 197
      * @param $user
198
-     * @return mixed
198
+     * @return string
199 199
      */
200 200
     public function generateRememberToken($user)
201 201
     {
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
      * Gets the timestamp of the last attempted login for this user.
279 279
      *
280 280
      * @param $email
281
-     * @return int|null
281
+     * @return integer
282 282
      */
283 283
     public function lastLoginAttemptTime($email)
284 284
     {
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
      */
123 123
     public function distributedBruteForceTime()
124 124
     {
125
-        if (! $time = $this->cache->get('dbrutetime'))
125
+        if ( ! $time = $this->cache->get('dbrutetime'))
126 126
         {
127 127
             $time = 0;
128 128
 
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 
132 132
             $query = $this->db->query("SELECT COUNT(*) / COUNT(DISTINCT DATE(`datetime`)) as num_rows FROM `auth_login_attempts` WHERE `datetime` >= ?", $avg_start_time);
133 133
 
134
-            if (! $query->num_rows())
134
+            if ( ! $query->num_rows())
135 135
             {
136 136
                 $average = 0;
137 137
             }
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
             }
153 153
 
154 154
             // Cache it for 3 hours.
155
-            $this->cache->save('dbrutetime', $time, 60*60*3);
155
+            $this->cache->save('dbrutetime', $time, 60 * 60 * 3);
156 156
         }
157 157
 
158 158
         return $time;
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
     public function recordLogin($user)
174 174
     {
175 175
         $data = [
176
-            'user_id'    => (int)$user['id'],
176
+            'user_id'    => (int) $user['id'],
177 177
             'datetime'   => date('Y-m-d H:i:s'),
178 178
             'ip_address' => $this->input->ip_address()
179 179
         ];
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
     {
202 202
         $this->load->helper('string');
203 203
 
204
-        return str_replace('@', '.', $user['email']) .'|' . random_string('alnum', 128);
204
+        return str_replace('@', '.', $user['email']).'|'.random_string('alnum', 128);
205 205
     }
206 206
 
207 207
     //--------------------------------------------------------------------
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
      */
215 215
     public function hashRememberToken($token)
216 216
     {
217
-        return sha1(config_item('auth.salt') . $token);
217
+        return sha1(config_item('auth.salt').$token);
218 218
     }
219 219
 
220 220
     //--------------------------------------------------------------------
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
      */
261 261
     public function purgeOldRememberTokens()
262 262
     {
263
-        if (! config_item('auth.allow_remembering'))
263
+        if ( ! config_item('auth.allow_remembering'))
264 264
         {
265 265
             return;
266 266
         }
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
                           ->limit(1)
288 288
                           ->get('auth_login_attempts');
289 289
 
290
-        if (! $query->num_rows())
290
+        if ( ! $query->num_rows())
291 291
         {
292 292
             return 0;
293 293
         }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -134,8 +134,7 @@
 block discarded – undo
134 134
             if (! $query->num_rows())
135 135
             {
136 136
                 $average = 0;
137
-            }
138
-            else
137
+            } else
139 138
             {
140 139
                 $average = $query->row()->num_rows;
141 140
             }
Please login to merge, or discard this patch.
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -1,34 +1,34 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Sprint
4
- *
5
- * A set of power tools to enhance the CodeIgniter framework and provide consistent workflow.
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in
15
- * all copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
- * THE SOFTWARE.
24
- *
25
- * @package     Sprint
26
- * @author      Lonnie Ezell
27
- * @copyright   Copyright 2014-2015, New Myth Media, LLC (http://newmythmedia.com)
28
- * @license     http://opensource.org/licenses/MIT  (MIT)
29
- * @link        http://sprintphp.com
30
- * @since       Version 1.0
31
- */
3
+	 * Sprint
4
+	 *
5
+	 * A set of power tools to enhance the CodeIgniter framework and provide consistent workflow.
6
+	 *
7
+	 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+	 * of this software and associated documentation files (the "Software"), to deal
9
+	 * in the Software without restriction, including without limitation the rights
10
+	 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+	 * copies of the Software, and to permit persons to whom the Software is
12
+	 * furnished to do so, subject to the following conditions:
13
+	 *
14
+	 * The above copyright notice and this permission notice shall be included in
15
+	 * all copies or substantial portions of the Software.
16
+	 *
17
+	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+	 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+	 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+	 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+	 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+	 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+	 * THE SOFTWARE.
24
+	 *
25
+	 * @package     Sprint
26
+	 * @author      Lonnie Ezell
27
+	 * @copyright   Copyright 2014-2015, New Myth Media, LLC (http://newmythmedia.com)
28
+	 * @license     http://opensource.org/licenses/MIT  (MIT)
29
+	 * @link        http://sprintphp.com
30
+	 * @since       Version 1.0
31
+	 */
32 32
 
33 33
 /**
34 34
  * Class Login_model
@@ -41,274 +41,274 @@  discard block
 block discarded – undo
41 41
  */
42 42
 class Login_model extends \Myth\Models\CIDbModel {
43 43
 
44
-    protected $table_name = 'auth_logins';
45
-
46
-    protected $set_created = false;
47
-    protected $set_modified = false;
48
-
49
-    //--------------------------------------------------------------------
50
-
51
-    //--------------------------------------------------------------------
52
-    // Login Attempts
53
-    //--------------------------------------------------------------------
54
-
55
-    /**
56
-     * Records a login attempt. This is used to implement
57
-     * throttling of user login attempts.
58
-     *
59
-     * @param $email
60
-     * @return object
61
-     */
62
-    public function recordLoginAttempt($email)
63
-    {
64
-        $data = [
65
-            'email' => $email,
66
-            'datetime' => date('Y-m-d H:i:s')
67
-        ];
68
-
69
-        return $this->db->insert('auth_login_attempts', $data);
70
-    }
71
-
72
-    //--------------------------------------------------------------------
73
-
74
-    /**
75
-     * Purges all login attempt records from the database.
76
-     *
77
-     * @param $email
78
-     * @return mixed
79
-     */
80
-    public function purgeLoginAttempts($email)
81
-    {
82
-        return $this->db->where('email', $email)
83
-                        ->delete('auth_login_attempts');
84
-    }
85
-
86
-    //--------------------------------------------------------------------
87
-
88
-    /**
89
-     * Checks to see if how many login attempts have been attempted in the
90
-     * last 60 seconds. If over 100, it is considered to be under a
91
-     * brute force attempt.
92
-     *
93
-     * @param $email
94
-     * @return bool
95
-     */
96
-    public function isBruteForced($email)
97
-    {
98
-        $start_time = date('Y-m-d H:i:s', time() - 60);
99
-
100
-        $attempts = $this->db->where('email', $email)
101
-                             ->where('datetime >=', $start_time)
102
-                             ->count_all_results('auth_login_attempts');
103
-
104
-        return $attempts > 100;
105
-    }
106
-
107
-    //--------------------------------------------------------------------
108
-
109
-    /**
110
-     * Attempts to determine if the system is under a distributed
111
-     * brute force attack.
112
-     *
113
-     * To determine if we are in under a brute force attack, we first
114
-     * find the average number of bad logins per day that never converted to
115
-     * successful logins over the last 3 months. Then we compare
116
-     * that to the the average number of logins in the past 24 hours.
117
-     *
118
-     * If the number of attempts in the last 24 hours is more than X (see config)
119
-     * times the average, then institute additional throttling.
120
-     *
121
-     * @return int The time to add to any throttling.
122
-     */
123
-    public function distributedBruteForceTime()
124
-    {
125
-        if (! $time = $this->cache->get('dbrutetime'))
126
-        {
127
-            $time = 0;
128
-
129
-            // Compute our daily average over the last 3 months.
130
-            $avg_start_time = date('Y-m-d 00:00:00', strtotime('-3 months'));
131
-
132
-            $query = $this->db->query("SELECT COUNT(*) / COUNT(DISTINCT DATE(`datetime`)) as num_rows FROM `auth_login_attempts` WHERE `datetime` >= ?", $avg_start_time);
133
-
134
-            if (! $query->num_rows())
135
-            {
136
-                $average = 0;
137
-            }
138
-            else
139
-            {
140
-                $average = $query->row()->num_rows;
141
-            }
142
-
143
-            // Get the total in the last 24 hours
144
-            $today_start_time = date('Y-m-d H:i:s', strtotime('-24 hours'));
145
-
146
-            $attempts = $this->db->where('datetime >=', $today_start_time)
147
-                                 ->count_all_results('auth_login_attempts');
148
-
149
-            if ($attempts > (config_item('auth.dbrute_multiplier') * $average))
150
-            {
151
-                $time = config_item('auth.distributed_brute_add_time');
152
-            }
153
-
154
-            // Cache it for 3 hours.
155
-            $this->cache->save('dbrutetime', $time, 60*60*3);
156
-        }
157
-
158
-        return $time;
159
-    }
160
-
161
-    //--------------------------------------------------------------------
162
-
163
-    //--------------------------------------------------------------------
164
-    // Logins
165
-    //--------------------------------------------------------------------
166
-
167
-    /**
168
-     * Records a successful login. This stores in a table so that a
169
-     * history can be pulled up later if needed for security analyses.
170
-     *
171
-     * @param $user
172
-     */
173
-    public function recordLogin($user)
174
-    {
175
-        $data = [
176
-            'user_id'    => (int)$user['id'],
177
-            'datetime'   => date('Y-m-d H:i:s'),
178
-            'ip_address' => $this->input->ip_address()
179
-        ];
180
-
181
-        return $this->db->insert('auth_logins', $data);
182
-    }
183
-
184
-    //--------------------------------------------------------------------
185
-
186
-    //--------------------------------------------------------------------
187
-    // Tokens
188
-    //--------------------------------------------------------------------
189
-
190
-    /**
191
-     * Generates a new token for the rememberme cookie.
192
-     *
193
-     * The token is based on the user's email address (since everyone will have one)
194
-     * with the '@' turned to a '.', followed by a pipe (|) and a random 128-character
195
-     * string with letters and numbers.
196
-     *
197
-     * @param $user
198
-     * @return mixed
199
-     */
200
-    public function generateRememberToken($user)
201
-    {
202
-        $this->load->helper('string');
203
-
204
-        return str_replace('@', '.', $user['email']) .'|' . random_string('alnum', 128);
205
-    }
206
-
207
-    //--------------------------------------------------------------------
208
-
209
-    /**
210
-     * Hashes the token for the Remember Me Functionality.
211
-     *
212
-     * @param $token
213
-     * @return string
214
-     */
215
-    public function hashRememberToken($token)
216
-    {
217
-        return sha1(config_item('auth.salt') . $token);
218
-    }
219
-
220
-    //--------------------------------------------------------------------
221
-
222
-    /**
223
-     * Deletes a single token that matches the email/token combo.
224
-     *
225
-     * @param $email
226
-     * @param $token
227
-     * @return mixed
228
-     */
229
-    public function deleteRememberToken($email, $token)
230
-    {
231
-        $where = [
232
-            'email' => $email,
233
-            'hash'  => $this->hashRememberToken($token)
234
-        ];
235
-
236
-        $this->db->delete('auth_tokens', $where);
237
-    }
238
-
239
-    //--------------------------------------------------------------------
240
-
241
-    /**
242
-     * Removes all persistent login tokens (RememberMe) for a single user
243
-     * across all devices they may have logged in with.
244
-     *
245
-     * @param $email
246
-     * @return mixed
247
-     */
248
-    public function purgeRememberTokens($email)
249
-    {
250
-        return $this->db->delete('auth_tokens', ['email' => $email]);
251
-    }
252
-
253
-    //--------------------------------------------------------------------
254
-
255
-
256
-    /**
257
-     * Purges the 'auth_tokens' table of any records that are too old
258
-     * to be of any use anymore. This equates to 1 week older than
259
-     * the remember_length set in the config file.
260
-     */
261
-    public function purgeOldRememberTokens()
262
-    {
263
-        if (! config_item('auth.allow_remembering'))
264
-        {
265
-            return;
266
-        }
267
-
268
-        $date = time() - config_item('auth.remember_length') - 604800; // 1 week
269
-        $date = date('Y-m-d 00:00:00', $date);
270
-
271
-        $this->db->where('created <=', $date)
272
-                 ->delete('auth_tokens');
273
-    }
274
-
275
-    //--------------------------------------------------------------------
276
-
277
-    /**
278
-     * Gets the timestamp of the last attempted login for this user.
279
-     *
280
-     * @param $email
281
-     * @return int|null
282
-     */
283
-    public function lastLoginAttemptTime($email)
284
-    {
285
-        $query = $this->db->where('email', $email)
286
-                          ->order_by('datetime', 'desc')
287
-                          ->limit(1)
288
-                          ->get('auth_login_attempts');
289
-
290
-        if (! $query->num_rows())
291
-        {
292
-            return 0;
293
-        }
294
-
295
-        return strtotime($query->row()->datetime);
296
-    }
297
-
298
-    //--------------------------------------------------------------------
299
-
300
-    /**
301
-     * Returns the number of failed login attempts for a single email.
302
-     *
303
-     * @param $email
304
-     * @return int
305
-     */
306
-    public function countLoginAttempts($email)
307
-    {
308
-        return $this->db->where('email', $email)
309
-                        ->count_all_results('auth_login_attempts');
310
-    }
311
-
312
-    //--------------------------------------------------------------------
44
+	protected $table_name = 'auth_logins';
45
+
46
+	protected $set_created = false;
47
+	protected $set_modified = false;
48
+
49
+	//--------------------------------------------------------------------
50
+
51
+	//--------------------------------------------------------------------
52
+	// Login Attempts
53
+	//--------------------------------------------------------------------
54
+
55
+	/**
56
+	 * Records a login attempt. This is used to implement
57
+	 * throttling of user login attempts.
58
+	 *
59
+	 * @param $email
60
+	 * @return object
61
+	 */
62
+	public function recordLoginAttempt($email)
63
+	{
64
+		$data = [
65
+			'email' => $email,
66
+			'datetime' => date('Y-m-d H:i:s')
67
+		];
68
+
69
+		return $this->db->insert('auth_login_attempts', $data);
70
+	}
71
+
72
+	//--------------------------------------------------------------------
73
+
74
+	/**
75
+	 * Purges all login attempt records from the database.
76
+	 *
77
+	 * @param $email
78
+	 * @return mixed
79
+	 */
80
+	public function purgeLoginAttempts($email)
81
+	{
82
+		return $this->db->where('email', $email)
83
+						->delete('auth_login_attempts');
84
+	}
85
+
86
+	//--------------------------------------------------------------------
87
+
88
+	/**
89
+	 * Checks to see if how many login attempts have been attempted in the
90
+	 * last 60 seconds. If over 100, it is considered to be under a
91
+	 * brute force attempt.
92
+	 *
93
+	 * @param $email
94
+	 * @return bool
95
+	 */
96
+	public function isBruteForced($email)
97
+	{
98
+		$start_time = date('Y-m-d H:i:s', time() - 60);
99
+
100
+		$attempts = $this->db->where('email', $email)
101
+							 ->where('datetime >=', $start_time)
102
+							 ->count_all_results('auth_login_attempts');
103
+
104
+		return $attempts > 100;
105
+	}
106
+
107
+	//--------------------------------------------------------------------
108
+
109
+	/**
110
+	 * Attempts to determine if the system is under a distributed
111
+	 * brute force attack.
112
+	 *
113
+	 * To determine if we are in under a brute force attack, we first
114
+	 * find the average number of bad logins per day that never converted to
115
+	 * successful logins over the last 3 months. Then we compare
116
+	 * that to the the average number of logins in the past 24 hours.
117
+	 *
118
+	 * If the number of attempts in the last 24 hours is more than X (see config)
119
+	 * times the average, then institute additional throttling.
120
+	 *
121
+	 * @return int The time to add to any throttling.
122
+	 */
123
+	public function distributedBruteForceTime()
124
+	{
125
+		if (! $time = $this->cache->get('dbrutetime'))
126
+		{
127
+			$time = 0;
128
+
129
+			// Compute our daily average over the last 3 months.
130
+			$avg_start_time = date('Y-m-d 00:00:00', strtotime('-3 months'));
131
+
132
+			$query = $this->db->query("SELECT COUNT(*) / COUNT(DISTINCT DATE(`datetime`)) as num_rows FROM `auth_login_attempts` WHERE `datetime` >= ?", $avg_start_time);
133
+
134
+			if (! $query->num_rows())
135
+			{
136
+				$average = 0;
137
+			}
138
+			else
139
+			{
140
+				$average = $query->row()->num_rows;
141
+			}
142
+
143
+			// Get the total in the last 24 hours
144
+			$today_start_time = date('Y-m-d H:i:s', strtotime('-24 hours'));
145
+
146
+			$attempts = $this->db->where('datetime >=', $today_start_time)
147
+								 ->count_all_results('auth_login_attempts');
148
+
149
+			if ($attempts > (config_item('auth.dbrute_multiplier') * $average))
150
+			{
151
+				$time = config_item('auth.distributed_brute_add_time');
152
+			}
153
+
154
+			// Cache it for 3 hours.
155
+			$this->cache->save('dbrutetime', $time, 60*60*3);
156
+		}
157
+
158
+		return $time;
159
+	}
160
+
161
+	//--------------------------------------------------------------------
162
+
163
+	//--------------------------------------------------------------------
164
+	// Logins
165
+	//--------------------------------------------------------------------
166
+
167
+	/**
168
+	 * Records a successful login. This stores in a table so that a
169
+	 * history can be pulled up later if needed for security analyses.
170
+	 *
171
+	 * @param $user
172
+	 */
173
+	public function recordLogin($user)
174
+	{
175
+		$data = [
176
+			'user_id'    => (int)$user['id'],
177
+			'datetime'   => date('Y-m-d H:i:s'),
178
+			'ip_address' => $this->input->ip_address()
179
+		];
180
+
181
+		return $this->db->insert('auth_logins', $data);
182
+	}
183
+
184
+	//--------------------------------------------------------------------
185
+
186
+	//--------------------------------------------------------------------
187
+	// Tokens
188
+	//--------------------------------------------------------------------
189
+
190
+	/**
191
+	 * Generates a new token for the rememberme cookie.
192
+	 *
193
+	 * The token is based on the user's email address (since everyone will have one)
194
+	 * with the '@' turned to a '.', followed by a pipe (|) and a random 128-character
195
+	 * string with letters and numbers.
196
+	 *
197
+	 * @param $user
198
+	 * @return mixed
199
+	 */
200
+	public function generateRememberToken($user)
201
+	{
202
+		$this->load->helper('string');
203
+
204
+		return str_replace('@', '.', $user['email']) .'|' . random_string('alnum', 128);
205
+	}
206
+
207
+	//--------------------------------------------------------------------
208
+
209
+	/**
210
+	 * Hashes the token for the Remember Me Functionality.
211
+	 *
212
+	 * @param $token
213
+	 * @return string
214
+	 */
215
+	public function hashRememberToken($token)
216
+	{
217
+		return sha1(config_item('auth.salt') . $token);
218
+	}
219
+
220
+	//--------------------------------------------------------------------
221
+
222
+	/**
223
+	 * Deletes a single token that matches the email/token combo.
224
+	 *
225
+	 * @param $email
226
+	 * @param $token
227
+	 * @return mixed
228
+	 */
229
+	public function deleteRememberToken($email, $token)
230
+	{
231
+		$where = [
232
+			'email' => $email,
233
+			'hash'  => $this->hashRememberToken($token)
234
+		];
235
+
236
+		$this->db->delete('auth_tokens', $where);
237
+	}
238
+
239
+	//--------------------------------------------------------------------
240
+
241
+	/**
242
+	 * Removes all persistent login tokens (RememberMe) for a single user
243
+	 * across all devices they may have logged in with.
244
+	 *
245
+	 * @param $email
246
+	 * @return mixed
247
+	 */
248
+	public function purgeRememberTokens($email)
249
+	{
250
+		return $this->db->delete('auth_tokens', ['email' => $email]);
251
+	}
252
+
253
+	//--------------------------------------------------------------------
254
+
255
+
256
+	/**
257
+	 * Purges the 'auth_tokens' table of any records that are too old
258
+	 * to be of any use anymore. This equates to 1 week older than
259
+	 * the remember_length set in the config file.
260
+	 */
261
+	public function purgeOldRememberTokens()
262
+	{
263
+		if (! config_item('auth.allow_remembering'))
264
+		{
265
+			return;
266
+		}
267
+
268
+		$date = time() - config_item('auth.remember_length') - 604800; // 1 week
269
+		$date = date('Y-m-d 00:00:00', $date);
270
+
271
+		$this->db->where('created <=', $date)
272
+				 ->delete('auth_tokens');
273
+	}
274
+
275
+	//--------------------------------------------------------------------
276
+
277
+	/**
278
+	 * Gets the timestamp of the last attempted login for this user.
279
+	 *
280
+	 * @param $email
281
+	 * @return int|null
282
+	 */
283
+	public function lastLoginAttemptTime($email)
284
+	{
285
+		$query = $this->db->where('email', $email)
286
+						  ->order_by('datetime', 'desc')
287
+						  ->limit(1)
288
+						  ->get('auth_login_attempts');
289
+
290
+		if (! $query->num_rows())
291
+		{
292
+			return 0;
293
+		}
294
+
295
+		return strtotime($query->row()->datetime);
296
+	}
297
+
298
+	//--------------------------------------------------------------------
299
+
300
+	/**
301
+	 * Returns the number of failed login attempts for a single email.
302
+	 *
303
+	 * @param $email
304
+	 * @return int
305
+	 */
306
+	public function countLoginAttempts($email)
307
+	{
308
+		return $this->db->where('email', $email)
309
+						->count_all_results('auth_login_attempts');
310
+	}
311
+
312
+	//--------------------------------------------------------------------
313 313
 
314 314
 }
Please login to merge, or discard this patch.
myth/CLI.php 4 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -142,7 +142,6 @@  discard block
 block discarded – undo
142 142
      * Named options must be in the following formats:
143 143
      * php index.php user -v --v -name=John --name=John
144 144
      *
145
-     * @param	string|int	$name	the name of the option (int if unnamed)
146 145
      * @return	string
147 146
      */
148 147
     public static function input($prefix = '')
@@ -281,6 +280,7 @@  discard block
 block discarded – undo
281 280
      * with a line break.
282 281
      *
283 282
      * @param	string|array	$text	the text to output, or array of lines
283
+     * @param string $foreground
284 284
      */
285 285
     public static function write($text = '', $foreground = null, $background = null)
286 286
     {
@@ -535,9 +535,9 @@  discard block
 block discarded – undo
535 535
 	 * Checks to see if an option was passed to us on the CLI and returns
536 536
 	 * the value if so. Otherwise, returns null.
537 537
 	 *
538
-	 * @param $name
538
+	 * @param string $name
539 539
 	 *
540
-	 * @return null
540
+	 * @return string
541 541
 	 */
542 542
 	public static function option($name)
543 543
 	{
Please login to merge, or discard this patch.
Indentation   +511 added lines, -511 removed lines patch added patch discarded remove patch
@@ -1,14 +1,14 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Part of the Fuel framework.
4
- *
5
- * @package    Fuel
6
- * @version    1.7
7
- * @author     Fuel Development Team
8
- * @license    MIT License
9
- * @copyright  2010 - 2013 Fuel Development Team
10
- * @link       http://fuelphp.com
11
- */
3
+	 * Part of the Fuel framework.
4
+	 *
5
+	 * @package    Fuel
6
+	 * @version    1.7
7
+	 * @author     Fuel Development Team
8
+	 * @license    MIT License
9
+	 * @copyright  2010 - 2013 Fuel Development Team
10
+	 * @link       http://fuelphp.com
11
+	 */
12 12
 
13 13
 /**
14 14
  * Modified to work with CodeIgniter by Lonnie Ezell.
@@ -30,506 +30,506 @@  discard block
 block discarded – undo
30 30
  */
31 31
 class CLI {
32 32
 
33
-    public static $readline_support = false;
33
+	public static $readline_support = false;
34 34
 
35
-    public static $wait_msg = 'Press any key to continue...';
35
+	public static $wait_msg = 'Press any key to continue...';
36 36
 
37
-    public static $segments = [];
37
+	public static $segments = [];
38 38
 
39 39
 	protected static $options = [];
40 40
 
41 41
 	protected static $initialized = false;
42 42
 
43
-    // Used by progress bar
44
-    protected static $inProgress = false;
45
-
46
-    protected static $foreground_colors = array(
47
-        'black'			=> '0;30',
48
-        'dark_gray'		=> '1;30',
49
-        'blue'			=> '0;34',
50
-        'dark_blue'		=> '1;34',
51
-        'light_blue'	=> '1;34',
52
-        'green'			=> '0;32',
53
-        'light_green'	=> '1;32',
54
-        'cyan'			=> '0;36',
55
-        'light_cyan'	=> '1;36',
56
-        'red'			=> '0;31',
57
-        'light_red'		=> '1;31',
58
-        'purple'		=> '0;35',
59
-        'light_purple'	=> '1;35',
60
-        'light_yellow'	=> '0;33',
61
-        'yellow'		=> '1;33',
62
-        'light_gray'	=> '0;37',
63
-        'white'			=> '1;37',
64
-    );
65
-
66
-    protected static $background_colors = array(
67
-        'black'			=> '40',
68
-        'red'			=> '41',
69
-        'green'			=> '42',
70
-        'yellow'		=> '43',
71
-        'blue'			=> '44',
72
-        'magenta'		=> '45',
73
-        'cyan'			=> '46',
74
-        'light_gray'	=> '47',
75
-    );
76
-
77
-    //--------------------------------------------------------------------
78
-
79
-    /**
80
-     * Static constructor.	Parses all the CLI params.
81
-     */
82
-    public static function _init()
83
-    {
84
-	    if (static::$initialized === true)
85
-	    {
86
-		    return;
87
-	    }
88
-
89
-        if ( ! (PHP_SAPI === 'cli' || defined('STDIN')) )
90
-        {
91
-            throw new \Exception('Cli class cannot be used outside of the command line.');
92
-        }
93
-
94
-	    self::parseCommand();
95
-
96
-        // Readline is an extension for PHP that makes interactive with PHP much more bash-like
97
-        // http://www.php.net/manual/en/readline.installation.php
98
-        static::$readline_support = extension_loaded('readline');
99
-
100
-	    static::$initialized = true;
101
-    }
102
-
103
-    //--------------------------------------------------------------------
104
-
105
-    /**
106
-     * Grabs an individual
107
-     *
108
-     * @param $index
109
-     * @return null
110
-     */
111
-    public static function segment($index)
112
-    {
113
-        if (! isset(static::$segments[$index - 1]))
114
-        {
115
-            return null;
116
-        }
117
-
118
-        return static::$segments[$index - 1];
119
-    }
120
-
121
-    //--------------------------------------------------------------------
122
-
123
-    /**
124
-     * Returns the command string portion of the arguments. Used
125
-     * by the 'sprint' CLI script to grab the portion of the arguments
126
-     * that is used to call the CodeIgniter application.
127
-     *
128
-     * @return string
129
-     */
130
-    public static function cli_string()
131
-    {
132
-        return implode(' ', static::$segments);
133
-    }
134
-
135
-    //--------------------------------------------------------------------
136
-
137
-
138
-
139
-    /**
140
-     * Get input from the shell, using readline or the standard STDIN
141
-     *
142
-     * Named options must be in the following formats:
143
-     * php index.php user -v --v -name=John --name=John
144
-     *
145
-     * @param	string|int	$name	the name of the option (int if unnamed)
146
-     * @return	string
147
-     */
148
-    public static function input($prefix = '')
149
-    {
150
-        if (static::$readline_support)
151
-        {
152
-            return readline($prefix);
153
-        }
154
-
155
-        echo $prefix;
156
-        return fgets(STDIN);
157
-    }
158
-
159
-    //--------------------------------------------------------------------
160
-
161
-    /**
162
-     * Asks the user for input.  This can have either 1 or 2 arguments.
163
-     *
164
-     * Usage:
165
-     *
166
-     * // Waits for any key press
167
-     * CLI::prompt();
168
-     *
169
-     * // Takes any input
170
-     * $color = CLI::prompt('What is your favorite color?');
171
-     *
172
-     * // Takes any input, but offers default
173
-     * $color = CLI::prompt('What is your favourite color?', 'white');
174
-     *
175
-     * // Will only accept the options in the array
176
-     * $ready = CLI::prompt('Are you ready?', array('y','n'));
177
-     *
178
-     * @return	string	the user input
179
-     */
180
-    public static function prompt()
181
-    {
182
-        $args = func_get_args();
183
-
184
-        $options = array();
185
-        $output = '';
186
-        $default = null;
187
-
188
-        // How many we got
189
-        $arg_count = count($args);
190
-
191
-        // Is the last argument a boolean? True means required
192
-        $required = end($args) === true;
193
-
194
-        // Reduce the argument count if required was passed, we don't care about that anymore
195
-        $required === true and --$arg_count;
196
-
197
-        // This method can take a few crazy combinations of arguments, so lets work it out
198
-        switch ($arg_count)
199
-        {
200
-            case 2:
201
-
202
-                // E.g: $ready = CLI::prompt('Are you ready?', array('y','n'));
203
-                if (is_array($args[1]))
204
-                {
205
-                    list($output, $options)=$args;
206
-                }
207
-
208
-                // E.g: $color = CLI::prompt('What is your favourite color?', 'white');
209
-                elseif (is_string($args[1]))
210
-                {
211
-                    list($output, $default)=$args;
212
-                }
213
-
214
-                break;
215
-
216
-            case 1:
217
-
218
-                // No question (probably been asked already) so just show options
219
-                // E.g: $ready = CLI::prompt(array('y','n'));
220
-                if (is_array($args[0]))
221
-                {
222
-                    $options = $args[0];
223
-                }
224
-
225
-                // Question without options
226
-                // E.g: $ready = CLI::prompt('What did you do today?');
227
-                elseif (is_string($args[0]))
228
-                {
229
-                    $output = $args[0];
230
-                }
231
-
232
-                break;
233
-        }
234
-
235
-        // If a question has been asked with the read
236
-        if ($output !== '')
237
-        {
238
-            $extra_output = '';
239
-
240
-            if ($default !== null)
241
-            {
242
-                $extra_output = ' [ Default: "'.$default.'" ]';
243
-            }
244
-
245
-            elseif ($options !== array())
246
-            {
247
-                $extra_output = ' [ '.implode(', ', $options).' ]';
248
-            }
249
-
250
-            fwrite(STDOUT, $output.$extra_output.': ');
251
-        }
252
-
253
-        // Read the input from keyboard.
254
-        $input = trim(static::input()) ?: $default;
255
-
256
-        // No input provided and we require one (default will stop this being called)
257
-        if (empty($input) and $required === true)
258
-        {
259
-            static::write('This is required.');
260
-            static::new_line();
261
-
262
-            $input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
263
-        }
264
-
265
-        // If options are provided and the choice is not in the array, tell them to try again
266
-        if ( ! empty($options) and ! in_array($input, $options))
267
-        {
268
-            static::write('This is not a valid option. Please try again.');
269
-            static::new_line();
270
-
271
-            $input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
272
-        }
273
-
274
-        return $input;
275
-    }
276
-
277
-    //--------------------------------------------------------------------
278
-
279
-    /**
280
-     * Outputs a string to the cli.	 If you send an array it will implode them
281
-     * with a line break.
282
-     *
283
-     * @param	string|array	$text	the text to output, or array of lines
284
-     */
285
-    public static function write($text = '', $foreground = null, $background = null)
286
-    {
287
-        if (is_array($text))
288
-        {
289
-            $text = implode(PHP_EOL, $text);
290
-        }
291
-
292
-        if ($foreground or $background)
293
-        {
294
-            $text = static::color($text, $foreground, $background);
295
-        }
296
-
297
-        fwrite(STDOUT, $text.PHP_EOL);
298
-    }
299
-
300
-    //--------------------------------------------------------------------
301
-
302
-    /**
303
-     * Outputs an error to the CLI using STDERR instead of STDOUT
304
-     *
305
-     * @param	string|array	$text	the text to output, or array of errors
306
-     */
307
-    public static function error($text = '', $foreground = 'light_red', $background = null)
308
-    {
309
-        if (is_array($text))
310
-        {
311
-            $text = implode(PHP_EOL, $text);
312
-        }
313
-
314
-        if ($foreground OR $background)
315
-        {
316
-            $text = static::color($text, $foreground, $background);
317
-        }
318
-
319
-        fwrite(STDERR, $text.PHP_EOL);
320
-    }
321
-
322
-    //--------------------------------------------------------------------
323
-
324
-    /**
325
-     * Beeps a certain number of times.
326
-     *
327
-     * @param	int $num	the number of times to beep
328
-     */
329
-    public static function beep($num = 1)
330
-    {
331
-        echo str_repeat("\x07", $num);
332
-    }
333
-
334
-    //--------------------------------------------------------------------
335
-
336
-    /**
337
-     * Waits a certain number of seconds, optionally showing a wait message and
338
-     * waiting for a key press.
339
-     *
340
-     * @param	int		$seconds	number of seconds
341
-     * @param	bool	$countdown	show a countdown or not
342
-     */
343
-    public static function wait($seconds = 0, $countdown = false)
344
-    {
345
-        if ($countdown === true)
346
-        {
347
-            $time = $seconds;
348
-
349
-            while ($time > 0)
350
-            {
351
-                fwrite(STDOUT, $time.'... ');
352
-                sleep(1);
353
-                $time--;
354
-            }
355
-            static::write();
356
-        }
357
-
358
-        else
359
-        {
360
-            if ($seconds > 0)
361
-            {
362
-                sleep($seconds);
363
-            }
364
-            else
365
-            {
366
-                static::write(static::$wait_msg);
367
-                static::input();
368
-            }
369
-        }
370
-    }
371
-
372
-
373
-    //--------------------------------------------------------------------
374
-
375
-    /**
376
-     * if operating system === windows
377
-     */
378
-    public static function is_windows()
379
-    {
380
-        return 'win' === strtolower(substr(php_uname("s"), 0, 3));
381
-    }
382
-
383
-    //--------------------------------------------------------------------
384
-
385
-    /**
386
-     * Enter a number of empty lines
387
-     *
388
-     * @param	integer	Number of lines to output
389
-     * @return	void
390
-     */
391
-    public static function new_line($num = 1)
392
-    {
393
-        // Do it once or more, write with empty string gives us a new line
394
-        for($i = 0; $i < $num; $i++)
395
-        {
396
-            static::write();
397
-        }
398
-    }
399
-
400
-    //--------------------------------------------------------------------
401
-
402
-    /**
403
-     * Clears the screen of output
404
-     *
405
-     * @return	void
406
-     */
407
-    public static function clear_screen()
408
-    {
409
-        static::is_windows()
410
-
411
-            // Windows is a bit crap at this, but their terminal is tiny so shove this in
412
-            ? static::new_line(40)
413
-
414
-            // Anything with a flair of Unix will handle these magic characters
415
-            : fwrite(STDOUT, chr(27)."[H".chr(27)."[2J");
416
-    }
417
-
418
-    //--------------------------------------------------------------------
419
-
420
-    /**
421
-     * Returns the given text with the correct color codes for a foreground and
422
-     * optionally a background color.
423
-     *
424
-     * @param	string	$text		the text to color
425
-     * @param	string	$foreground the foreground color
426
-     * @param	string	$background the background color
427
-     * @param	string	$format		other formatting to apply. Currently only 'underline' is understood
428
-     * @return	string	the color coded string
429
-     */
430
-    public static function color($text, $foreground, $background = null, $format=null)
431
-    {
432
-        if (static::is_windows() and ! isset($_SERVER['ANSICON']))
433
-        {
434
-            return $text;
435
-        }
436
-
437
-        if ( ! array_key_exists($foreground, static::$foreground_colors))
438
-        {
439
-            throw new \RuntimeException('Invalid CLI foreground color: '.$foreground);
440
-        }
441
-
442
-        if ( $background !== null and ! array_key_exists($background, static::$background_colors))
443
-        {
444
-            throw new \RuntimeException('Invalid CLI background color: '.$background);
445
-        }
446
-
447
-        $string = "\033[".static::$foreground_colors[$foreground]."m";
448
-
449
-        if ($background !== null)
450
-        {
451
-            $string .= "\033[".static::$background_colors[$background]."m";
452
-        }
453
-
454
-        if ($format === 'underline')
455
-        {
456
-            $string .= "\033[4m";
457
-        }
458
-
459
-        $string .= $text."\033[0m";
460
-
461
-        return $string;
462
-    }
463
-
464
-    //--------------------------------------------------------------------
465
-
466
-    public static function getWidth($default=80)
467
-    {
468
-        if (static::is_windows())
469
-        {
470
-            return $default;
471
-        }
472
-
473
-        return (int)shell_exec('tput cols');
474
-    }
43
+	// Used by progress bar
44
+	protected static $inProgress = false;
45
+
46
+	protected static $foreground_colors = array(
47
+		'black'			=> '0;30',
48
+		'dark_gray'		=> '1;30',
49
+		'blue'			=> '0;34',
50
+		'dark_blue'		=> '1;34',
51
+		'light_blue'	=> '1;34',
52
+		'green'			=> '0;32',
53
+		'light_green'	=> '1;32',
54
+		'cyan'			=> '0;36',
55
+		'light_cyan'	=> '1;36',
56
+		'red'			=> '0;31',
57
+		'light_red'		=> '1;31',
58
+		'purple'		=> '0;35',
59
+		'light_purple'	=> '1;35',
60
+		'light_yellow'	=> '0;33',
61
+		'yellow'		=> '1;33',
62
+		'light_gray'	=> '0;37',
63
+		'white'			=> '1;37',
64
+	);
65
+
66
+	protected static $background_colors = array(
67
+		'black'			=> '40',
68
+		'red'			=> '41',
69
+		'green'			=> '42',
70
+		'yellow'		=> '43',
71
+		'blue'			=> '44',
72
+		'magenta'		=> '45',
73
+		'cyan'			=> '46',
74
+		'light_gray'	=> '47',
75
+	);
76
+
77
+	//--------------------------------------------------------------------
78
+
79
+	/**
80
+	 * Static constructor.	Parses all the CLI params.
81
+	 */
82
+	public static function _init()
83
+	{
84
+		if (static::$initialized === true)
85
+		{
86
+			return;
87
+		}
88
+
89
+		if ( ! (PHP_SAPI === 'cli' || defined('STDIN')) )
90
+		{
91
+			throw new \Exception('Cli class cannot be used outside of the command line.');
92
+		}
93
+
94
+		self::parseCommand();
95
+
96
+		// Readline is an extension for PHP that makes interactive with PHP much more bash-like
97
+		// http://www.php.net/manual/en/readline.installation.php
98
+		static::$readline_support = extension_loaded('readline');
99
+
100
+		static::$initialized = true;
101
+	}
102
+
103
+	//--------------------------------------------------------------------
104
+
105
+	/**
106
+	 * Grabs an individual
107
+	 *
108
+	 * @param $index
109
+	 * @return null
110
+	 */
111
+	public static function segment($index)
112
+	{
113
+		if (! isset(static::$segments[$index - 1]))
114
+		{
115
+			return null;
116
+		}
117
+
118
+		return static::$segments[$index - 1];
119
+	}
120
+
121
+	//--------------------------------------------------------------------
122
+
123
+	/**
124
+	 * Returns the command string portion of the arguments. Used
125
+	 * by the 'sprint' CLI script to grab the portion of the arguments
126
+	 * that is used to call the CodeIgniter application.
127
+	 *
128
+	 * @return string
129
+	 */
130
+	public static function cli_string()
131
+	{
132
+		return implode(' ', static::$segments);
133
+	}
134
+
135
+	//--------------------------------------------------------------------
136
+
137
+
138
+
139
+	/**
140
+	 * Get input from the shell, using readline or the standard STDIN
141
+	 *
142
+	 * Named options must be in the following formats:
143
+	 * php index.php user -v --v -name=John --name=John
144
+	 *
145
+	 * @param	string|int	$name	the name of the option (int if unnamed)
146
+	 * @return	string
147
+	 */
148
+	public static function input($prefix = '')
149
+	{
150
+		if (static::$readline_support)
151
+		{
152
+			return readline($prefix);
153
+		}
154
+
155
+		echo $prefix;
156
+		return fgets(STDIN);
157
+	}
158
+
159
+	//--------------------------------------------------------------------
160
+
161
+	/**
162
+	 * Asks the user for input.  This can have either 1 or 2 arguments.
163
+	 *
164
+	 * Usage:
165
+	 *
166
+	 * // Waits for any key press
167
+	 * CLI::prompt();
168
+	 *
169
+	 * // Takes any input
170
+	 * $color = CLI::prompt('What is your favorite color?');
171
+	 *
172
+	 * // Takes any input, but offers default
173
+	 * $color = CLI::prompt('What is your favourite color?', 'white');
174
+	 *
175
+	 * // Will only accept the options in the array
176
+	 * $ready = CLI::prompt('Are you ready?', array('y','n'));
177
+	 *
178
+	 * @return	string	the user input
179
+	 */
180
+	public static function prompt()
181
+	{
182
+		$args = func_get_args();
183
+
184
+		$options = array();
185
+		$output = '';
186
+		$default = null;
187
+
188
+		// How many we got
189
+		$arg_count = count($args);
190
+
191
+		// Is the last argument a boolean? True means required
192
+		$required = end($args) === true;
193
+
194
+		// Reduce the argument count if required was passed, we don't care about that anymore
195
+		$required === true and --$arg_count;
196
+
197
+		// This method can take a few crazy combinations of arguments, so lets work it out
198
+		switch ($arg_count)
199
+		{
200
+			case 2:
201
+
202
+				// E.g: $ready = CLI::prompt('Are you ready?', array('y','n'));
203
+				if (is_array($args[1]))
204
+				{
205
+					list($output, $options)=$args;
206
+				}
207
+
208
+				// E.g: $color = CLI::prompt('What is your favourite color?', 'white');
209
+				elseif (is_string($args[1]))
210
+				{
211
+					list($output, $default)=$args;
212
+				}
213
+
214
+				break;
215
+
216
+			case 1:
217
+
218
+				// No question (probably been asked already) so just show options
219
+				// E.g: $ready = CLI::prompt(array('y','n'));
220
+				if (is_array($args[0]))
221
+				{
222
+					$options = $args[0];
223
+				}
224
+
225
+				// Question without options
226
+				// E.g: $ready = CLI::prompt('What did you do today?');
227
+				elseif (is_string($args[0]))
228
+				{
229
+					$output = $args[0];
230
+				}
231
+
232
+				break;
233
+		}
234
+
235
+		// If a question has been asked with the read
236
+		if ($output !== '')
237
+		{
238
+			$extra_output = '';
239
+
240
+			if ($default !== null)
241
+			{
242
+				$extra_output = ' [ Default: "'.$default.'" ]';
243
+			}
244
+
245
+			elseif ($options !== array())
246
+			{
247
+				$extra_output = ' [ '.implode(', ', $options).' ]';
248
+			}
249
+
250
+			fwrite(STDOUT, $output.$extra_output.': ');
251
+		}
252
+
253
+		// Read the input from keyboard.
254
+		$input = trim(static::input()) ?: $default;
255
+
256
+		// No input provided and we require one (default will stop this being called)
257
+		if (empty($input) and $required === true)
258
+		{
259
+			static::write('This is required.');
260
+			static::new_line();
261
+
262
+			$input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
263
+		}
264
+
265
+		// If options are provided and the choice is not in the array, tell them to try again
266
+		if ( ! empty($options) and ! in_array($input, $options))
267
+		{
268
+			static::write('This is not a valid option. Please try again.');
269
+			static::new_line();
270
+
271
+			$input = forward_static_call_array(array(__CLASS__, 'prompt'), $args);
272
+		}
273
+
274
+		return $input;
275
+	}
276
+
277
+	//--------------------------------------------------------------------
278
+
279
+	/**
280
+	 * Outputs a string to the cli.	 If you send an array it will implode them
281
+	 * with a line break.
282
+	 *
283
+	 * @param	string|array	$text	the text to output, or array of lines
284
+	 */
285
+	public static function write($text = '', $foreground = null, $background = null)
286
+	{
287
+		if (is_array($text))
288
+		{
289
+			$text = implode(PHP_EOL, $text);
290
+		}
291
+
292
+		if ($foreground or $background)
293
+		{
294
+			$text = static::color($text, $foreground, $background);
295
+		}
296
+
297
+		fwrite(STDOUT, $text.PHP_EOL);
298
+	}
299
+
300
+	//--------------------------------------------------------------------
301
+
302
+	/**
303
+	 * Outputs an error to the CLI using STDERR instead of STDOUT
304
+	 *
305
+	 * @param	string|array	$text	the text to output, or array of errors
306
+	 */
307
+	public static function error($text = '', $foreground = 'light_red', $background = null)
308
+	{
309
+		if (is_array($text))
310
+		{
311
+			$text = implode(PHP_EOL, $text);
312
+		}
313
+
314
+		if ($foreground OR $background)
315
+		{
316
+			$text = static::color($text, $foreground, $background);
317
+		}
318
+
319
+		fwrite(STDERR, $text.PHP_EOL);
320
+	}
321
+
322
+	//--------------------------------------------------------------------
323
+
324
+	/**
325
+	 * Beeps a certain number of times.
326
+	 *
327
+	 * @param	int $num	the number of times to beep
328
+	 */
329
+	public static function beep($num = 1)
330
+	{
331
+		echo str_repeat("\x07", $num);
332
+	}
333
+
334
+	//--------------------------------------------------------------------
335
+
336
+	/**
337
+	 * Waits a certain number of seconds, optionally showing a wait message and
338
+	 * waiting for a key press.
339
+	 *
340
+	 * @param	int		$seconds	number of seconds
341
+	 * @param	bool	$countdown	show a countdown or not
342
+	 */
343
+	public static function wait($seconds = 0, $countdown = false)
344
+	{
345
+		if ($countdown === true)
346
+		{
347
+			$time = $seconds;
348
+
349
+			while ($time > 0)
350
+			{
351
+				fwrite(STDOUT, $time.'... ');
352
+				sleep(1);
353
+				$time--;
354
+			}
355
+			static::write();
356
+		}
357
+
358
+		else
359
+		{
360
+			if ($seconds > 0)
361
+			{
362
+				sleep($seconds);
363
+			}
364
+			else
365
+			{
366
+				static::write(static::$wait_msg);
367
+				static::input();
368
+			}
369
+		}
370
+	}
371
+
372
+
373
+	//--------------------------------------------------------------------
374
+
375
+	/**
376
+	 * if operating system === windows
377
+	 */
378
+	public static function is_windows()
379
+	{
380
+		return 'win' === strtolower(substr(php_uname("s"), 0, 3));
381
+	}
382
+
383
+	//--------------------------------------------------------------------
384
+
385
+	/**
386
+	 * Enter a number of empty lines
387
+	 *
388
+	 * @param	integer	Number of lines to output
389
+	 * @return	void
390
+	 */
391
+	public static function new_line($num = 1)
392
+	{
393
+		// Do it once or more, write with empty string gives us a new line
394
+		for($i = 0; $i < $num; $i++)
395
+		{
396
+			static::write();
397
+		}
398
+	}
399
+
400
+	//--------------------------------------------------------------------
401
+
402
+	/**
403
+	 * Clears the screen of output
404
+	 *
405
+	 * @return	void
406
+	 */
407
+	public static function clear_screen()
408
+	{
409
+		static::is_windows()
410
+
411
+			// Windows is a bit crap at this, but their terminal is tiny so shove this in
412
+			? static::new_line(40)
413
+
414
+			// Anything with a flair of Unix will handle these magic characters
415
+			: fwrite(STDOUT, chr(27)."[H".chr(27)."[2J");
416
+	}
417
+
418
+	//--------------------------------------------------------------------
419
+
420
+	/**
421
+	 * Returns the given text with the correct color codes for a foreground and
422
+	 * optionally a background color.
423
+	 *
424
+	 * @param	string	$text		the text to color
425
+	 * @param	string	$foreground the foreground color
426
+	 * @param	string	$background the background color
427
+	 * @param	string	$format		other formatting to apply. Currently only 'underline' is understood
428
+	 * @return	string	the color coded string
429
+	 */
430
+	public static function color($text, $foreground, $background = null, $format=null)
431
+	{
432
+		if (static::is_windows() and ! isset($_SERVER['ANSICON']))
433
+		{
434
+			return $text;
435
+		}
436
+
437
+		if ( ! array_key_exists($foreground, static::$foreground_colors))
438
+		{
439
+			throw new \RuntimeException('Invalid CLI foreground color: '.$foreground);
440
+		}
441
+
442
+		if ( $background !== null and ! array_key_exists($background, static::$background_colors))
443
+		{
444
+			throw new \RuntimeException('Invalid CLI background color: '.$background);
445
+		}
446
+
447
+		$string = "\033[".static::$foreground_colors[$foreground]."m";
448
+
449
+		if ($background !== null)
450
+		{
451
+			$string .= "\033[".static::$background_colors[$background]."m";
452
+		}
453
+
454
+		if ($format === 'underline')
455
+		{
456
+			$string .= "\033[4m";
457
+		}
458
+
459
+		$string .= $text."\033[0m";
460
+
461
+		return $string;
462
+	}
463
+
464
+	//--------------------------------------------------------------------
465
+
466
+	public static function getWidth($default=80)
467
+	{
468
+		if (static::is_windows())
469
+		{
470
+			return $default;
471
+		}
472
+
473
+		return (int)shell_exec('tput cols');
474
+	}
475 475
     
476
-    //--------------------------------------------------------------------
477
-
478
-    public static function getHeight($default=32)
479
-    {
480
-        if (static::is_windows())
481
-        {
482
-            return $default;
483
-        }
484
-
485
-        return (int)shell_exec('tput lines');
486
-    }
487
-
488
-    //--------------------------------------------------------------------
489
-
490
-    /**
491
-     * Displays a progress bar on the CLI. You must call it repeatedly
492
-     * to update it. Set $thisStep = false to erase the progress bar.
493
-     *
494
-     * @param int $thisStep
495
-     * @param int $totalSteps
496
-     */
497
-    public static function showProgress($thisStep=1, $totalSteps=10)
498
-    {
499
-        // The first time through, save
500
-        // our position so the script knows where to go
501
-        // back to when writing the bar, and
502
-        // at the end of the script.
503
-        if (! static::$inProgress) {
504
-            fwrite(STDOUT, "\0337");
505
-            static::$inProgress = true;
506
-        }
507
-
508
-        // Restore position
509
-        fwrite(STDERR, "\0338");
510
-
511
-        if ($thisStep !== false) {
512
-            // Don't allow div by zero or negative numbers....
513
-            $thisStep = abs($thisStep);
514
-            $totalSteps = $totalSteps < 1 ? 1 : $totalSteps;
515
-
516
-            $percent = intval( ($thisStep / $totalSteps) * 100 );
517
-            $step = (int)round($percent / 10);
518
-
519
-            // Write the progress bar
520
-            fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]");
521
-            // Textual representation...
522
-            fwrite(STDOUT, " {$percent}% Complete" . PHP_EOL);
523
-            // Move up, undo the PHP_EOL
524
-            fwrite(STDOUT, "\033[1A");
525
-        }
526
-        else
527
-        {
528
-            fwrite(STDERR, "\007");
529
-        }
530
-    }
531
-
532
-    //--------------------------------------------------------------------
476
+	//--------------------------------------------------------------------
477
+
478
+	public static function getHeight($default=32)
479
+	{
480
+		if (static::is_windows())
481
+		{
482
+			return $default;
483
+		}
484
+
485
+		return (int)shell_exec('tput lines');
486
+	}
487
+
488
+	//--------------------------------------------------------------------
489
+
490
+	/**
491
+	 * Displays a progress bar on the CLI. You must call it repeatedly
492
+	 * to update it. Set $thisStep = false to erase the progress bar.
493
+	 *
494
+	 * @param int $thisStep
495
+	 * @param int $totalSteps
496
+	 */
497
+	public static function showProgress($thisStep=1, $totalSteps=10)
498
+	{
499
+		// The first time through, save
500
+		// our position so the script knows where to go
501
+		// back to when writing the bar, and
502
+		// at the end of the script.
503
+		if (! static::$inProgress) {
504
+			fwrite(STDOUT, "\0337");
505
+			static::$inProgress = true;
506
+		}
507
+
508
+		// Restore position
509
+		fwrite(STDERR, "\0338");
510
+
511
+		if ($thisStep !== false) {
512
+			// Don't allow div by zero or negative numbers....
513
+			$thisStep = abs($thisStep);
514
+			$totalSteps = $totalSteps < 1 ? 1 : $totalSteps;
515
+
516
+			$percent = intval( ($thisStep / $totalSteps) * 100 );
517
+			$step = (int)round($percent / 10);
518
+
519
+			// Write the progress bar
520
+			fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]");
521
+			// Textual representation...
522
+			fwrite(STDOUT, " {$percent}% Complete" . PHP_EOL);
523
+			// Move up, undo the PHP_EOL
524
+			fwrite(STDOUT, "\033[1A");
525
+		}
526
+		else
527
+		{
528
+			fwrite(STDERR, "\007");
529
+		}
530
+	}
531
+
532
+	//--------------------------------------------------------------------
533 533
 
534 534
 	/**
535 535
 	 * Checks to see if an option was passed to us on the CLI and returns
@@ -541,11 +541,11 @@  discard block
 block discarded – undo
541 541
 	 */
542 542
 	public static function option($name)
543 543
 	{
544
-	    if (array_key_exists($name, self::$options))
545
-	    {
546
-		    $val = self::$options[$name] === null ? true : self::$options[$name];
547
-		    return $val;
548
-	    }
544
+		if (array_key_exists($name, self::$options))
545
+		{
546
+			$val = self::$options[$name] === null ? true : self::$options[$name];
547
+			return $val;
548
+		}
549 549
 
550 550
 		return null;
551 551
 	}
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
 	 */
560 560
 	public static function getOptions()
561 561
 	{
562
-	    return self::$options;
562
+		return self::$options;
563 563
 	}
564 564
 
565 565
 	//--------------------------------------------------------------------
@@ -615,10 +615,10 @@  discard block
 block discarded – undo
615 615
 			return '';
616 616
 		}
617 617
 
618
-        if ($max == 0)
619
-        {
620
-            $max = CLI::getWidth();
621
-        }
618
+		if ($max == 0)
619
+		{
620
+			$max = CLI::getWidth();
621
+		}
622 622
 
623 623
 		if (CLI::getWidth() < $max)
624 624
 		{
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 		    return;
87 87
 	    }
88 88
 
89
-        if ( ! (PHP_SAPI === 'cli' || defined('STDIN')) )
89
+        if ( ! (PHP_SAPI === 'cli' || defined('STDIN')))
90 90
         {
91 91
             throw new \Exception('Cli class cannot be used outside of the command line.');
92 92
         }
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
      */
111 111
     public static function segment($index)
112 112
     {
113
-        if (! isset(static::$segments[$index - 1]))
113
+        if ( ! isset(static::$segments[$index - 1]))
114 114
         {
115 115
             return null;
116 116
         }
@@ -202,13 +202,13 @@  discard block
 block discarded – undo
202 202
                 // E.g: $ready = CLI::prompt('Are you ready?', array('y','n'));
203 203
                 if (is_array($args[1]))
204 204
                 {
205
-                    list($output, $options)=$args;
205
+                    list($output, $options) = $args;
206 206
                 }
207 207
 
208 208
                 // E.g: $color = CLI::prompt('What is your favourite color?', 'white');
209 209
                 elseif (is_string($args[1]))
210 210
                 {
211
-                    list($output, $default)=$args;
211
+                    list($output, $default) = $args;
212 212
                 }
213 213
 
214 214
                 break;
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
     public static function new_line($num = 1)
392 392
     {
393 393
         // Do it once or more, write with empty string gives us a new line
394
-        for($i = 0; $i < $num; $i++)
394
+        for ($i = 0; $i < $num; $i++)
395 395
         {
396 396
             static::write();
397 397
         }
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
      * @param	string	$format		other formatting to apply. Currently only 'underline' is understood
428 428
      * @return	string	the color coded string
429 429
      */
430
-    public static function color($text, $foreground, $background = null, $format=null)
430
+    public static function color($text, $foreground, $background = null, $format = null)
431 431
     {
432 432
         if (static::is_windows() and ! isset($_SERVER['ANSICON']))
433 433
         {
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
             throw new \RuntimeException('Invalid CLI foreground color: '.$foreground);
440 440
         }
441 441
 
442
-        if ( $background !== null and ! array_key_exists($background, static::$background_colors))
442
+        if ($background !== null and ! array_key_exists($background, static::$background_colors))
443 443
         {
444 444
             throw new \RuntimeException('Invalid CLI background color: '.$background);
445 445
         }
@@ -463,26 +463,26 @@  discard block
 block discarded – undo
463 463
 
464 464
     //--------------------------------------------------------------------
465 465
 
466
-    public static function getWidth($default=80)
466
+    public static function getWidth($default = 80)
467 467
     {
468 468
         if (static::is_windows())
469 469
         {
470 470
             return $default;
471 471
         }
472 472
 
473
-        return (int)shell_exec('tput cols');
473
+        return (int) shell_exec('tput cols');
474 474
     }
475 475
     
476 476
     //--------------------------------------------------------------------
477 477
 
478
-    public static function getHeight($default=32)
478
+    public static function getHeight($default = 32)
479 479
     {
480 480
         if (static::is_windows())
481 481
         {
482 482
             return $default;
483 483
         }
484 484
 
485
-        return (int)shell_exec('tput lines');
485
+        return (int) shell_exec('tput lines');
486 486
     }
487 487
 
488 488
     //--------------------------------------------------------------------
@@ -494,13 +494,13 @@  discard block
 block discarded – undo
494 494
      * @param int $thisStep
495 495
      * @param int $totalSteps
496 496
      */
497
-    public static function showProgress($thisStep=1, $totalSteps=10)
497
+    public static function showProgress($thisStep = 1, $totalSteps = 10)
498 498
     {
499 499
         // The first time through, save
500 500
         // our position so the script knows where to go
501 501
         // back to when writing the bar, and
502 502
         // at the end of the script.
503
-        if (! static::$inProgress) {
503
+        if ( ! static::$inProgress) {
504 504
             fwrite(STDOUT, "\0337");
505 505
             static::$inProgress = true;
506 506
         }
@@ -513,13 +513,13 @@  discard block
 block discarded – undo
513 513
             $thisStep = abs($thisStep);
514 514
             $totalSteps = $totalSteps < 1 ? 1 : $totalSteps;
515 515
 
516
-            $percent = intval( ($thisStep / $totalSteps) * 100 );
517
-            $step = (int)round($percent / 10);
516
+            $percent = intval(($thisStep / $totalSteps) * 100);
517
+            $step = (int) round($percent / 10);
518 518
 
519 519
             // Write the progress bar
520
-            fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]");
520
+            fwrite(STDOUT, "[\033[32m".str_repeat('#', $step).str_repeat('.', 10 - $step)."\033[0m]");
521 521
             // Textual representation...
522
-            fwrite(STDOUT, " {$percent}% Complete" . PHP_EOL);
522
+            fwrite(STDOUT, " {$percent}% Complete".PHP_EOL);
523 523
             // Move up, undo the PHP_EOL
524 524
             fwrite(STDOUT, "\033[1A");
525 525
         }
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
 	 */
571 571
 	public static function optionString()
572 572
 	{
573
-		if (! count(static::$options))
573
+		if ( ! count(static::$options))
574 574
 		{
575 575
 			return '';
576 576
 		}
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 			// so it will pass correctly.
584 584
 			if (strpos($value, ' ') !== false)
585 585
 			{
586
-				$value = '"'. $value .'"';
586
+				$value = '"'.$value.'"';
587 587
 			}
588 588
 			$out .= "-{$name} $value ";
589 589
 		}
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 	 * @param int $max
609 609
 	 * @param int $pad_left
610 610
 	 */
611
-	public static function wrap($string=null, $max=0, $pad_left=0)
611
+	public static function wrap($string = null, $max = 0, $pad_left = 0)
612 612
 	{
613 613
 		if (empty($string))
614 614
 		{
@@ -630,13 +630,13 @@  discard block
 block discarded – undo
630 630
 		$lines = wordwrap($string, $max);
631 631
 
632 632
 		if ($pad_left > 0) {
633
-			$lines = explode( "\n", $lines );
633
+			$lines = explode("\n", $lines);
634 634
 
635 635
 			$first = true;
636 636
 
637
-			array_walk( $lines, function ( &$line, $index ) use($max, $pad_left, &$first) {
638
-				if (! $first) {
639
-					$line = str_repeat( " ", $pad_left ) . $line;
637
+			array_walk($lines, function(&$line, $index) use($max, $pad_left, &$first) {
638
+				if ( ! $first) {
639
+					$line = str_repeat(" ", $pad_left).$line;
640 640
 				}
641 641
 				else
642 642
 				{
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 		{
669 669
 			// If there's no '-' at the beginning of the argument
670 670
 			// then add it to our segments.
671
-			if (! $options_found && strpos($_SERVER['argv'][$i], '-') === false)
671
+			if ( ! $options_found && strpos($_SERVER['argv'][$i], '-') === false)
672 672
 			{
673 673
 				self::$segments[] = $_SERVER['argv'][$i];
674 674
 				continue;
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 			$value = null;
686 686
 
687 687
 			// If the next item starts with a dash it's a value
688
-			if (isset($_SERVER['argv'][$i + 1]) && substr($_SERVER['argv'][$i + 1], 0, 1) != '-' )
688
+			if (isset($_SERVER['argv'][$i + 1]) && substr($_SERVER['argv'][$i + 1], 0, 1) != '-')
689 689
 			{
690 690
 				$value = $_SERVER['argv'][$i + 1];
691 691
 				$i++;
Please login to merge, or discard this patch.
Braces   +5 added lines, -12 removed lines patch added patch discarded remove patch
@@ -240,9 +240,7 @@  discard block
 block discarded – undo
240 240
             if ($default !== null)
241 241
             {
242 242
                 $extra_output = ' [ Default: "'.$default.'" ]';
243
-            }
244
-
245
-            elseif ($options !== array())
243
+            } elseif ($options !== array())
246 244
             {
247 245
                 $extra_output = ' [ '.implode(', ', $options).' ]';
248 246
             }
@@ -353,15 +351,12 @@  discard block
 block discarded – undo
353 351
                 $time--;
354 352
             }
355 353
             static::write();
356
-        }
357
-
358
-        else
354
+        } else
359 355
         {
360 356
             if ($seconds > 0)
361 357
             {
362 358
                 sleep($seconds);
363
-            }
364
-            else
359
+            } else
365 360
             {
366 361
                 static::write(static::$wait_msg);
367 362
                 static::input();
@@ -522,8 +517,7 @@  discard block
 block discarded – undo
522 517
             fwrite(STDOUT, " {$percent}% Complete" . PHP_EOL);
523 518
             // Move up, undo the PHP_EOL
524 519
             fwrite(STDOUT, "\033[1A");
525
-        }
526
-        else
520
+        } else
527 521
         {
528 522
             fwrite(STDERR, "\007");
529 523
         }
@@ -637,8 +631,7 @@  discard block
 block discarded – undo
637 631
 			array_walk( $lines, function ( &$line, $index ) use($max, $pad_left, &$first) {
638 632
 				if (! $first) {
639 633
 					$line = str_repeat( " ", $pad_left ) . $line;
640
-				}
641
-				else
634
+				} else
642 635
 				{
643 636
 					$first = false;
644 637
 				}
Please login to merge, or discard this patch.
myth/Controllers/ThemedController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -368,7 +368,7 @@
 block discarded – undo
368 368
     /**
369 369
      * Adds an external javascript file to the 'external_scripts' array.
370 370
      *
371
-     * @param [type] $filename [description]
371
+     * @param string $filename [description]
372 372
      */
373 373
     public function addScript($filename)
374 374
     {
Please login to merge, or discard this patch.
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -41,358 +41,358 @@
 block discarded – undo
41 41
  */
42 42
 class ThemedController extends BaseController
43 43
 {
44
-    /**
45
-     * Stores data variables to be sent to the view.
46
-     * @var array
47
-     */
48
-    protected $vars = array();
49
-
50
-    /**
51
-     * Stores current status message.
52
-     * @var
53
-     */
54
-    protected $message;
55
-
56
-    /**
57
-     * The UIKit to make available to the template views.
58
-     * @var string
59
-     */
60
-    protected $uikit = '';
61
-
62
-    /**
63
-     * An instance of an active Themer to use.
64
-     * @var null
65
-     */
66
-    protected $themer = null;
67
-
68
-    /**
69
-     * Allows per-controller override of theme.
70
-     * @var null
71
-     */
72
-    protected $theme = null;
73
-
74
-    /**
75
-     * Per-controller override of the current layout file.
76
-     * @var null
77
-     */
78
-    protected $layout = null;
79
-
80
-    /**
81
-     * Stores an array of javascript files.
82
-     * @var array
83
-     */
84
-    protected $external_scripts = array();
85
-
86
-    /**
87
-     * Stores an array of CSS stylesheets.
88
-     * @var array
89
-     */
90
-    protected $stylesheets = array();
91
-
92
-    /**
93
-     * A MenuCollection instance
94
-     * @var
95
-     */
96
-    protected $meta;
97
-
98
-    /**
99
-     * Whether set() should escape the output...
100
-     * @var bool
101
-     */
102
-    protected $auto_escape = null;
103
-
104
-    /**
105
-     * An instance of ZendFrameworks Escaper
106
-     * @var null
107
-     */
108
-    protected $escaper = null;
109
-
110
-    //--------------------------------------------------------------------
111
-
112
-    /**
113
-     * Constructor takes care of getting the template engine up and running
114
-     * and bound to our DI object, as well as any other preliminary needs,
115
-     * like detecting the variant to use, etc.
116
-     */
117
-    public function __construct()
118
-    {
119
-        parent::__construct();
120
-
121
-        // Setup our Template Engine
122
-        $themer = config_item('active_themer');
123
-
124
-        if (empty($themer)) {
125
-            throw new \RuntimeException( lang('no_themer') );
126
-        }
127
-
128
-        $this->themer = new $themer( get_instance() );
129
-
130
-        // Register our paths with the themer
131
-        $paths = config_item('theme.paths');
132
-
133
-        foreach ($paths as $key => $path) {
134
-            $this->themer->addThemePath($key, $path);
135
-        }
136
-
137
-        // Set our default theme.
138
-        $this->themer->setDefaultTheme( config_item('theme.default_theme') );
139
-
140
-        // Register our variants with the engine.
141
-        $variants = config_item('theme.variants');
142
-
143
-        foreach ($variants as $key => $value) {
144
-            $this->themer->addVariant($key, $value);
145
-        }
146
-
147
-        $this->detectVariant();
148
-
149
-        // Ensure that our UIKit is loaded up if we're using one.
150
-        $uikit = config_item('theme.uikit');
151
-
152
-        if ($uikit)
153
-        {
154
-            $this->uikit = new $uikit();
155
-        }
156
-
157
-        // Load up our meta collection
158
-        $this->meta = new MetaCollection( get_instance() );
159
-
160
-        // Should we autoescape vars?
161
-        if (is_null($this->auto_escape))
162
-        {
163
-            $this->auto_escape = config_item( 'theme.auto_escape' );
164
-        }
165
-    }
166
-
167
-    //--------------------------------------------------------------------
168
-
169
-    /**
170
-     * Provides a common interface with the other rendering methods to
171
-     * set the output of the method. Uses the current instance of $this->template.
172
-     * Ensures that any data we've stored through $this->setVar() are present
173
-     * and includes the status messages into the data.
174
-     *
175
-     * @param array $data
176
-     * @param int   $cache_time
177
-     */
178
-    public function render($data = array(), $cache_time=0)
179
-    {
180
-	    if ($cache_time > 0)
181
-	    {
182
-		    $this->output->cache( (int)$cache_time );
183
-	    }
184
-
185
-        // Determine the correct theme to use
186
-        $theme = ! empty($this->theme) ? $this->theme : config_item('theme.default_theme');
187
-        $this->themer->setTheme($theme);
188
-
189
-        // Determine the correct layout to use
190
-        $layout = !empty($this->layout) ? $this->layout : null;
191
-        $this->themer->setLayout($layout);
192
-
193
-        // Merge any saved vars into the data
194
-        // But first, escape the data if needed
195
-        if ($this->auto_escape)
196
-        {
197
-            $data = esc($data, 'html');
198
-        }
199
-        $data = array_merge($data, $this->vars);
200
-
201
-        // Make sure the MetaCollection is available in the view.
202
-        $data['html_meta'] = $this->meta;
203
-
204
-        // Include our UIKit so views can use it
205
-        if (! empty($this->uikit)) {
206
-            $data['uikit'] = $this->uikit;
207
-        }
208
-
209
-        // Build our notices from the theme's view file.
210
-        $data['notice'] = $this->themer->display($this->themer->theme() . ':notice', ["notice" => $this->message()]);
211
-
212
-        // Make sure any scripts/stylesheets are available to the view
213
-        $data['external_scripts'] = $this->external_scripts;
214
-        $data['stylesheets'] = $this->stylesheets;
215
-
216
-        $this->themer->set($data);
217
-
218
-        $this->output->set_content_type('html')
219
-                     ->set_output($this->themer->render());
220
-    }
221
-
222
-    //--------------------------------------------------------------------
223
-
224
-    /**
225
-     * Sets a data variable to be sent to the view during the render() method.
226
-     * Will auto-escape data on the way in, unless specifically told not to.
227
-     *
228
-     * Uses ZendFramework's Escaper to handle the data escaping,
229
-     * based on context. Valid contexts are:
230
-     *      - html
231
-     *      - htmlAttr
232
-     *      - js
233
-     *      - css
234
-     *      - url
235
-     *
236
-     * @param string $name
237
-     * @param mixed $value
238
-     * @param string $context
239
-     * @param bool $do_escape
240
-     */
241
-    public function setVar($name, $value = null, $context='html', $do_escape=null)
242
-    {
243
-        $escape = $do_escape == true ? true : $this->auto_escape;
244
-
245
-        if (is_null($this->escaper))
246
-        {
247
-            $this->escaper = new Escaper(config_item('charset'));
248
-        }
249
-
250
-        if (is_array($name))
251
-        {
252
-            foreach ($name as $k => $v)
253
-            {
254
-                $this->vars[$k] = $escape ? esc($v, $context, $this->escaper) : $v;
255
-            }
256
-        }
257
-        else
258
-        {
259
-            $this->vars[$name] = $escape ? esc($value, $context, $this->escaper) : $value;
260
-        }
261
-    }
262
-
263
-    //--------------------------------------------------------------------
264
-
265
-    //--------------------------------------------------------------------
266
-    // Status Messages
267
-    //--------------------------------------------------------------------
268
-
269
-    /**
270
-     * Sets a status message (for displaying small success/error messages).
271
-     * This is used in place of the session->flashdata functions since you
272
-     * don't always want to have to refresh the page to show the message.
273
-     *
274
-     * @param string $message The message to save.
275
-     * @param string $type The string to be included as the CSS class of the containing div.
276
-     */
277
-    public function setMessage($message = '', $type = 'info')
278
-    {
279
-        if (! empty($message)) {
280
-            if (isset($this->session)) {
281
-                $this->session->set_flashdata('message', $type . '::' . $message);
282
-            }
283
-
284
-            $this->message = array(
285
-                'type' => $type,
286
-                'message' => $message
287
-            );
288
-        }
289
-    }
290
-
291
-    //--------------------------------------------------------------------
292
-
293
-    /**
294
-     * Retrieves the status message to display (if any).
295
-     *
296
-     * @param  string $message [description]
297
-     * @param  string $type [description]
298
-     * @return array
299
-     */
300
-    public function message($message = '', $type = 'info')
301
-    {
302
-        $return = array(
303
-            'message' => $message,
304
-            'type' => $type
305
-        );
306
-
307
-        // Does session data exist?
308
-        if (empty($message) && class_exists('CI_Session')) {
309
-            $message = $this->session->flashdata('message');
310
-
311
-            if (! empty($message)) {
312
-                // Split out our message parts
313
-                $temp_message = explode('::', $message);
314
-                $return['type'] = $temp_message[0];
315
-                $return['message'] = $temp_message[1];
316
-
317
-                unset($temp_message);
318
-            }
319
-        }
320
-
321
-        // If message is empty, we need to check our own storage.
322
-        if (empty($message)) {
323
-            if (empty($this->message['message'])) {
324
-                return '';
325
-            }
326
-
327
-            $return = $this->message;
328
-        }
329
-
330
-        // Clear our session data so we don't get extra messages on rare occasions.
331
-        if (class_exists('CI_Session')) {
332
-            $this->session->set_flashdata('message', '');
333
-        }
334
-
335
-        return $return;
336
-    }
337
-
338
-    //--------------------------------------------------------------------
339
-
340
-    //--------------------------------------------------------------------
341
-    // Utility Methods
342
-    //--------------------------------------------------------------------
343
-
344
-    /**
345
-     * Detects whether the item is being displayed on a desktop, phone,
346
-     * or tablet device.
347
-     */
348
-    protected function detectVariant()
349
-    {
350
-        // Variant Detection and setup
351
-        if (config_item('autodetect_variant') === true) {
352
-            $detect = new \Mobile_Detect();
353
-
354
-            if ($detect->isMobile()) {
355
-                $this->template->setVariant('phone');
356
-            } else if ($detect->isTablet()) {
357
-                $this->template->setVariant('tablet');
358
-            }
359
-        }
360
-    }
361
-
362
-    //--------------------------------------------------------------------
363
-
364
-    //--------------------------------------------------------------------
365
-    // 'Asset' functions
366
-    //--------------------------------------------------------------------
367
-
368
-    /**
369
-     * Adds an external javascript file to the 'external_scripts' array.
370
-     *
371
-     * @param [type] $filename [description]
372
-     */
373
-    public function addScript($filename)
374
-    {
375
-        if (strpos($filename, 'http') === FALSE) {
376
-            $filename = base_url() . 'assets/js/' . $filename;
377
-        }
378
-
379
-        $this->external_scripts[] = $filename;
380
-    }
381
-
382
-    //--------------------------------------------------------------------
383
-
384
-    /**
385
-     * Adds an external stylesheet file to the 'stylesheets' array.
386
-     */
387
-    public function addStyle($filename)
388
-    {
389
-        if (strpos($filename, 'http') === FALSE) {
390
-            $filename = base_url() . 'assets/css/' . $filename;
391
-        }
392
-
393
-        $this->stylesheets[] = $filename;
394
-    }
395
-
396
-    //--------------------------------------------------------------------
44
+	/**
45
+	 * Stores data variables to be sent to the view.
46
+	 * @var array
47
+	 */
48
+	protected $vars = array();
49
+
50
+	/**
51
+	 * Stores current status message.
52
+	 * @var
53
+	 */
54
+	protected $message;
55
+
56
+	/**
57
+	 * The UIKit to make available to the template views.
58
+	 * @var string
59
+	 */
60
+	protected $uikit = '';
61
+
62
+	/**
63
+	 * An instance of an active Themer to use.
64
+	 * @var null
65
+	 */
66
+	protected $themer = null;
67
+
68
+	/**
69
+	 * Allows per-controller override of theme.
70
+	 * @var null
71
+	 */
72
+	protected $theme = null;
73
+
74
+	/**
75
+	 * Per-controller override of the current layout file.
76
+	 * @var null
77
+	 */
78
+	protected $layout = null;
79
+
80
+	/**
81
+	 * Stores an array of javascript files.
82
+	 * @var array
83
+	 */
84
+	protected $external_scripts = array();
85
+
86
+	/**
87
+	 * Stores an array of CSS stylesheets.
88
+	 * @var array
89
+	 */
90
+	protected $stylesheets = array();
91
+
92
+	/**
93
+	 * A MenuCollection instance
94
+	 * @var
95
+	 */
96
+	protected $meta;
97
+
98
+	/**
99
+	 * Whether set() should escape the output...
100
+	 * @var bool
101
+	 */
102
+	protected $auto_escape = null;
103
+
104
+	/**
105
+	 * An instance of ZendFrameworks Escaper
106
+	 * @var null
107
+	 */
108
+	protected $escaper = null;
109
+
110
+	//--------------------------------------------------------------------
111
+
112
+	/**
113
+	 * Constructor takes care of getting the template engine up and running
114
+	 * and bound to our DI object, as well as any other preliminary needs,
115
+	 * like detecting the variant to use, etc.
116
+	 */
117
+	public function __construct()
118
+	{
119
+		parent::__construct();
120
+
121
+		// Setup our Template Engine
122
+		$themer = config_item('active_themer');
123
+
124
+		if (empty($themer)) {
125
+			throw new \RuntimeException( lang('no_themer') );
126
+		}
127
+
128
+		$this->themer = new $themer( get_instance() );
129
+
130
+		// Register our paths with the themer
131
+		$paths = config_item('theme.paths');
132
+
133
+		foreach ($paths as $key => $path) {
134
+			$this->themer->addThemePath($key, $path);
135
+		}
136
+
137
+		// Set our default theme.
138
+		$this->themer->setDefaultTheme( config_item('theme.default_theme') );
139
+
140
+		// Register our variants with the engine.
141
+		$variants = config_item('theme.variants');
142
+
143
+		foreach ($variants as $key => $value) {
144
+			$this->themer->addVariant($key, $value);
145
+		}
146
+
147
+		$this->detectVariant();
148
+
149
+		// Ensure that our UIKit is loaded up if we're using one.
150
+		$uikit = config_item('theme.uikit');
151
+
152
+		if ($uikit)
153
+		{
154
+			$this->uikit = new $uikit();
155
+		}
156
+
157
+		// Load up our meta collection
158
+		$this->meta = new MetaCollection( get_instance() );
159
+
160
+		// Should we autoescape vars?
161
+		if (is_null($this->auto_escape))
162
+		{
163
+			$this->auto_escape = config_item( 'theme.auto_escape' );
164
+		}
165
+	}
166
+
167
+	//--------------------------------------------------------------------
168
+
169
+	/**
170
+	 * Provides a common interface with the other rendering methods to
171
+	 * set the output of the method. Uses the current instance of $this->template.
172
+	 * Ensures that any data we've stored through $this->setVar() are present
173
+	 * and includes the status messages into the data.
174
+	 *
175
+	 * @param array $data
176
+	 * @param int   $cache_time
177
+	 */
178
+	public function render($data = array(), $cache_time=0)
179
+	{
180
+		if ($cache_time > 0)
181
+		{
182
+			$this->output->cache( (int)$cache_time );
183
+		}
184
+
185
+		// Determine the correct theme to use
186
+		$theme = ! empty($this->theme) ? $this->theme : config_item('theme.default_theme');
187
+		$this->themer->setTheme($theme);
188
+
189
+		// Determine the correct layout to use
190
+		$layout = !empty($this->layout) ? $this->layout : null;
191
+		$this->themer->setLayout($layout);
192
+
193
+		// Merge any saved vars into the data
194
+		// But first, escape the data if needed
195
+		if ($this->auto_escape)
196
+		{
197
+			$data = esc($data, 'html');
198
+		}
199
+		$data = array_merge($data, $this->vars);
200
+
201
+		// Make sure the MetaCollection is available in the view.
202
+		$data['html_meta'] = $this->meta;
203
+
204
+		// Include our UIKit so views can use it
205
+		if (! empty($this->uikit)) {
206
+			$data['uikit'] = $this->uikit;
207
+		}
208
+
209
+		// Build our notices from the theme's view file.
210
+		$data['notice'] = $this->themer->display($this->themer->theme() . ':notice', ["notice" => $this->message()]);
211
+
212
+		// Make sure any scripts/stylesheets are available to the view
213
+		$data['external_scripts'] = $this->external_scripts;
214
+		$data['stylesheets'] = $this->stylesheets;
215
+
216
+		$this->themer->set($data);
217
+
218
+		$this->output->set_content_type('html')
219
+					 ->set_output($this->themer->render());
220
+	}
221
+
222
+	//--------------------------------------------------------------------
223
+
224
+	/**
225
+	 * Sets a data variable to be sent to the view during the render() method.
226
+	 * Will auto-escape data on the way in, unless specifically told not to.
227
+	 *
228
+	 * Uses ZendFramework's Escaper to handle the data escaping,
229
+	 * based on context. Valid contexts are:
230
+	 *      - html
231
+	 *      - htmlAttr
232
+	 *      - js
233
+	 *      - css
234
+	 *      - url
235
+	 *
236
+	 * @param string $name
237
+	 * @param mixed $value
238
+	 * @param string $context
239
+	 * @param bool $do_escape
240
+	 */
241
+	public function setVar($name, $value = null, $context='html', $do_escape=null)
242
+	{
243
+		$escape = $do_escape == true ? true : $this->auto_escape;
244
+
245
+		if (is_null($this->escaper))
246
+		{
247
+			$this->escaper = new Escaper(config_item('charset'));
248
+		}
249
+
250
+		if (is_array($name))
251
+		{
252
+			foreach ($name as $k => $v)
253
+			{
254
+				$this->vars[$k] = $escape ? esc($v, $context, $this->escaper) : $v;
255
+			}
256
+		}
257
+		else
258
+		{
259
+			$this->vars[$name] = $escape ? esc($value, $context, $this->escaper) : $value;
260
+		}
261
+	}
262
+
263
+	//--------------------------------------------------------------------
264
+
265
+	//--------------------------------------------------------------------
266
+	// Status Messages
267
+	//--------------------------------------------------------------------
268
+
269
+	/**
270
+	 * Sets a status message (for displaying small success/error messages).
271
+	 * This is used in place of the session->flashdata functions since you
272
+	 * don't always want to have to refresh the page to show the message.
273
+	 *
274
+	 * @param string $message The message to save.
275
+	 * @param string $type The string to be included as the CSS class of the containing div.
276
+	 */
277
+	public function setMessage($message = '', $type = 'info')
278
+	{
279
+		if (! empty($message)) {
280
+			if (isset($this->session)) {
281
+				$this->session->set_flashdata('message', $type . '::' . $message);
282
+			}
283
+
284
+			$this->message = array(
285
+				'type' => $type,
286
+				'message' => $message
287
+			);
288
+		}
289
+	}
290
+
291
+	//--------------------------------------------------------------------
292
+
293
+	/**
294
+	 * Retrieves the status message to display (if any).
295
+	 *
296
+	 * @param  string $message [description]
297
+	 * @param  string $type [description]
298
+	 * @return array
299
+	 */
300
+	public function message($message = '', $type = 'info')
301
+	{
302
+		$return = array(
303
+			'message' => $message,
304
+			'type' => $type
305
+		);
306
+
307
+		// Does session data exist?
308
+		if (empty($message) && class_exists('CI_Session')) {
309
+			$message = $this->session->flashdata('message');
310
+
311
+			if (! empty($message)) {
312
+				// Split out our message parts
313
+				$temp_message = explode('::', $message);
314
+				$return['type'] = $temp_message[0];
315
+				$return['message'] = $temp_message[1];
316
+
317
+				unset($temp_message);
318
+			}
319
+		}
320
+
321
+		// If message is empty, we need to check our own storage.
322
+		if (empty($message)) {
323
+			if (empty($this->message['message'])) {
324
+				return '';
325
+			}
326
+
327
+			$return = $this->message;
328
+		}
329
+
330
+		// Clear our session data so we don't get extra messages on rare occasions.
331
+		if (class_exists('CI_Session')) {
332
+			$this->session->set_flashdata('message', '');
333
+		}
334
+
335
+		return $return;
336
+	}
337
+
338
+	//--------------------------------------------------------------------
339
+
340
+	//--------------------------------------------------------------------
341
+	// Utility Methods
342
+	//--------------------------------------------------------------------
343
+
344
+	/**
345
+	 * Detects whether the item is being displayed on a desktop, phone,
346
+	 * or tablet device.
347
+	 */
348
+	protected function detectVariant()
349
+	{
350
+		// Variant Detection and setup
351
+		if (config_item('autodetect_variant') === true) {
352
+			$detect = new \Mobile_Detect();
353
+
354
+			if ($detect->isMobile()) {
355
+				$this->template->setVariant('phone');
356
+			} else if ($detect->isTablet()) {
357
+				$this->template->setVariant('tablet');
358
+			}
359
+		}
360
+	}
361
+
362
+	//--------------------------------------------------------------------
363
+
364
+	//--------------------------------------------------------------------
365
+	// 'Asset' functions
366
+	//--------------------------------------------------------------------
367
+
368
+	/**
369
+	 * Adds an external javascript file to the 'external_scripts' array.
370
+	 *
371
+	 * @param [type] $filename [description]
372
+	 */
373
+	public function addScript($filename)
374
+	{
375
+		if (strpos($filename, 'http') === FALSE) {
376
+			$filename = base_url() . 'assets/js/' . $filename;
377
+		}
378
+
379
+		$this->external_scripts[] = $filename;
380
+	}
381
+
382
+	//--------------------------------------------------------------------
383
+
384
+	/**
385
+	 * Adds an external stylesheet file to the 'stylesheets' array.
386
+	 */
387
+	public function addStyle($filename)
388
+	{
389
+		if (strpos($filename, 'http') === FALSE) {
390
+			$filename = base_url() . 'assets/css/' . $filename;
391
+		}
392
+
393
+		$this->stylesheets[] = $filename;
394
+	}
395
+
396
+	//--------------------------------------------------------------------
397 397
 }
398 398
 
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
 use Myth\Themers\MetaCollection;
33 33
 use Zend\Escaper\Escaper;
34 34
 
35
-require_once dirname(__FILE__) .'/../Themers/escape.php';
35
+require_once dirname(__FILE__).'/../Themers/escape.php';
36 36
 
37 37
 /**
38 38
  * Class ThemedController
@@ -122,10 +122,10 @@  discard block
 block discarded – undo
122 122
         $themer = config_item('active_themer');
123 123
 
124 124
         if (empty($themer)) {
125
-            throw new \RuntimeException( lang('no_themer') );
125
+            throw new \RuntimeException(lang('no_themer'));
126 126
         }
127 127
 
128
-        $this->themer = new $themer( get_instance() );
128
+        $this->themer = new $themer(get_instance());
129 129
 
130 130
         // Register our paths with the themer
131 131
         $paths = config_item('theme.paths');
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
         }
136 136
 
137 137
         // Set our default theme.
138
-        $this->themer->setDefaultTheme( config_item('theme.default_theme') );
138
+        $this->themer->setDefaultTheme(config_item('theme.default_theme'));
139 139
 
140 140
         // Register our variants with the engine.
141 141
         $variants = config_item('theme.variants');
@@ -155,12 +155,12 @@  discard block
 block discarded – undo
155 155
         }
156 156
 
157 157
         // Load up our meta collection
158
-        $this->meta = new MetaCollection( get_instance() );
158
+        $this->meta = new MetaCollection(get_instance());
159 159
 
160 160
         // Should we autoescape vars?
161 161
         if (is_null($this->auto_escape))
162 162
         {
163
-            $this->auto_escape = config_item( 'theme.auto_escape' );
163
+            $this->auto_escape = config_item('theme.auto_escape');
164 164
         }
165 165
     }
166 166
 
@@ -175,11 +175,11 @@  discard block
 block discarded – undo
175 175
      * @param array $data
176 176
      * @param int   $cache_time
177 177
      */
178
-    public function render($data = array(), $cache_time=0)
178
+    public function render($data = array(), $cache_time = 0)
179 179
     {
180 180
 	    if ($cache_time > 0)
181 181
 	    {
182
-		    $this->output->cache( (int)$cache_time );
182
+		    $this->output->cache((int) $cache_time);
183 183
 	    }
184 184
 
185 185
         // Determine the correct theme to use
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
         $this->themer->setTheme($theme);
188 188
 
189 189
         // Determine the correct layout to use
190
-        $layout = !empty($this->layout) ? $this->layout : null;
190
+        $layout = ! empty($this->layout) ? $this->layout : null;
191 191
         $this->themer->setLayout($layout);
192 192
 
193 193
         // Merge any saved vars into the data
@@ -202,12 +202,12 @@  discard block
 block discarded – undo
202 202
         $data['html_meta'] = $this->meta;
203 203
 
204 204
         // Include our UIKit so views can use it
205
-        if (! empty($this->uikit)) {
205
+        if ( ! empty($this->uikit)) {
206 206
             $data['uikit'] = $this->uikit;
207 207
         }
208 208
 
209 209
         // Build our notices from the theme's view file.
210
-        $data['notice'] = $this->themer->display($this->themer->theme() . ':notice', ["notice" => $this->message()]);
210
+        $data['notice'] = $this->themer->display($this->themer->theme().':notice', ["notice" => $this->message()]);
211 211
 
212 212
         // Make sure any scripts/stylesheets are available to the view
213 213
         $data['external_scripts'] = $this->external_scripts;
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
      * @param string $context
239 239
      * @param bool $do_escape
240 240
      */
241
-    public function setVar($name, $value = null, $context='html', $do_escape=null)
241
+    public function setVar($name, $value = null, $context = 'html', $do_escape = null)
242 242
     {
243 243
         $escape = $do_escape == true ? true : $this->auto_escape;
244 244
 
@@ -276,9 +276,9 @@  discard block
 block discarded – undo
276 276
      */
277 277
     public function setMessage($message = '', $type = 'info')
278 278
     {
279
-        if (! empty($message)) {
279
+        if ( ! empty($message)) {
280 280
             if (isset($this->session)) {
281
-                $this->session->set_flashdata('message', $type . '::' . $message);
281
+                $this->session->set_flashdata('message', $type.'::'.$message);
282 282
             }
283 283
 
284 284
             $this->message = array(
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
         if (empty($message) && class_exists('CI_Session')) {
309 309
             $message = $this->session->flashdata('message');
310 310
 
311
-            if (! empty($message)) {
311
+            if ( ! empty($message)) {
312 312
                 // Split out our message parts
313 313
                 $temp_message = explode('::', $message);
314 314
                 $return['type'] = $temp_message[0];
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
     public function addScript($filename)
374 374
     {
375 375
         if (strpos($filename, 'http') === FALSE) {
376
-            $filename = base_url() . 'assets/js/' . $filename;
376
+            $filename = base_url().'assets/js/'.$filename;
377 377
         }
378 378
 
379 379
         $this->external_scripts[] = $filename;
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
     public function addStyle($filename)
388 388
     {
389 389
         if (strpos($filename, 'http') === FALSE) {
390
-            $filename = base_url() . 'assets/css/' . $filename;
390
+            $filename = base_url().'assets/css/'.$filename;
391 391
         }
392 392
 
393 393
         $this->stylesheets[] = $filename;
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -253,8 +253,7 @@
 block discarded – undo
253 253
             {
254 254
                 $this->vars[$k] = $escape ? esc($v, $context, $this->escaper) : $v;
255 255
             }
256
-        }
257
-        else
256
+        } else
258 257
         {
259 258
             $this->vars[$name] = $escape ? esc($value, $context, $this->escaper) : $value;
260 259
         }
Please login to merge, or discard this patch.
myth/Cron/CronTask.php 4 patches
Doc Comments   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
     /**
67 67
      * Stores our scheduled string and actual task.
68 68
      *
69
-     * @param $schedule
69
+     * @param string $schedule
70 70
      * @param callable $task
71 71
      */
72 72
     public function __construct($schedule, $task)
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
      *
91 91
      * @param int|'now' $current_time
92 92
      *
93
-     * @return timestamp|null
93
+     * @return integer|null
94 94
      */
95 95
     public function nextRunDate($current_time='now')
96 96
     {
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
      *
122 122
      * @param int|'now' $current_time
123 123
      *
124
-     * @return timestamp|null
124
+     * @return integer|null
125 125
      */
126 126
     public function previousRunDate($current_time='now')
127 127
     {
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      * into any format available to date.
172 172
      *
173 173
      * @param $format_string
174
-     * @return bool|string
174
+     * @return string
175 175
      */
176 176
     public function format($format_string)
177 177
     {
@@ -266,8 +266,8 @@  discard block
 block discarded – undo
266 266
      * 'every 5 minutes', every 3 days, etc.
267 267
      *
268 268
      * @param $schedule
269
-     * @param $type
270
-     * @return float|int|null
269
+     * @param string $type
270
+     * @return integer|null
271 271
      */
272 272
     public function findDateInterval($schedule, $type, $current_time='now')
273 273
     {
Please login to merge, or discard this patch.
Indentation   +291 added lines, -291 removed lines patch added patch discarded remove patch
@@ -45,301 +45,301 @@
 block discarded – undo
45 45
  */
46 46
 class CronTask {
47 47
 
48
-    /**
49
-     * The original scheduled string.
50
-     * Any valid relative time string.
51
-     * http://php.net/manual/en/datetime.formats.relative.php
52
-     *
53
-     * @var
54
-     */
55
-    protected $schedule;
56
-
57
-    /**
58
-     * Stores the callable or library name:method to run.
59
-     *
60
-     * @var
61
-     */
62
-    protected $task;
63
-
64
-    //--------------------------------------------------------------------
65
-
66
-    /**
67
-     * Stores our scheduled string and actual task.
68
-     *
69
-     * @param $schedule
70
-     * @param callable $task
71
-     */
72
-    public function __construct($schedule, $task)
73
-    {
74
-        $this->schedule = $schedule;
75
-
76
-        // If $task is not callable, it should be a library:method
77
-        // string that we can parse. But it must have the colon in the string.
78
-        if (! is_callable($task) && strpos($task, ':') === false)
79
-        {
80
-            throw new \RuntimeException( lang('cron.invalid_task') );
81
-        }
82
-
83
-        $this->task = $task;
84
-    }
85
-
86
-    //--------------------------------------------------------------------
87
-
88
-    /**
89
-     * Calculates the next date this task is supposed to run.
90
-     *
91
-     * @param int|'now' $current_time
92
-     *
93
-     * @return timestamp|null
94
-     */
95
-    public function nextRunDate($current_time='now')
96
-    {
97
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
98
-
99
-        $scheduleType = $this->determineScheduleType($this->schedule);
100
-
101
-        switch ($scheduleType)
102
-        {
103
-            case 'time':
104
-                return $this->findDateInterval($this->schedule, 'next', $current_time);
105
-                break;
106
-            case 'ordinal':
107
-                return strtotime($this->schedule, $current_time);
108
-                break;
109
-            case 'increment':
110
-                return strtotime($this->schedule, $current_time);
111
-                break;
112
-        }
113
-
114
-        return null;
115
-    }
48
+	/**
49
+	 * The original scheduled string.
50
+	 * Any valid relative time string.
51
+	 * http://php.net/manual/en/datetime.formats.relative.php
52
+	 *
53
+	 * @var
54
+	 */
55
+	protected $schedule;
56
+
57
+	/**
58
+	 * Stores the callable or library name:method to run.
59
+	 *
60
+	 * @var
61
+	 */
62
+	protected $task;
63
+
64
+	//--------------------------------------------------------------------
65
+
66
+	/**
67
+	 * Stores our scheduled string and actual task.
68
+	 *
69
+	 * @param $schedule
70
+	 * @param callable $task
71
+	 */
72
+	public function __construct($schedule, $task)
73
+	{
74
+		$this->schedule = $schedule;
75
+
76
+		// If $task is not callable, it should be a library:method
77
+		// string that we can parse. But it must have the colon in the string.
78
+		if (! is_callable($task) && strpos($task, ':') === false)
79
+		{
80
+			throw new \RuntimeException( lang('cron.invalid_task') );
81
+		}
82
+
83
+		$this->task = $task;
84
+	}
85
+
86
+	//--------------------------------------------------------------------
87
+
88
+	/**
89
+	 * Calculates the next date this task is supposed to run.
90
+	 *
91
+	 * @param int|'now' $current_time
92
+	 *
93
+	 * @return timestamp|null
94
+	 */
95
+	public function nextRunDate($current_time='now')
96
+	{
97
+		$current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
98
+
99
+		$scheduleType = $this->determineScheduleType($this->schedule);
100
+
101
+		switch ($scheduleType)
102
+		{
103
+			case 'time':
104
+				return $this->findDateInterval($this->schedule, 'next', $current_time);
105
+				break;
106
+			case 'ordinal':
107
+				return strtotime($this->schedule, $current_time);
108
+				break;
109
+			case 'increment':
110
+				return strtotime($this->schedule, $current_time);
111
+				break;
112
+		}
113
+
114
+		return null;
115
+	}
116 116
     
117
-    //--------------------------------------------------------------------
118
-
119
-    /**
120
-     * Calculates the last time the task should have ran.
121
-     *
122
-     * @param int|'now' $current_time
123
-     *
124
-     * @return timestamp|null
125
-     */
126
-    public function previousRunDate($current_time='now')
127
-    {
128
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
129
-
130
-        $scheduleType = $this->determineScheduleType($this->schedule);
131
-
132
-        switch ($scheduleType)
133
-        {
134
-            case 'time':
135
-                return $this->findDateInterval($this->schedule, 'prev', $current_time);
136
-                break;
137
-            case 'ordinal':
138
-                return $this->findPreviousOrdinal($this->schedule, $current_time);
139
-                break;
140
-            case 'increment':
141
-                return strtotime('-1 '. $this->schedule, $current_time);
142
-                break;
143
-        }
144
-
145
-        return null;
146
-    }
147
-
148
-    //--------------------------------------------------------------------
149
-
150
-    /**
151
-     * Determines if the task is due to be run now.
152
-     *
153
-     * @param string $current_time
154
-     * @internal param $ int|'now' $current_time
155
-     *
156
-     * @return bool
157
-     */
158
-    public function isDue($current_time='now')
159
-    {
160
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
161
-
162
-        // For easier matching, and I can't imagine people needing cronjob
163
-        // accuracy to the seconds, we'll just take the current minute.
164
-        return date('Y-m-d H:i', $current_time) == date('Y-m-d H:i', $this->nextRunDate($current_time) );
165
-    }
117
+	//--------------------------------------------------------------------
118
+
119
+	/**
120
+	 * Calculates the last time the task should have ran.
121
+	 *
122
+	 * @param int|'now' $current_time
123
+	 *
124
+	 * @return timestamp|null
125
+	 */
126
+	public function previousRunDate($current_time='now')
127
+	{
128
+		$current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
129
+
130
+		$scheduleType = $this->determineScheduleType($this->schedule);
131
+
132
+		switch ($scheduleType)
133
+		{
134
+			case 'time':
135
+				return $this->findDateInterval($this->schedule, 'prev', $current_time);
136
+				break;
137
+			case 'ordinal':
138
+				return $this->findPreviousOrdinal($this->schedule, $current_time);
139
+				break;
140
+			case 'increment':
141
+				return strtotime('-1 '. $this->schedule, $current_time);
142
+				break;
143
+		}
144
+
145
+		return null;
146
+	}
147
+
148
+	//--------------------------------------------------------------------
149
+
150
+	/**
151
+	 * Determines if the task is due to be run now.
152
+	 *
153
+	 * @param string $current_time
154
+	 * @internal param $ int|'now' $current_time
155
+	 *
156
+	 * @return bool
157
+	 */
158
+	public function isDue($current_time='now')
159
+	{
160
+		$current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
161
+
162
+		// For easier matching, and I can't imagine people needing cronjob
163
+		// accuracy to the seconds, we'll just take the current minute.
164
+		return date('Y-m-d H:i', $current_time) == date('Y-m-d H:i', $this->nextRunDate($current_time) );
165
+	}
166 166
     
167
-    //--------------------------------------------------------------------
168
-
169
-    /**
170
-     * Formats the timestamp produced by nextRunDate and previousRunDate
171
-     * into any format available to date.
172
-     *
173
-     * @param $format_string
174
-     * @return bool|string
175
-     */
176
-    public function format($format_string)
177
-    {
178
-        return date($format_string, strtotime($this->schedule));
179
-    }
180
-
181
-    //--------------------------------------------------------------------
182
-
183
-    /**
184
-     * Gets the associated task.
185
-     *
186
-     * return callable|string
187
-     */
188
-    public function task()
189
-    {
190
-        return $this->task;
191
-    }
192
-
193
-    //--------------------------------------------------------------------
194
-
195
-    /**
196
-     * Gets the original schedule string.
197
-     */
198
-    public function schedule()
199
-    {
200
-        return $this->schedule;
201
-    }
202
-
203
-    //--------------------------------------------------------------------
204
-
205
-    /**
206
-     * Checks the schedule text and determines how we have to treat
207
-     * the schedule when determining next and previous values.
208
-     *
209
-     * Potential Types are:
210
-     *
211
-     *  - increment         Can simply add a +x/-x to the front to get the value.
212
-     *  - time              Something like "every 5 minutes"
213
-     *  - ordinal           Like "first", "second", etc.
214
-     *
215
-     * @param $schedule
216
-     * @return null|string
217
-     */
218
-    public function determineScheduleType($schedule)
219
-    {
220
-        $incs = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sun', 'mon', 'tue',
221
-                'wed', 'thu', 'fri', 'sat', 'weekday', 'weekdays', 'midnight', 'noon'];
222
-        $bigger_incs = [ 'back of', 'front of', 'first day of', 'last day of'];
223
-        $ordinals = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'];
224
-        $schedule = trim( strtolower($schedule) );
225
-
226
-        $multiple_words = strpos($schedule, ' ');
227
-        $first_word = substr($schedule, 0, $multiple_words ? $multiple_words : strlen($schedule));
228
-
229
-        // Is the first character a number? Then it's a time
230
-        if ( is_numeric( $first_word ) )
231
-        {
232
-            return 'time';
233
-        }
234
-
235
-
236
-        // First, try the shorter increments. We do increments in
237
-        // two passes becuase this should be faster than the loop.
238
-        if (in_array($first_word, $incs))
239
-        {
240
-            return 'increment';
241
-        }
242
-
243
-        // But we have to loop before checking ordinals since
244
-        // ordinals may have same first word as these phrases.
245
-        foreach ($bigger_incs as $test)
246
-        {
247
-            if (strpos($schedule, $test) === 0)
248
-            {
249
-                return 'increment';
250
-            }
251
-        }
252
-
253
-        if (in_array($first_word, $ordinals))
254
-        {
255
-            return 'ordinal';
256
-        }
257
-
258
-        return null;
259
-    }
260
-
261
-    //--------------------------------------------------------------------
262
-
263
-    /**
264
-     * Determines the correct time for 'time' type intervals where
265
-     * the timestamp is expected to happen every 'x period', like
266
-     * 'every 5 minutes', every 3 days, etc.
267
-     *
268
-     * @param $schedule
269
-     * @param $type
270
-     * @return float|int|null
271
-     */
272
-    public function findDateInterval($schedule, $type, $current_time='now')
273
-    {
274
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
167
+	//--------------------------------------------------------------------
168
+
169
+	/**
170
+	 * Formats the timestamp produced by nextRunDate and previousRunDate
171
+	 * into any format available to date.
172
+	 *
173
+	 * @param $format_string
174
+	 * @return bool|string
175
+	 */
176
+	public function format($format_string)
177
+	{
178
+		return date($format_string, strtotime($this->schedule));
179
+	}
180
+
181
+	//--------------------------------------------------------------------
182
+
183
+	/**
184
+	 * Gets the associated task.
185
+	 *
186
+	 * return callable|string
187
+	 */
188
+	public function task()
189
+	{
190
+		return $this->task;
191
+	}
192
+
193
+	//--------------------------------------------------------------------
194
+
195
+	/**
196
+	 * Gets the original schedule string.
197
+	 */
198
+	public function schedule()
199
+	{
200
+		return $this->schedule;
201
+	}
202
+
203
+	//--------------------------------------------------------------------
204
+
205
+	/**
206
+	 * Checks the schedule text and determines how we have to treat
207
+	 * the schedule when determining next and previous values.
208
+	 *
209
+	 * Potential Types are:
210
+	 *
211
+	 *  - increment         Can simply add a +x/-x to the front to get the value.
212
+	 *  - time              Something like "every 5 minutes"
213
+	 *  - ordinal           Like "first", "second", etc.
214
+	 *
215
+	 * @param $schedule
216
+	 * @return null|string
217
+	 */
218
+	public function determineScheduleType($schedule)
219
+	{
220
+		$incs = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sun', 'mon', 'tue',
221
+				'wed', 'thu', 'fri', 'sat', 'weekday', 'weekdays', 'midnight', 'noon'];
222
+		$bigger_incs = [ 'back of', 'front of', 'first day of', 'last day of'];
223
+		$ordinals = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'];
224
+		$schedule = trim( strtolower($schedule) );
225
+
226
+		$multiple_words = strpos($schedule, ' ');
227
+		$first_word = substr($schedule, 0, $multiple_words ? $multiple_words : strlen($schedule));
228
+
229
+		// Is the first character a number? Then it's a time
230
+		if ( is_numeric( $first_word ) )
231
+		{
232
+			return 'time';
233
+		}
234
+
235
+
236
+		// First, try the shorter increments. We do increments in
237
+		// two passes becuase this should be faster than the loop.
238
+		if (in_array($first_word, $incs))
239
+		{
240
+			return 'increment';
241
+		}
242
+
243
+		// But we have to loop before checking ordinals since
244
+		// ordinals may have same first word as these phrases.
245
+		foreach ($bigger_incs as $test)
246
+		{
247
+			if (strpos($schedule, $test) === 0)
248
+			{
249
+				return 'increment';
250
+			}
251
+		}
252
+
253
+		if (in_array($first_word, $ordinals))
254
+		{
255
+			return 'ordinal';
256
+		}
257
+
258
+		return null;
259
+	}
260
+
261
+	//--------------------------------------------------------------------
262
+
263
+	/**
264
+	 * Determines the correct time for 'time' type intervals where
265
+	 * the timestamp is expected to happen every 'x period', like
266
+	 * 'every 5 minutes', every 3 days, etc.
267
+	 *
268
+	 * @param $schedule
269
+	 * @param $type
270
+	 * @return float|int|null
271
+	 */
272
+	public function findDateInterval($schedule, $type, $current_time='now')
273
+	{
274
+		$current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
275 275
 
276 276
 //        list($int, $period) = explode(' ', $schedule);
277 277
 
278
-        $diff = strtotime($schedule, $current_time) - $current_time;
279
-
280
-        $return = null;
281
-
282
-        switch ($type)
283
-        {
284
-            case 'next':
285
-                $next = floor($current_time / $diff) * $diff;
286
-
287
-                // Does next already match the current time?
288
-                if (date('Y-m-d H:i', $next) == date('Y-m-d H:i', $current_time))
289
-                {
290
-                    $return = $next;
291
-                }
292
-                else {
293
-                    $return = $next + $diff;
294
-                }
295
-                break;
296
-            case 'prev':
297
-                $next = ceil($current_time / $diff) * $diff;
298
-                $return = $next - $diff;
299
-                break;
300
-        }
301
-
302
-        if (is_numeric($return))
303
-        {
304
-            $return = (int)$return;
305
-        }
306
-
307
-        return $return;
308
-    }
309
-
310
-    //--------------------------------------------------------------------
311
-
312
-    /**
313
-     * Determines the timestamp of the previous ordinal-based time, like
314
-     * 'second Monday'.
315
-     *
316
-     * @param $schedule
317
-     * @param string $current_time
318
-     * @return int|null
319
-     */
320
-    public function findPreviousOrdinal($schedule, $current_time='now')
321
-    {
322
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
323
-
324
-        if (empty($schedule)) return null;
325
-
326
-        // Loop through months in reverse, checking each one to
327
-        // see if the ordinal is in the past. If so - wer'e done.
328
-        foreach ([0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12] as $i)
329
-        {
330
-            $lastmonth = strtotime("last day of {$i} month", $current_time);
331
-
332
-            $test = strtotime($schedule, $lastmonth);
333
-
334
-            if ($test <= $current_time)
335
-            {
336
-                return $test;
337
-            }
338
-        }
339
-
340
-        return null;
341
-    }
342
-
343
-    //--------------------------------------------------------------------
278
+		$diff = strtotime($schedule, $current_time) - $current_time;
279
+
280
+		$return = null;
281
+
282
+		switch ($type)
283
+		{
284
+			case 'next':
285
+				$next = floor($current_time / $diff) * $diff;
286
+
287
+				// Does next already match the current time?
288
+				if (date('Y-m-d H:i', $next) == date('Y-m-d H:i', $current_time))
289
+				{
290
+					$return = $next;
291
+				}
292
+				else {
293
+					$return = $next + $diff;
294
+				}
295
+				break;
296
+			case 'prev':
297
+				$next = ceil($current_time / $diff) * $diff;
298
+				$return = $next - $diff;
299
+				break;
300
+		}
301
+
302
+		if (is_numeric($return))
303
+		{
304
+			$return = (int)$return;
305
+		}
306
+
307
+		return $return;
308
+	}
309
+
310
+	//--------------------------------------------------------------------
311
+
312
+	/**
313
+	 * Determines the timestamp of the previous ordinal-based time, like
314
+	 * 'second Monday'.
315
+	 *
316
+	 * @param $schedule
317
+	 * @param string $current_time
318
+	 * @return int|null
319
+	 */
320
+	public function findPreviousOrdinal($schedule, $current_time='now')
321
+	{
322
+		$current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
323
+
324
+		if (empty($schedule)) return null;
325
+
326
+		// Loop through months in reverse, checking each one to
327
+		// see if the ordinal is in the past. If so - wer'e done.
328
+		foreach ([0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12] as $i)
329
+		{
330
+			$lastmonth = strtotime("last day of {$i} month", $current_time);
331
+
332
+			$test = strtotime($schedule, $lastmonth);
333
+
334
+			if ($test <= $current_time)
335
+			{
336
+				return $test;
337
+			}
338
+		}
339
+
340
+		return null;
341
+	}
342
+
343
+	//--------------------------------------------------------------------
344 344
 
345 345
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -75,9 +75,9 @@  discard block
 block discarded – undo
75 75
 
76 76
         // If $task is not callable, it should be a library:method
77 77
         // string that we can parse. But it must have the colon in the string.
78
-        if (! is_callable($task) && strpos($task, ':') === false)
78
+        if ( ! is_callable($task) && strpos($task, ':') === false)
79 79
         {
80
-            throw new \RuntimeException( lang('cron.invalid_task') );
80
+            throw new \RuntimeException(lang('cron.invalid_task'));
81 81
         }
82 82
 
83 83
         $this->task = $task;
@@ -92,9 +92,9 @@  discard block
 block discarded – undo
92 92
      *
93 93
      * @return timestamp|null
94 94
      */
95
-    public function nextRunDate($current_time='now')
95
+    public function nextRunDate($current_time = 'now')
96 96
     {
97
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
97
+        $current_time = is_numeric($current_time) ? (int) $current_time : strtotime($current_time);
98 98
 
99 99
         $scheduleType = $this->determineScheduleType($this->schedule);
100 100
 
@@ -123,9 +123,9 @@  discard block
 block discarded – undo
123 123
      *
124 124
      * @return timestamp|null
125 125
      */
126
-    public function previousRunDate($current_time='now')
126
+    public function previousRunDate($current_time = 'now')
127 127
     {
128
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
128
+        $current_time = is_numeric($current_time) ? (int) $current_time : strtotime($current_time);
129 129
 
130 130
         $scheduleType = $this->determineScheduleType($this->schedule);
131 131
 
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
                 return $this->findPreviousOrdinal($this->schedule, $current_time);
139 139
                 break;
140 140
             case 'increment':
141
-                return strtotime('-1 '. $this->schedule, $current_time);
141
+                return strtotime('-1 '.$this->schedule, $current_time);
142 142
                 break;
143 143
         }
144 144
 
@@ -155,13 +155,13 @@  discard block
 block discarded – undo
155 155
      *
156 156
      * @return bool
157 157
      */
158
-    public function isDue($current_time='now')
158
+    public function isDue($current_time = 'now')
159 159
     {
160
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
160
+        $current_time = is_numeric($current_time) ? (int) $current_time : strtotime($current_time);
161 161
 
162 162
         // For easier matching, and I can't imagine people needing cronjob
163 163
         // accuracy to the seconds, we'll just take the current minute.
164
-        return date('Y-m-d H:i', $current_time) == date('Y-m-d H:i', $this->nextRunDate($current_time) );
164
+        return date('Y-m-d H:i', $current_time) == date('Y-m-d H:i', $this->nextRunDate($current_time));
165 165
     }
166 166
     
167 167
     //--------------------------------------------------------------------
@@ -219,15 +219,15 @@  discard block
 block discarded – undo
219 219
     {
220 220
         $incs = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sun', 'mon', 'tue',
221 221
                 'wed', 'thu', 'fri', 'sat', 'weekday', 'weekdays', 'midnight', 'noon'];
222
-        $bigger_incs = [ 'back of', 'front of', 'first day of', 'last day of'];
222
+        $bigger_incs = ['back of', 'front of', 'first day of', 'last day of'];
223 223
         $ordinals = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'];
224
-        $schedule = trim( strtolower($schedule) );
224
+        $schedule = trim(strtolower($schedule));
225 225
 
226 226
         $multiple_words = strpos($schedule, ' ');
227 227
         $first_word = substr($schedule, 0, $multiple_words ? $multiple_words : strlen($schedule));
228 228
 
229 229
         // Is the first character a number? Then it's a time
230
-        if ( is_numeric( $first_word ) )
230
+        if (is_numeric($first_word))
231 231
         {
232 232
             return 'time';
233 233
         }
@@ -269,9 +269,9 @@  discard block
 block discarded – undo
269 269
      * @param $type
270 270
      * @return float|int|null
271 271
      */
272
-    public function findDateInterval($schedule, $type, $current_time='now')
272
+    public function findDateInterval($schedule, $type, $current_time = 'now')
273 273
     {
274
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
274
+        $current_time = is_numeric($current_time) ? (int) $current_time : strtotime($current_time);
275 275
 
276 276
 //        list($int, $period) = explode(' ', $schedule);
277 277
 
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 
302 302
         if (is_numeric($return))
303 303
         {
304
-            $return = (int)$return;
304
+            $return = (int) $return;
305 305
         }
306 306
 
307 307
         return $return;
@@ -317,9 +317,9 @@  discard block
 block discarded – undo
317 317
      * @param string $current_time
318 318
      * @return int|null
319 319
      */
320
-    public function findPreviousOrdinal($schedule, $current_time='now')
320
+    public function findPreviousOrdinal($schedule, $current_time = 'now')
321 321
     {
322
-        $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
322
+        $current_time = is_numeric($current_time) ? (int) $current_time : strtotime($current_time);
323 323
 
324 324
         if (empty($schedule)) return null;
325 325
 
Please login to merge, or discard this patch.
Braces   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -288,8 +288,7 @@  discard block
 block discarded – undo
288 288
                 if (date('Y-m-d H:i', $next) == date('Y-m-d H:i', $current_time))
289 289
                 {
290 290
                     $return = $next;
291
-                }
292
-                else {
291
+                } else {
293 292
                     $return = $next + $diff;
294 293
                 }
295 294
                 break;
@@ -321,7 +320,9 @@  discard block
 block discarded – undo
321 320
     {
322 321
         $current_time = is_numeric($current_time) ? (int)$current_time : strtotime($current_time);
323 322
 
324
-        if (empty($schedule)) return null;
323
+        if (empty($schedule)) {
324
+        	return null;
325
+        }
325 326
 
326 327
         // Loop through months in reverse, checking each one to
327 328
         // see if the ordinal is in the past. If so - wer'e done.
Please login to merge, or discard this patch.
myth/Docs/Builder.php 4 patches
Doc Comments   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      * Parses the contents. Currently runs through the Markdown Extended
132 132
      * parser to convert to HTML.
133 133
      *
134
-     * @param $str
134
+     * @param string|null $str
135 135
      * @return mixed
136 136
      */
137 137
     public function parse($str)
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
      * Analyzes the passed in current url string and checks against
496 496
      * a list of groups to determine what the current group is.
497 497
      *
498
-     * @param $current_url
498
+     * @param string $current_url
499 499
      * @param $groups
500 500
      * @return string
501 501
      */
@@ -576,8 +576,8 @@  discard block
 block discarded – undo
576 576
      * Re-formats the passed in link.
577 577
      *
578 578
      * @param $link
579
-     * @param $current_url
580
-     * @param $site_url
579
+     * @param string $current_url
580
+     * @param string $site_url
581 581
      * @return mixed
582 582
      */
583 583
     private function reformatAnchor($link, $groups, $current_url, $site_url)
@@ -659,8 +659,8 @@  discard block
 block discarded – undo
659 659
      * Also adds named anchors into the $content so the map
660 660
      * can link to the content properly.
661 661
      *
662
-     * @param $content
663
-     * @param $xml
662
+     * @param string $content
663
+     * @param \SimpleXMLElement $xml
664 664
      * @param $map
665 665
      * @return array
666 666
      */
Please login to merge, or discard this patch.
Indentation   +718 added lines, -718 removed lines patch added patch discarded remove patch
@@ -60,725 +60,725 @@
 block discarded – undo
60 60
 class Builder implements DocBuilderInterface
61 61
 {
62 62
 
63
-    protected $docs_ext = '.md';
64
-
65
-    protected $ignore_files = ['_404.md'];
66
-
67
-    protected $doc_folders = [];
68
-
69
-    /**
70
-     * Stores the current folder alias,
71
-     * once the file has been found.
72
-     *
73
-     * @var null
74
-     */
75
-    protected $current_folder = null;
76
-
77
-    protected $table_classes = 'table table-hover';
78
-
79
-    protected $apppath = '';
80
-
81
-    protected $formatters = [];
82
-
83
-    protected $page_title = null;
84
-
85
-    //--------------------------------------------------------------------
86
-
87
-    public function __construct($config = array())
88
-    {
89
-        $this->apppath = ! empty($config['apppath']) ? rtrim($config['apppath'], '/') . '/' : '';
90
-    }
91
-
92
-    //--------------------------------------------------------------------
93
-
94
-    public function pageTitle()
95
-    {
96
-        return $this->page_title;
97
-    }
98
-
99
-    //--------------------------------------------------------------------
100
-
101
-
102
-
103
-    /**
104
-     * Does the actual work of reading in and parsing the help file.
105
-     * If a folder Nickname (see addDocFolder() ) is passed as the second parameter,
106
-     * it will limit it's search to that single folder. If nothing is passed, it will
107
-     * search through all of the folders in the order they were given to the library,
108
-     * until it finds the first one.
109
-     *
110
-     * @param string $path The 'path' of the file (relative to the docs
111
-     *                                 folder. Usually from the URI)
112
-     * @param string $restrictToFolder (Optional) The folder nickname
113
-     *
114
-     * @return string
115
-     */
116
-    public function readPage($path, $restrictToFolder = null)
117
-    {
118
-        // Clean up our path
119
-        $path = trim($path, '/ ');
120
-
121
-        $content = $this->locateAndReadFile($path, $restrictToFolder);
122
-
123
-        $content = $this->parse($content);
124
-
125
-        return $content;
126
-    }
127
-
128
-    //--------------------------------------------------------------------
129
-
130
-    /**
131
-     * Parses the contents. Currently runs through the Markdown Extended
132
-     * parser to convert to HTML.
133
-     *
134
-     * @param $str
135
-     * @return mixed
136
-     */
137
-    public function parse($str)
138
-    {
139
-        return $this->format($str);
140
-    }
141
-
142
-    //--------------------------------------------------------------------
143
-
144
-    /**
145
-     * Perform a few housekeeping tasks on a page, like rewriting URLs to full
146
-     * URLs, not relative, ensuring they link correctly, etc.
147
-     *
148
-     * @param      $content
149
-     * @param null $site_url
150
-     * @param null $current_url
151
-     * @return string   The post-processed HTML.
152
-     */
153
-    public function postProcess($content, $site_url = null, $current_url = null)
154
-    {
155
-        if (empty($content)) {
156
-            return $content;
157
-        }
158
-
159
-        try {
160
-            $xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>' . $content . '</div>');
161
-        } catch (\Exception $e) {
162
-            // SimpleXML barfed on us, so send back the un-modified content
163
-            return $content;
164
-        }
165
-
166
-        // Prepare some things and cleanup others
167
-        $groups = array_keys($this->doc_folders);
168
-        $site_url = rtrim($site_url, '/') . '/';
169
-        $current_url = rtrim($current_url, '#/');
170
-
171
-        // Try to determine the current_url if one isn't set.
172
-        if (empty($this->current_folder)) {
173
-            $this->current_folder = $this->detectCurrentFolder($current_url, $groups);
174
-        }
175
-
176
-        /*
63
+	protected $docs_ext = '.md';
64
+
65
+	protected $ignore_files = ['_404.md'];
66
+
67
+	protected $doc_folders = [];
68
+
69
+	/**
70
+	 * Stores the current folder alias,
71
+	 * once the file has been found.
72
+	 *
73
+	 * @var null
74
+	 */
75
+	protected $current_folder = null;
76
+
77
+	protected $table_classes = 'table table-hover';
78
+
79
+	protected $apppath = '';
80
+
81
+	protected $formatters = [];
82
+
83
+	protected $page_title = null;
84
+
85
+	//--------------------------------------------------------------------
86
+
87
+	public function __construct($config = array())
88
+	{
89
+		$this->apppath = ! empty($config['apppath']) ? rtrim($config['apppath'], '/') . '/' : '';
90
+	}
91
+
92
+	//--------------------------------------------------------------------
93
+
94
+	public function pageTitle()
95
+	{
96
+		return $this->page_title;
97
+	}
98
+
99
+	//--------------------------------------------------------------------
100
+
101
+
102
+
103
+	/**
104
+	 * Does the actual work of reading in and parsing the help file.
105
+	 * If a folder Nickname (see addDocFolder() ) is passed as the second parameter,
106
+	 * it will limit it's search to that single folder. If nothing is passed, it will
107
+	 * search through all of the folders in the order they were given to the library,
108
+	 * until it finds the first one.
109
+	 *
110
+	 * @param string $path The 'path' of the file (relative to the docs
111
+	 *                                 folder. Usually from the URI)
112
+	 * @param string $restrictToFolder (Optional) The folder nickname
113
+	 *
114
+	 * @return string
115
+	 */
116
+	public function readPage($path, $restrictToFolder = null)
117
+	{
118
+		// Clean up our path
119
+		$path = trim($path, '/ ');
120
+
121
+		$content = $this->locateAndReadFile($path, $restrictToFolder);
122
+
123
+		$content = $this->parse($content);
124
+
125
+		return $content;
126
+	}
127
+
128
+	//--------------------------------------------------------------------
129
+
130
+	/**
131
+	 * Parses the contents. Currently runs through the Markdown Extended
132
+	 * parser to convert to HTML.
133
+	 *
134
+	 * @param $str
135
+	 * @return mixed
136
+	 */
137
+	public function parse($str)
138
+	{
139
+		return $this->format($str);
140
+	}
141
+
142
+	//--------------------------------------------------------------------
143
+
144
+	/**
145
+	 * Perform a few housekeeping tasks on a page, like rewriting URLs to full
146
+	 * URLs, not relative, ensuring they link correctly, etc.
147
+	 *
148
+	 * @param      $content
149
+	 * @param null $site_url
150
+	 * @param null $current_url
151
+	 * @return string   The post-processed HTML.
152
+	 */
153
+	public function postProcess($content, $site_url = null, $current_url = null)
154
+	{
155
+		if (empty($content)) {
156
+			return $content;
157
+		}
158
+
159
+		try {
160
+			$xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>' . $content . '</div>');
161
+		} catch (\Exception $e) {
162
+			// SimpleXML barfed on us, so send back the un-modified content
163
+			return $content;
164
+		}
165
+
166
+		// Prepare some things and cleanup others
167
+		$groups = array_keys($this->doc_folders);
168
+		$site_url = rtrim($site_url, '/') . '/';
169
+		$current_url = rtrim($current_url, '#/');
170
+
171
+		// Try to determine the current_url if one isn't set.
172
+		if (empty($this->current_folder)) {
173
+			$this->current_folder = $this->detectCurrentFolder($current_url, $groups);
174
+		}
175
+
176
+		/*
177 177
          * Rewrite the URLs
178 178
          */
179
-        foreach ($xml->xpath('//a') as $link) {
180
-            $link = $this->reformatAnchor($link, $groups, $current_url, $site_url);
181
-        }
182
-
183
-        $content = $xml->asXML();
184
-        $content = trim(str_replace('<?xml version="1.0" standalone="yes"?>', '', $content));
185
-
186
-        // Clean up and style the tables
187
-        $content = str_replace('<table>', '<table class="' . $this->table_classes . '">', $content);
188
-
189
-        return $content;
190
-    }
191
-    //--------------------------------------------------------------------
192
-
193
-    /**
194
-     * Allows users to define the classes that are attached to
195
-     * generated tables.
196
-     *
197
-     * @param null $classes
198
-     * @return $this
199
-     */
200
-    public function setTableClasses($classes = null)
201
-    {
202
-        $this->table_classes = $classes;
203
-
204
-        return $this;
205
-    }
206
-
207
-    //--------------------------------------------------------------------
208
-
209
-    /**
210
-     * Given the contents to render, will build a list of links for the sidebar
211
-     * out of the headings in the file.
212
-     *
213
-     * Note: Will ONLY use h2 and h3 to build the links from.
214
-     *
215
-     * Note: The $content passed in WILL be modified by adding named anchors
216
-     * that match up with the locations.
217
-     *
218
-     * @param string $content The HTML to analyse for headings.
219
-     * @return string
220
-     */
221
-    public function buildDocumentMap(&$content)
222
-    {
223
-        if (empty($content)) {
224
-            return $content;
225
-        }
226
-
227
-        // If $content already has a wrapping <div> and </div> tags, remove them,
228
-        // since we'll replace them just below.
229
-        if (strpos($content, '<div>') === 0) {
230
-            $content = substr($content, 5);
231
-
232
-            // Trailing div also?
233
-            if (substr($content, -6) == '</div>') {
234
-                $content = substr($content, 0, -6);
235
-            }
236
-        }
237
-
238
-        try {
239
-            $xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>' . $content . '</div>');
240
-        } catch (\Exception $e) {
241
-            // SimpleXML barfed on us, so send back the un-modified content
242
-            return [];
243
-        }
244
-
245
-        $map = [];
246
-        list($map, $content) = $this->extractDocMapAndAddAnchors($content, $xml, $map);
247
-
248
-        return $map;
249
-    }
250
-
251
-    //--------------------------------------------------------------------
252
-
253
-    /**
254
-     * Stores the name of the callback method to run to convert the source
255
-     * files to viewable files. By default, this should be used to register
256
-     * a Mardown Extended formatter with the system, but could be used to
257
-     * extend the
258
-     *
259
-     * @param string $callback
260
-     * @param bool $cascade // If FALSE the formatting of a component ends here. If TRUE, will be passed to next formatter.
261
-     * @return $this
262
-     */
263
-    public function registerFormatter($callback = null, $cascade = false)
264
-    {
265
-        if (empty($callback)) return;
266
-
267
-        $this->formatters[] = [
268
-            'callable' => $callback,
269
-            'cascade'  => (bool)$cascade
270
-        ];
271
-
272
-        return $this;
273
-    }
274
-
275
-    //--------------------------------------------------------------------
276
-
277
-    /**
278
-     * Runs the text through the registered formatters.
279
-     *
280
-     * @param $str
281
-     * @return mixed
282
-     */
283
-    public function format($str)
284
-    {
285
-        if (! is_array($this->formatters)) return $str;
286
-
287
-        foreach ($this->formatters as $formatter) {
288
-            $method = $formatter['callable'];
289
-            $cascade = $formatter['cascade'];
290
-
291
-            $str = call_user_func($method, $str);
292
-
293
-            if (! $cascade) return $str;
294
-        }
295
-
296
-        return $str;
297
-    }
298
-
299
-    //--------------------------------------------------------------------
300
-
301
-    //--------------------------------------------------------------------
302
-    // Table of Contents methods
303
-    //--------------------------------------------------------------------
304
-
305
-    /**
306
-     * Retrieves the list of files in a folder and preps the name and filename
307
-     * so it's ready for creating the HTML.
308
-     *
309
-     * @param  String $folder The path to the folder to retrieve.
310
-     *
311
-     * @return Array  An associative array @see parse_ini_file for format
312
-     * details.
313
-     */
314
-    public function buildTOC($folder)
315
-    {
316
-        // If the toc file exists in the folder, use it to build the links.
317
-        if (is_file("{$folder}/_toc.ini")) {
318
-            $toc = parse_ini_file("{$folder}/_toc.ini", true);
319
-            return $this->columnizeTOC($toc);
320
-        }
321
-
322
-        // If the toc file does not exist, build the links by listing the files
323
-        // in the directory (and any sub-directories)
324
-        $map = $this->directory_map($folder);
325
-
326
-        // If directory_map can not open the directory or find any files inside
327
-        // the directory, return an empty array.
328
-        if (empty($map)) {
329
-            return [];
330
-        }
331
-
332
-        // If these docs are located in the /application/docs or /bonfire/docs
333
-        // directory, just use $this->current_group for the root.
334
-        // Module docs need $this->current_group and $type.
335
-        $tocRoot = $this->current_folder;
336
-        if ($this->current_folder != strtolower($folder)) {
337
-            $tocRoot .= '/' . strtolower($folder);
338
-        }
339
-
340
-        $toc = [];
341
-        foreach ($map as $files) {
342
-            // If $files isn't an array, then make it one so that all situations
343
-            // may be dealt with cleanly.
344
-            if (! is_array($files)) {
345
-                $files = [$files];
346
-            }
347
-
348
-            foreach ($files as $file) {
349
-                if (in_array($file, $this->ignore_files)) {
350
-                    continue;
351
-                }
352
-
353
-                // The title for the index is the passed $type. Otherwise,
354
-                // build the title from the file's name.
355
-                if (strpos($file, 'index') === false) {
356
-                    $title = str_replace($this->docs_ext, '', $file);
357
-                    $title = str_replace('_', ' ', $title);
358
-                    $title = ucwords($title);
359
-
360
-                    $toc["{$tocRoot}/{$file}"] = $title;
361
-                } else {
362
-                    $toc[$tocRoot] = $type;
363
-                }
364
-            }
365
-        }
366
-
367
-        $toc = $this->columnizeTOC($toc);
368
-
369
-        return $toc;
370
-    }
371
-
372
-    //--------------------------------------------------------------------
373
-
374
-    /**
375
-     * Sorts the passed TOC array into columns of as close to equal length
376
-     * as we can get it.
377
-     *
378
-     * @param $toc
379
-     * @return array
380
-     */
381
-    protected function columnizeTOC($toc)
382
-    {
383
-        $section_count = count($toc);
384
-
385
-        // First - determine the size of each 'section'.
386
-        $sizes = [];
387
-
388
-        foreach ($toc as $section => $chapters) {
389
-            $sizes[] = count($chapters);
390
-        }
391
-
392
-        $column_avg = (int)round(array_sum($sizes) / $section_count);
393
-
394
-        // Split things into 4 columns of approximately equal size.
395
-        // If we only have 4 columns (or less), then make sure to
396
-        // deal with that also.
397
-        $columns = [];
398
-
399
-        $current_column = 0;
400
-        $current_column_count = 0;
401
-        $keys = array_keys($toc);
402
-
403
-        for ($i = 0; $i <= $section_count; $i++) {
404
-            if (! isset($keys[$i])) {
405
-                continue;
406
-            }
407
-
408
-            $section = array_shift($toc);
409
-
410
-            // Can we stay in this column?
411
-            if ($current_column_count <= $column_avg && $section_count > 4) {
412
-                // Don't forget to account for the heading also.
413
-                $current_column_count += count($section) + 1;
414
-            } else {
415
-                $current_column_count = 0;
416
-                $current_column++;
417
-            }
418
-
419
-            $columns[$current_column][$keys[$i]] = $section;
420
-        }
421
-
422
-        return $columns;
423
-    }
424
-
425
-    //--------------------------------------------------------------------
426
-
427
-    //--------------------------------------------------------------------
428
-    // Folder Methods
429
-    //--------------------------------------------------------------------
430
-
431
-    /**
432
-     * Returns the current docFolders array.
433
-     *
434
-     * @return array
435
-     */
436
-    public function docFolders()
437
-    {
438
-        return $this->doc_folders;
439
-    }
440
-
441
-    //--------------------------------------------------------------------
442
-
443
-    /**
444
-     * Registers a path to be used when searching for documentation files.
445
-     *
446
-     * @param $name     A nickname to reference it by later.
447
-     * @param $path     The server path to the folder.
448
-     * @return $this
449
-     */
450
-    public function addDocFolder($name, $path)
451
-    {
452
-        // Standardize the path
453
-        $path = realpath($path) . '/';
454
-
455
-        // realpath will return FALSE if the path doesn't exist
456
-        // or the script doesn't have access to it.
457
-        if (! $path || $path == '/') {
458
-            return $this;
459
-        }
460
-
461
-        $name = strtolower($name);
462
-
463
-        $this->doc_folders[$name] = $path;
464
-
465
-        return $this;
466
-    }
467
-
468
-    //--------------------------------------------------------------------
469
-
470
-    /**
471
-     * Removes a folder from the folders we scan for documentation files
472
-     * within.
473
-     *
474
-     * @param $name
475
-     * @return $this
476
-     */
477
-    public function removeDocFolder($name)
478
-    {
479
-        $name = strtolower($name);
480
-
481
-        if (isset($this->doc_folders[$name])) {
482
-            unset($this->doc_folders[$name]);
483
-        }
484
-
485
-        return $this;
486
-    }
487
-
488
-    //--------------------------------------------------------------------
489
-
490
-    //--------------------------------------------------------------------
491
-    // Private Methods
492
-    //--------------------------------------------------------------------
493
-
494
-    /**
495
-     * Analyzes the passed in current url string and checks against
496
-     * a list of groups to determine what the current group is.
497
-     *
498
-     * @param $current_url
499
-     * @param $groups
500
-     * @return string
501
-     */
502
-    protected function detectCurrentFolder($current_url, $groups = [])
503
-    {
504
-        if (! is_array($groups)) {
505
-            return null;
506
-        }
507
-
508
-        $segments = explode('/', $current_url);
509
-
510
-        // We start from the back of the array since
511
-        // that's most likely to be close to the end.
512
-        $segments = array_reverse($segments);
513
-
514
-        foreach ($segments as $segment) {
515
-            foreach ($groups as $group) {
516
-                if (strtolower($group) == strtolower($segment)) {
517
-                    return $group;
518
-                }
519
-            }
520
-        }
521
-
522
-        // Nothing found?
523
-        return null;
524
-    }
525
-
526
-    //--------------------------------------------------------------------
527
-
528
-    //--------------------------------------------------------------------
529
-    // Private Methods
530
-    //--------------------------------------------------------------------
531
-
532
-    /**
533
-     * Locates the file on disk and reads the contents into a single string.
534
-     *
535
-     * If a folder Nickname (see addDocFolder() ) is passed as the second parameter,
536
-     * it will limit it's search to that single folder. If nothing is passed, it will
537
-     * search through all of the folders in the order they were given to the library,
538
-     * until it finds the first one.
539
-     *
540
-     * @param string $path The 'path' of the file (relative to the docs
541
-     *                                 folder. Usually from the URI)
542
-     * @param string $restrictToFolder (Optional) The nickname of one of the
543
-     *                                 folders to restrict the search to.
544
-     *
545
-     * @throws RuntimeException
546
-     * @return null|string
547
-     */
548
-    private function locateAndReadFile($path, $restrictToFolder = null)
549
-    {
550
-        $folders = $this->doc_folders;
551
-
552
-        if (! is_null($restrictToFolder)) {
553
-            // Make sure the folder exists
554
-            if (! is_null($restrictToFolder) && ! isset($this->doc_folders[$restrictToFolder])) {
555
-                throw new \RuntimeException('You must add the docs folder that you wish to find docs from.');
556
-            }
557
-
558
-            $folders = [$this->doc_folders[$restrictToFolder]];
559
-        }
560
-
561
-        foreach ($folders as $alias => $folder) {
562
-            if (file_exists($folder . $path . $this->docs_ext)) {
563
-                // Store the alias so we know which folder we're in.
564
-                $this->current_folder = $alias;
565
-
566
-                return file_get_contents($folder . $path . $this->docs_ext);
567
-            }
568
-        }
569
-
570
-        return null;
571
-    }
572
-
573
-    //--------------------------------------------------------------------
574
-
575
-    /**
576
-     * Re-formats the passed in link.
577
-     *
578
-     * @param $link
579
-     * @param $current_url
580
-     * @param $site_url
581
-     * @return mixed
582
-     */
583
-    private function reformatAnchor($link, $groups, $current_url, $site_url)
584
-    {
585
-        // Grab the href value.
586
-        $href = $link->attributes()->href;
587
-
588
-        // If the href is null, it's probably a named anchor with no content.
589
-        if (! $href) {
590
-            // Make sure it has an href, else the XML will not close this
591
-            // tag correctly.
592
-            $link['href'] = ' ';
593
-
594
-            return $link;
595
-        }
596
-
597
-        // Remove any trailing # signs
598
-        $href = rtrim($href, '# ');
599
-
600
-        // If the href starts with #, then attach the current_url to it
601
-        if ($href != '' && substr_compare($href, '#', 0, 1) === 0) {
602
-            $link['href'] = $current_url . $href;
603
-
604
-            return $link;
605
-        }
606
-
607
-        // If it's a full external path, go on...
608
-        if ((strpos($href, 'http://') !== false || strpos($href, 'https://') !== false) &&
609
-            strpos($href, $site_url) === false
610
-        ) {
611
-            $link['target'] = "_blank";
612
-            return $link;
613
-        }
614
-
615
-        // If it's a full local path, get rid of it.
616
-        if (strpos($href, $site_url) !== false) {
617
-            $href = str_replace($site_url, '', $href);
618
-        }
619
-
620
-        // Strip out some unnecessary items, just in case they're there.
621
-        if (substr($href, 0, strlen('docs/')) == 'docs/') {
622
-            $href = substr($href, strlen('docs/'));
623
-        }
624
-
625
-        // This includes 'bonfire/' if it was missed during the conversion.
626
-        if (substr($href, 0, strlen('bonfire/')) == 'bonfire/') {
627
-            $href = substr($href, strlen('bonfire/'));
628
-        }
629
-
630
-        // If another 'group' is not already defined at the head of the link
631
-        // then add the current group to it.
632
-        $group_found = false;
633
-
634
-        foreach ($groups as $group) {
635
-            if (strpos($href, $group) === 0) {
636
-                $group_found = true;
637
-            }
638
-        }
639
-
640
-        if (! $group_found) {
641
-            $href = $this->current_folder . '/' . $href;
642
-        }
643
-
644
-        // Convert to full site_url
645
-        if (strpos($href, 'http') !== 0) {
646
-            $href = $site_url . 'docs/' . ltrim($href, '/ ');
647
-        }
648
-
649
-        // Save the corrected href
650
-        $link['href'] = $href;
651
-
652
-        return $link;
653
-    }
654
-
655
-    //--------------------------------------------------------------------
656
-
657
-    /**
658
-     * Creates a Document Map based on <h2> and <h3> tags.
659
-     * Also adds named anchors into the $content so the map
660
-     * can link to the content properly.
661
-     *
662
-     * @param $content
663
-     * @param $xml
664
-     * @param $map
665
-     * @return array
666
-     */
667
-    protected function extractDocMapAndAddAnchors(&$content, $xml, $map)
668
-    {
669
-        // Holds the current h2 we're processing
670
-        $current_obj = [];
671
-
672
-        $currentChild = 0;
673
-
674
-        foreach ($xml->children() as $childType => $line) {
675
-            $currentChild++;
676
-
677
-            // If it's an h1 - take the first and make it
678
-            // our page title.
679
-            if ($childType == 'h1' && empty($this->page_title))
680
-            {
681
-                $this->page_title = (string)$line;
682
-            }
683
-
684
-            // Make sure that our current object is
685
-            // stored and reset.
686
-            if ($childType == 'h1' || $childType == 'h2') {
687
-                if (count($current_obj)) {
688
-                    $map[] = $current_obj;
689
-                    $current_obj = [];
690
-                }
691
-            }
692
-
693
-            if ($childType == 'h2') {
694
-                $name = (string)$line;
695
-                $link = strtolower(str_replace(' ', '_', (string)$line));
696
-
697
-                $current_obj['name'] = $name;
698
-                $current_obj['link'] = '#' . $link;
699
-                $current_obj['items'] = [];
700
-
701
-                // Insert a named anchor into the $content
702
-                $anchor = '<a name="' . $link . '" id="' . $link . '" ></a>';
703
-
704
-                $search = "<h2>{$name}</h2>";
705
-
706
-                $content = str_replace($search, $anchor . $search, $content);
707
-            } elseif ($childType == 'h3') {
708
-                // Make sure we have some place to store the items.
709
-                if (! isset($current_obj['items'])) {
710
-                    $current_obj['items'] = [];
711
-                }
712
-
713
-                $link = strtolower(str_replace(' ', '_', (string)$line));
714
-                $name = (string)$line;
715
-
716
-                $current_obj['items'][] = [
717
-                    'name' => $name,
718
-                    'link' => '#' . $link
719
-                ];
720
-
721
-                // Insert a named anchor into the $content
722
-                $anchor = '<a name="' . $link . '" id="' . $link . '" ></a>';
723
-
724
-                $search = "<h3>{$name}</h3>";
725
-
726
-                $content = str_replace($search, $anchor . $search, $content);
727
-            }
728
-
729
-            // Is this the last element? Then close out our current object.
730
-            if (count($xml) == $currentChild) {
731
-                if (count($current_obj)) {
732
-                    $map[] = $current_obj;
733
-                }
734
-            }
735
-        }
736
-        return [$map, $content];
737
-    }
738
-    //--------------------------------------------------------------------
739
-
740
-    /**
741
-     * Create a Directory Map
742
-     *
743
-     * Reads the specified directory and builds an array
744
-     * representation of it. Sub-folders contained with the
745
-     * directory will be mapped as well.
746
-     *
747
-     * @param    string $source_dir Path to source
748
-     * @param    int $directory_depth Depth of directories to traverse
749
-     *                        (0 = fully recursive, 1 = current dir, etc)
750
-     * @param    bool $hidden Whether to show hidden files
751
-     * @return    array
752
-     */
753
-    protected function directory_map($source_dir, $directory_depth = 0, $hidden = FALSE)
754
-    {
755
-        if ($fp = @opendir($source_dir)) {
756
-            $filedata = array();
757
-            $new_depth = $directory_depth - 1;
758
-            $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
759
-
760
-            while (FALSE !== ($file = readdir($fp))) {
761
-                // Remove '.', '..', and hidden files [optional]
762
-                if ($file === '.' OR $file === '..' OR ($hidden === FALSE && $file[0] === '.')) {
763
-                    continue;
764
-                }
765
-
766
-                is_dir($source_dir . $file) && $file .= DIRECTORY_SEPARATOR;
767
-
768
-                if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir . $file)) {
769
-                    $filedata[$file] = directory_map($source_dir . $file, $new_depth, $hidden);
770
-                } else {
771
-                    $filedata[] = $file;
772
-                }
773
-            }
774
-
775
-            closedir($fp);
776
-            return $filedata;
777
-        }
778
-
779
-        return FALSE;
780
-    }
781
-
782
-    //--------------------------------------------------------------------
179
+		foreach ($xml->xpath('//a') as $link) {
180
+			$link = $this->reformatAnchor($link, $groups, $current_url, $site_url);
181
+		}
182
+
183
+		$content = $xml->asXML();
184
+		$content = trim(str_replace('<?xml version="1.0" standalone="yes"?>', '', $content));
185
+
186
+		// Clean up and style the tables
187
+		$content = str_replace('<table>', '<table class="' . $this->table_classes . '">', $content);
188
+
189
+		return $content;
190
+	}
191
+	//--------------------------------------------------------------------
192
+
193
+	/**
194
+	 * Allows users to define the classes that are attached to
195
+	 * generated tables.
196
+	 *
197
+	 * @param null $classes
198
+	 * @return $this
199
+	 */
200
+	public function setTableClasses($classes = null)
201
+	{
202
+		$this->table_classes = $classes;
203
+
204
+		return $this;
205
+	}
206
+
207
+	//--------------------------------------------------------------------
208
+
209
+	/**
210
+	 * Given the contents to render, will build a list of links for the sidebar
211
+	 * out of the headings in the file.
212
+	 *
213
+	 * Note: Will ONLY use h2 and h3 to build the links from.
214
+	 *
215
+	 * Note: The $content passed in WILL be modified by adding named anchors
216
+	 * that match up with the locations.
217
+	 *
218
+	 * @param string $content The HTML to analyse for headings.
219
+	 * @return string
220
+	 */
221
+	public function buildDocumentMap(&$content)
222
+	{
223
+		if (empty($content)) {
224
+			return $content;
225
+		}
226
+
227
+		// If $content already has a wrapping <div> and </div> tags, remove them,
228
+		// since we'll replace them just below.
229
+		if (strpos($content, '<div>') === 0) {
230
+			$content = substr($content, 5);
231
+
232
+			// Trailing div also?
233
+			if (substr($content, -6) == '</div>') {
234
+				$content = substr($content, 0, -6);
235
+			}
236
+		}
237
+
238
+		try {
239
+			$xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>' . $content . '</div>');
240
+		} catch (\Exception $e) {
241
+			// SimpleXML barfed on us, so send back the un-modified content
242
+			return [];
243
+		}
244
+
245
+		$map = [];
246
+		list($map, $content) = $this->extractDocMapAndAddAnchors($content, $xml, $map);
247
+
248
+		return $map;
249
+	}
250
+
251
+	//--------------------------------------------------------------------
252
+
253
+	/**
254
+	 * Stores the name of the callback method to run to convert the source
255
+	 * files to viewable files. By default, this should be used to register
256
+	 * a Mardown Extended formatter with the system, but could be used to
257
+	 * extend the
258
+	 *
259
+	 * @param string $callback
260
+	 * @param bool $cascade // If FALSE the formatting of a component ends here. If TRUE, will be passed to next formatter.
261
+	 * @return $this
262
+	 */
263
+	public function registerFormatter($callback = null, $cascade = false)
264
+	{
265
+		if (empty($callback)) return;
266
+
267
+		$this->formatters[] = [
268
+			'callable' => $callback,
269
+			'cascade'  => (bool)$cascade
270
+		];
271
+
272
+		return $this;
273
+	}
274
+
275
+	//--------------------------------------------------------------------
276
+
277
+	/**
278
+	 * Runs the text through the registered formatters.
279
+	 *
280
+	 * @param $str
281
+	 * @return mixed
282
+	 */
283
+	public function format($str)
284
+	{
285
+		if (! is_array($this->formatters)) return $str;
286
+
287
+		foreach ($this->formatters as $formatter) {
288
+			$method = $formatter['callable'];
289
+			$cascade = $formatter['cascade'];
290
+
291
+			$str = call_user_func($method, $str);
292
+
293
+			if (! $cascade) return $str;
294
+		}
295
+
296
+		return $str;
297
+	}
298
+
299
+	//--------------------------------------------------------------------
300
+
301
+	//--------------------------------------------------------------------
302
+	// Table of Contents methods
303
+	//--------------------------------------------------------------------
304
+
305
+	/**
306
+	 * Retrieves the list of files in a folder and preps the name and filename
307
+	 * so it's ready for creating the HTML.
308
+	 *
309
+	 * @param  String $folder The path to the folder to retrieve.
310
+	 *
311
+	 * @return Array  An associative array @see parse_ini_file for format
312
+	 * details.
313
+	 */
314
+	public function buildTOC($folder)
315
+	{
316
+		// If the toc file exists in the folder, use it to build the links.
317
+		if (is_file("{$folder}/_toc.ini")) {
318
+			$toc = parse_ini_file("{$folder}/_toc.ini", true);
319
+			return $this->columnizeTOC($toc);
320
+		}
321
+
322
+		// If the toc file does not exist, build the links by listing the files
323
+		// in the directory (and any sub-directories)
324
+		$map = $this->directory_map($folder);
325
+
326
+		// If directory_map can not open the directory or find any files inside
327
+		// the directory, return an empty array.
328
+		if (empty($map)) {
329
+			return [];
330
+		}
331
+
332
+		// If these docs are located in the /application/docs or /bonfire/docs
333
+		// directory, just use $this->current_group for the root.
334
+		// Module docs need $this->current_group and $type.
335
+		$tocRoot = $this->current_folder;
336
+		if ($this->current_folder != strtolower($folder)) {
337
+			$tocRoot .= '/' . strtolower($folder);
338
+		}
339
+
340
+		$toc = [];
341
+		foreach ($map as $files) {
342
+			// If $files isn't an array, then make it one so that all situations
343
+			// may be dealt with cleanly.
344
+			if (! is_array($files)) {
345
+				$files = [$files];
346
+			}
347
+
348
+			foreach ($files as $file) {
349
+				if (in_array($file, $this->ignore_files)) {
350
+					continue;
351
+				}
352
+
353
+				// The title for the index is the passed $type. Otherwise,
354
+				// build the title from the file's name.
355
+				if (strpos($file, 'index') === false) {
356
+					$title = str_replace($this->docs_ext, '', $file);
357
+					$title = str_replace('_', ' ', $title);
358
+					$title = ucwords($title);
359
+
360
+					$toc["{$tocRoot}/{$file}"] = $title;
361
+				} else {
362
+					$toc[$tocRoot] = $type;
363
+				}
364
+			}
365
+		}
366
+
367
+		$toc = $this->columnizeTOC($toc);
368
+
369
+		return $toc;
370
+	}
371
+
372
+	//--------------------------------------------------------------------
373
+
374
+	/**
375
+	 * Sorts the passed TOC array into columns of as close to equal length
376
+	 * as we can get it.
377
+	 *
378
+	 * @param $toc
379
+	 * @return array
380
+	 */
381
+	protected function columnizeTOC($toc)
382
+	{
383
+		$section_count = count($toc);
384
+
385
+		// First - determine the size of each 'section'.
386
+		$sizes = [];
387
+
388
+		foreach ($toc as $section => $chapters) {
389
+			$sizes[] = count($chapters);
390
+		}
391
+
392
+		$column_avg = (int)round(array_sum($sizes) / $section_count);
393
+
394
+		// Split things into 4 columns of approximately equal size.
395
+		// If we only have 4 columns (or less), then make sure to
396
+		// deal with that also.
397
+		$columns = [];
398
+
399
+		$current_column = 0;
400
+		$current_column_count = 0;
401
+		$keys = array_keys($toc);
402
+
403
+		for ($i = 0; $i <= $section_count; $i++) {
404
+			if (! isset($keys[$i])) {
405
+				continue;
406
+			}
407
+
408
+			$section = array_shift($toc);
409
+
410
+			// Can we stay in this column?
411
+			if ($current_column_count <= $column_avg && $section_count > 4) {
412
+				// Don't forget to account for the heading also.
413
+				$current_column_count += count($section) + 1;
414
+			} else {
415
+				$current_column_count = 0;
416
+				$current_column++;
417
+			}
418
+
419
+			$columns[$current_column][$keys[$i]] = $section;
420
+		}
421
+
422
+		return $columns;
423
+	}
424
+
425
+	//--------------------------------------------------------------------
426
+
427
+	//--------------------------------------------------------------------
428
+	// Folder Methods
429
+	//--------------------------------------------------------------------
430
+
431
+	/**
432
+	 * Returns the current docFolders array.
433
+	 *
434
+	 * @return array
435
+	 */
436
+	public function docFolders()
437
+	{
438
+		return $this->doc_folders;
439
+	}
440
+
441
+	//--------------------------------------------------------------------
442
+
443
+	/**
444
+	 * Registers a path to be used when searching for documentation files.
445
+	 *
446
+	 * @param $name     A nickname to reference it by later.
447
+	 * @param $path     The server path to the folder.
448
+	 * @return $this
449
+	 */
450
+	public function addDocFolder($name, $path)
451
+	{
452
+		// Standardize the path
453
+		$path = realpath($path) . '/';
454
+
455
+		// realpath will return FALSE if the path doesn't exist
456
+		// or the script doesn't have access to it.
457
+		if (! $path || $path == '/') {
458
+			return $this;
459
+		}
460
+
461
+		$name = strtolower($name);
462
+
463
+		$this->doc_folders[$name] = $path;
464
+
465
+		return $this;
466
+	}
467
+
468
+	//--------------------------------------------------------------------
469
+
470
+	/**
471
+	 * Removes a folder from the folders we scan for documentation files
472
+	 * within.
473
+	 *
474
+	 * @param $name
475
+	 * @return $this
476
+	 */
477
+	public function removeDocFolder($name)
478
+	{
479
+		$name = strtolower($name);
480
+
481
+		if (isset($this->doc_folders[$name])) {
482
+			unset($this->doc_folders[$name]);
483
+		}
484
+
485
+		return $this;
486
+	}
487
+
488
+	//--------------------------------------------------------------------
489
+
490
+	//--------------------------------------------------------------------
491
+	// Private Methods
492
+	//--------------------------------------------------------------------
493
+
494
+	/**
495
+	 * Analyzes the passed in current url string and checks against
496
+	 * a list of groups to determine what the current group is.
497
+	 *
498
+	 * @param $current_url
499
+	 * @param $groups
500
+	 * @return string
501
+	 */
502
+	protected function detectCurrentFolder($current_url, $groups = [])
503
+	{
504
+		if (! is_array($groups)) {
505
+			return null;
506
+		}
507
+
508
+		$segments = explode('/', $current_url);
509
+
510
+		// We start from the back of the array since
511
+		// that's most likely to be close to the end.
512
+		$segments = array_reverse($segments);
513
+
514
+		foreach ($segments as $segment) {
515
+			foreach ($groups as $group) {
516
+				if (strtolower($group) == strtolower($segment)) {
517
+					return $group;
518
+				}
519
+			}
520
+		}
521
+
522
+		// Nothing found?
523
+		return null;
524
+	}
525
+
526
+	//--------------------------------------------------------------------
527
+
528
+	//--------------------------------------------------------------------
529
+	// Private Methods
530
+	//--------------------------------------------------------------------
531
+
532
+	/**
533
+	 * Locates the file on disk and reads the contents into a single string.
534
+	 *
535
+	 * If a folder Nickname (see addDocFolder() ) is passed as the second parameter,
536
+	 * it will limit it's search to that single folder. If nothing is passed, it will
537
+	 * search through all of the folders in the order they were given to the library,
538
+	 * until it finds the first one.
539
+	 *
540
+	 * @param string $path The 'path' of the file (relative to the docs
541
+	 *                                 folder. Usually from the URI)
542
+	 * @param string $restrictToFolder (Optional) The nickname of one of the
543
+	 *                                 folders to restrict the search to.
544
+	 *
545
+	 * @throws RuntimeException
546
+	 * @return null|string
547
+	 */
548
+	private function locateAndReadFile($path, $restrictToFolder = null)
549
+	{
550
+		$folders = $this->doc_folders;
551
+
552
+		if (! is_null($restrictToFolder)) {
553
+			// Make sure the folder exists
554
+			if (! is_null($restrictToFolder) && ! isset($this->doc_folders[$restrictToFolder])) {
555
+				throw new \RuntimeException('You must add the docs folder that you wish to find docs from.');
556
+			}
557
+
558
+			$folders = [$this->doc_folders[$restrictToFolder]];
559
+		}
560
+
561
+		foreach ($folders as $alias => $folder) {
562
+			if (file_exists($folder . $path . $this->docs_ext)) {
563
+				// Store the alias so we know which folder we're in.
564
+				$this->current_folder = $alias;
565
+
566
+				return file_get_contents($folder . $path . $this->docs_ext);
567
+			}
568
+		}
569
+
570
+		return null;
571
+	}
572
+
573
+	//--------------------------------------------------------------------
574
+
575
+	/**
576
+	 * Re-formats the passed in link.
577
+	 *
578
+	 * @param $link
579
+	 * @param $current_url
580
+	 * @param $site_url
581
+	 * @return mixed
582
+	 */
583
+	private function reformatAnchor($link, $groups, $current_url, $site_url)
584
+	{
585
+		// Grab the href value.
586
+		$href = $link->attributes()->href;
587
+
588
+		// If the href is null, it's probably a named anchor with no content.
589
+		if (! $href) {
590
+			// Make sure it has an href, else the XML will not close this
591
+			// tag correctly.
592
+			$link['href'] = ' ';
593
+
594
+			return $link;
595
+		}
596
+
597
+		// Remove any trailing # signs
598
+		$href = rtrim($href, '# ');
599
+
600
+		// If the href starts with #, then attach the current_url to it
601
+		if ($href != '' && substr_compare($href, '#', 0, 1) === 0) {
602
+			$link['href'] = $current_url . $href;
603
+
604
+			return $link;
605
+		}
606
+
607
+		// If it's a full external path, go on...
608
+		if ((strpos($href, 'http://') !== false || strpos($href, 'https://') !== false) &&
609
+			strpos($href, $site_url) === false
610
+		) {
611
+			$link['target'] = "_blank";
612
+			return $link;
613
+		}
614
+
615
+		// If it's a full local path, get rid of it.
616
+		if (strpos($href, $site_url) !== false) {
617
+			$href = str_replace($site_url, '', $href);
618
+		}
619
+
620
+		// Strip out some unnecessary items, just in case they're there.
621
+		if (substr($href, 0, strlen('docs/')) == 'docs/') {
622
+			$href = substr($href, strlen('docs/'));
623
+		}
624
+
625
+		// This includes 'bonfire/' if it was missed during the conversion.
626
+		if (substr($href, 0, strlen('bonfire/')) == 'bonfire/') {
627
+			$href = substr($href, strlen('bonfire/'));
628
+		}
629
+
630
+		// If another 'group' is not already defined at the head of the link
631
+		// then add the current group to it.
632
+		$group_found = false;
633
+
634
+		foreach ($groups as $group) {
635
+			if (strpos($href, $group) === 0) {
636
+				$group_found = true;
637
+			}
638
+		}
639
+
640
+		if (! $group_found) {
641
+			$href = $this->current_folder . '/' . $href;
642
+		}
643
+
644
+		// Convert to full site_url
645
+		if (strpos($href, 'http') !== 0) {
646
+			$href = $site_url . 'docs/' . ltrim($href, '/ ');
647
+		}
648
+
649
+		// Save the corrected href
650
+		$link['href'] = $href;
651
+
652
+		return $link;
653
+	}
654
+
655
+	//--------------------------------------------------------------------
656
+
657
+	/**
658
+	 * Creates a Document Map based on <h2> and <h3> tags.
659
+	 * Also adds named anchors into the $content so the map
660
+	 * can link to the content properly.
661
+	 *
662
+	 * @param $content
663
+	 * @param $xml
664
+	 * @param $map
665
+	 * @return array
666
+	 */
667
+	protected function extractDocMapAndAddAnchors(&$content, $xml, $map)
668
+	{
669
+		// Holds the current h2 we're processing
670
+		$current_obj = [];
671
+
672
+		$currentChild = 0;
673
+
674
+		foreach ($xml->children() as $childType => $line) {
675
+			$currentChild++;
676
+
677
+			// If it's an h1 - take the first and make it
678
+			// our page title.
679
+			if ($childType == 'h1' && empty($this->page_title))
680
+			{
681
+				$this->page_title = (string)$line;
682
+			}
683
+
684
+			// Make sure that our current object is
685
+			// stored and reset.
686
+			if ($childType == 'h1' || $childType == 'h2') {
687
+				if (count($current_obj)) {
688
+					$map[] = $current_obj;
689
+					$current_obj = [];
690
+				}
691
+			}
692
+
693
+			if ($childType == 'h2') {
694
+				$name = (string)$line;
695
+				$link = strtolower(str_replace(' ', '_', (string)$line));
696
+
697
+				$current_obj['name'] = $name;
698
+				$current_obj['link'] = '#' . $link;
699
+				$current_obj['items'] = [];
700
+
701
+				// Insert a named anchor into the $content
702
+				$anchor = '<a name="' . $link . '" id="' . $link . '" ></a>';
703
+
704
+				$search = "<h2>{$name}</h2>";
705
+
706
+				$content = str_replace($search, $anchor . $search, $content);
707
+			} elseif ($childType == 'h3') {
708
+				// Make sure we have some place to store the items.
709
+				if (! isset($current_obj['items'])) {
710
+					$current_obj['items'] = [];
711
+				}
712
+
713
+				$link = strtolower(str_replace(' ', '_', (string)$line));
714
+				$name = (string)$line;
715
+
716
+				$current_obj['items'][] = [
717
+					'name' => $name,
718
+					'link' => '#' . $link
719
+				];
720
+
721
+				// Insert a named anchor into the $content
722
+				$anchor = '<a name="' . $link . '" id="' . $link . '" ></a>';
723
+
724
+				$search = "<h3>{$name}</h3>";
725
+
726
+				$content = str_replace($search, $anchor . $search, $content);
727
+			}
728
+
729
+			// Is this the last element? Then close out our current object.
730
+			if (count($xml) == $currentChild) {
731
+				if (count($current_obj)) {
732
+					$map[] = $current_obj;
733
+				}
734
+			}
735
+		}
736
+		return [$map, $content];
737
+	}
738
+	//--------------------------------------------------------------------
739
+
740
+	/**
741
+	 * Create a Directory Map
742
+	 *
743
+	 * Reads the specified directory and builds an array
744
+	 * representation of it. Sub-folders contained with the
745
+	 * directory will be mapped as well.
746
+	 *
747
+	 * @param    string $source_dir Path to source
748
+	 * @param    int $directory_depth Depth of directories to traverse
749
+	 *                        (0 = fully recursive, 1 = current dir, etc)
750
+	 * @param    bool $hidden Whether to show hidden files
751
+	 * @return    array
752
+	 */
753
+	protected function directory_map($source_dir, $directory_depth = 0, $hidden = FALSE)
754
+	{
755
+		if ($fp = @opendir($source_dir)) {
756
+			$filedata = array();
757
+			$new_depth = $directory_depth - 1;
758
+			$source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
759
+
760
+			while (FALSE !== ($file = readdir($fp))) {
761
+				// Remove '.', '..', and hidden files [optional]
762
+				if ($file === '.' OR $file === '..' OR ($hidden === FALSE && $file[0] === '.')) {
763
+					continue;
764
+				}
765
+
766
+				is_dir($source_dir . $file) && $file .= DIRECTORY_SEPARATOR;
767
+
768
+				if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir . $file)) {
769
+					$filedata[$file] = directory_map($source_dir . $file, $new_depth, $hidden);
770
+				} else {
771
+					$filedata[] = $file;
772
+				}
773
+			}
774
+
775
+			closedir($fp);
776
+			return $filedata;
777
+		}
778
+
779
+		return FALSE;
780
+	}
781
+
782
+	//--------------------------------------------------------------------
783 783
 
784 784
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 
87 87
     public function __construct($config = array())
88 88
     {
89
-        $this->apppath = ! empty($config['apppath']) ? rtrim($config['apppath'], '/') . '/' : '';
89
+        $this->apppath = ! empty($config['apppath']) ? rtrim($config['apppath'], '/').'/' : '';
90 90
     }
91 91
 
92 92
     //--------------------------------------------------------------------
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
         }
158 158
 
159 159
         try {
160
-            $xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>' . $content . '</div>');
160
+            $xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>'.$content.'</div>');
161 161
         } catch (\Exception $e) {
162 162
             // SimpleXML barfed on us, so send back the un-modified content
163 163
             return $content;
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 
166 166
         // Prepare some things and cleanup others
167 167
         $groups = array_keys($this->doc_folders);
168
-        $site_url = rtrim($site_url, '/') . '/';
168
+        $site_url = rtrim($site_url, '/').'/';
169 169
         $current_url = rtrim($current_url, '#/');
170 170
 
171 171
         // Try to determine the current_url if one isn't set.
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
         $content = trim(str_replace('<?xml version="1.0" standalone="yes"?>', '', $content));
185 185
 
186 186
         // Clean up and style the tables
187
-        $content = str_replace('<table>', '<table class="' . $this->table_classes . '">', $content);
187
+        $content = str_replace('<table>', '<table class="'.$this->table_classes.'">', $content);
188 188
 
189 189
         return $content;
190 190
     }
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
         }
237 237
 
238 238
         try {
239
-            $xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>' . $content . '</div>');
239
+            $xml = new \SimpleXMLElement('<?xml version="1.0" standalone="yes"?><div>'.$content.'</div>');
240 240
         } catch (\Exception $e) {
241 241
             // SimpleXML barfed on us, so send back the un-modified content
242 242
             return [];
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 
267 267
         $this->formatters[] = [
268 268
             'callable' => $callback,
269
-            'cascade'  => (bool)$cascade
269
+            'cascade'  => (bool) $cascade
270 270
         ];
271 271
 
272 272
         return $this;
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
      */
283 283
     public function format($str)
284 284
     {
285
-        if (! is_array($this->formatters)) return $str;
285
+        if ( ! is_array($this->formatters)) return $str;
286 286
 
287 287
         foreach ($this->formatters as $formatter) {
288 288
             $method = $formatter['callable'];
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 
291 291
             $str = call_user_func($method, $str);
292 292
 
293
-            if (! $cascade) return $str;
293
+            if ( ! $cascade) return $str;
294 294
         }
295 295
 
296 296
         return $str;
@@ -334,14 +334,14 @@  discard block
 block discarded – undo
334 334
         // Module docs need $this->current_group and $type.
335 335
         $tocRoot = $this->current_folder;
336 336
         if ($this->current_folder != strtolower($folder)) {
337
-            $tocRoot .= '/' . strtolower($folder);
337
+            $tocRoot .= '/'.strtolower($folder);
338 338
         }
339 339
 
340 340
         $toc = [];
341 341
         foreach ($map as $files) {
342 342
             // If $files isn't an array, then make it one so that all situations
343 343
             // may be dealt with cleanly.
344
-            if (! is_array($files)) {
344
+            if ( ! is_array($files)) {
345 345
                 $files = [$files];
346 346
             }
347 347
 
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
             $sizes[] = count($chapters);
390 390
         }
391 391
 
392
-        $column_avg = (int)round(array_sum($sizes) / $section_count);
392
+        $column_avg = (int) round(array_sum($sizes) / $section_count);
393 393
 
394 394
         // Split things into 4 columns of approximately equal size.
395 395
         // If we only have 4 columns (or less), then make sure to
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
         $keys = array_keys($toc);
402 402
 
403 403
         for ($i = 0; $i <= $section_count; $i++) {
404
-            if (! isset($keys[$i])) {
404
+            if ( ! isset($keys[$i])) {
405 405
                 continue;
406 406
             }
407 407
 
@@ -450,11 +450,11 @@  discard block
 block discarded – undo
450 450
     public function addDocFolder($name, $path)
451 451
     {
452 452
         // Standardize the path
453
-        $path = realpath($path) . '/';
453
+        $path = realpath($path).'/';
454 454
 
455 455
         // realpath will return FALSE if the path doesn't exist
456 456
         // or the script doesn't have access to it.
457
-        if (! $path || $path == '/') {
457
+        if ( ! $path || $path == '/') {
458 458
             return $this;
459 459
         }
460 460
 
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
      */
502 502
     protected function detectCurrentFolder($current_url, $groups = [])
503 503
     {
504
-        if (! is_array($groups)) {
504
+        if ( ! is_array($groups)) {
505 505
             return null;
506 506
         }
507 507
 
@@ -549,9 +549,9 @@  discard block
 block discarded – undo
549 549
     {
550 550
         $folders = $this->doc_folders;
551 551
 
552
-        if (! is_null($restrictToFolder)) {
552
+        if ( ! is_null($restrictToFolder)) {
553 553
             // Make sure the folder exists
554
-            if (! is_null($restrictToFolder) && ! isset($this->doc_folders[$restrictToFolder])) {
554
+            if ( ! is_null($restrictToFolder) && ! isset($this->doc_folders[$restrictToFolder])) {
555 555
                 throw new \RuntimeException('You must add the docs folder that you wish to find docs from.');
556 556
             }
557 557
 
@@ -559,11 +559,11 @@  discard block
 block discarded – undo
559 559
         }
560 560
 
561 561
         foreach ($folders as $alias => $folder) {
562
-            if (file_exists($folder . $path . $this->docs_ext)) {
562
+            if (file_exists($folder.$path.$this->docs_ext)) {
563 563
                 // Store the alias so we know which folder we're in.
564 564
                 $this->current_folder = $alias;
565 565
 
566
-                return file_get_contents($folder . $path . $this->docs_ext);
566
+                return file_get_contents($folder.$path.$this->docs_ext);
567 567
             }
568 568
         }
569 569
 
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
         $href = $link->attributes()->href;
587 587
 
588 588
         // If the href is null, it's probably a named anchor with no content.
589
-        if (! $href) {
589
+        if ( ! $href) {
590 590
             // Make sure it has an href, else the XML will not close this
591 591
             // tag correctly.
592 592
             $link['href'] = ' ';
@@ -599,7 +599,7 @@  discard block
 block discarded – undo
599 599
 
600 600
         // If the href starts with #, then attach the current_url to it
601 601
         if ($href != '' && substr_compare($href, '#', 0, 1) === 0) {
602
-            $link['href'] = $current_url . $href;
602
+            $link['href'] = $current_url.$href;
603 603
 
604 604
             return $link;
605 605
         }
@@ -637,13 +637,13 @@  discard block
 block discarded – undo
637 637
             }
638 638
         }
639 639
 
640
-        if (! $group_found) {
641
-            $href = $this->current_folder . '/' . $href;
640
+        if ( ! $group_found) {
641
+            $href = $this->current_folder.'/'.$href;
642 642
         }
643 643
 
644 644
         // Convert to full site_url
645 645
         if (strpos($href, 'http') !== 0) {
646
-            $href = $site_url . 'docs/' . ltrim($href, '/ ');
646
+            $href = $site_url.'docs/'.ltrim($href, '/ ');
647 647
         }
648 648
 
649 649
         // Save the corrected href
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
             // our page title.
679 679
             if ($childType == 'h1' && empty($this->page_title))
680 680
             {
681
-                $this->page_title = (string)$line;
681
+                $this->page_title = (string) $line;
682 682
             }
683 683
 
684 684
             // Make sure that our current object is
@@ -691,39 +691,39 @@  discard block
 block discarded – undo
691 691
             }
692 692
 
693 693
             if ($childType == 'h2') {
694
-                $name = (string)$line;
695
-                $link = strtolower(str_replace(' ', '_', (string)$line));
694
+                $name = (string) $line;
695
+                $link = strtolower(str_replace(' ', '_', (string) $line));
696 696
 
697 697
                 $current_obj['name'] = $name;
698
-                $current_obj['link'] = '#' . $link;
698
+                $current_obj['link'] = '#'.$link;
699 699
                 $current_obj['items'] = [];
700 700
 
701 701
                 // Insert a named anchor into the $content
702
-                $anchor = '<a name="' . $link . '" id="' . $link . '" ></a>';
702
+                $anchor = '<a name="'.$link.'" id="'.$link.'" ></a>';
703 703
 
704 704
                 $search = "<h2>{$name}</h2>";
705 705
 
706
-                $content = str_replace($search, $anchor . $search, $content);
706
+                $content = str_replace($search, $anchor.$search, $content);
707 707
             } elseif ($childType == 'h3') {
708 708
                 // Make sure we have some place to store the items.
709
-                if (! isset($current_obj['items'])) {
709
+                if ( ! isset($current_obj['items'])) {
710 710
                     $current_obj['items'] = [];
711 711
                 }
712 712
 
713
-                $link = strtolower(str_replace(' ', '_', (string)$line));
714
-                $name = (string)$line;
713
+                $link = strtolower(str_replace(' ', '_', (string) $line));
714
+                $name = (string) $line;
715 715
 
716 716
                 $current_obj['items'][] = [
717 717
                     'name' => $name,
718
-                    'link' => '#' . $link
718
+                    'link' => '#'.$link
719 719
                 ];
720 720
 
721 721
                 // Insert a named anchor into the $content
722
-                $anchor = '<a name="' . $link . '" id="' . $link . '" ></a>';
722
+                $anchor = '<a name="'.$link.'" id="'.$link.'" ></a>';
723 723
 
724 724
                 $search = "<h3>{$name}</h3>";
725 725
 
726
-                $content = str_replace($search, $anchor . $search, $content);
726
+                $content = str_replace($search, $anchor.$search, $content);
727 727
             }
728 728
 
729 729
             // Is this the last element? Then close out our current object.
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
         if ($fp = @opendir($source_dir)) {
756 756
             $filedata = array();
757 757
             $new_depth = $directory_depth - 1;
758
-            $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
758
+            $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
759 759
 
760 760
             while (FALSE !== ($file = readdir($fp))) {
761 761
                 // Remove '.', '..', and hidden files [optional]
@@ -763,10 +763,10 @@  discard block
 block discarded – undo
763 763
                     continue;
764 764
                 }
765 765
 
766
-                is_dir($source_dir . $file) && $file .= DIRECTORY_SEPARATOR;
766
+                is_dir($source_dir.$file) && $file .= DIRECTORY_SEPARATOR;
767 767
 
768
-                if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir . $file)) {
769
-                    $filedata[$file] = directory_map($source_dir . $file, $new_depth, $hidden);
768
+                if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir.$file)) {
769
+                    $filedata[$file] = directory_map($source_dir.$file, $new_depth, $hidden);
770 770
                 } else {
771 771
                     $filedata[] = $file;
772 772
                 }
Please login to merge, or discard this patch.
Braces   +9 added lines, -3 removed lines patch added patch discarded remove patch
@@ -262,7 +262,9 @@  discard block
 block discarded – undo
262 262
      */
263 263
     public function registerFormatter($callback = null, $cascade = false)
264 264
     {
265
-        if (empty($callback)) return;
265
+        if (empty($callback)) {
266
+        	return;
267
+        }
266 268
 
267 269
         $this->formatters[] = [
268 270
             'callable' => $callback,
@@ -282,7 +284,9 @@  discard block
 block discarded – undo
282 284
      */
283 285
     public function format($str)
284 286
     {
285
-        if (! is_array($this->formatters)) return $str;
287
+        if (! is_array($this->formatters)) {
288
+        	return $str;
289
+        }
286 290
 
287 291
         foreach ($this->formatters as $formatter) {
288 292
             $method = $formatter['callable'];
@@ -290,7 +294,9 @@  discard block
 block discarded – undo
290 294
 
291 295
             $str = call_user_func($method, $str);
292 296
 
293
-            if (! $cascade) return $str;
297
+            if (! $cascade) {
298
+            	return $str;
299
+            }
294 300
         }
295 301
 
296 302
         return $str;
Please login to merge, or discard this patch.
myth/Forensics/Profiler.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -501,7 +501,7 @@
 block discarded – undo
501 501
 	 *
502 502
 	 * Allows any data passed to views to be available in the profiler bar.
503 503
 	 *
504
-	 * @return array
504
+	 * @return string
505 505
 	 */
506 506
 	public function _compile_view_data()
507 507
 	{
Please login to merge, or discard this patch.
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -531,16 +531,16 @@
 block discarded – undo
531 531
 
532 532
 
533 533
 	public static function get_file_size($size, $retstring = null) {
534
-        // adapted from code at http://aidanlister.com/repos/v/function.size_readable.php
535
-	    $sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
534
+		// adapted from code at http://aidanlister.com/repos/v/function.size_readable.php
535
+		$sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
536 536
 
537
-	    if ($retstring === null) { $retstring = '%01.2f %s'; }
537
+		if ($retstring === null) { $retstring = '%01.2f %s'; }
538 538
 
539 539
 		$lastsizestring = end($sizes);
540 540
 
541 541
 		foreach ($sizes as $sizestring) {
542
-	       	if ($size < 1024) { break; }
543
-	           if ($sizestring != $lastsizestring) { $size /= 1024; }
542
+		   	if ($size < 1024) { break; }
543
+			   if ($sizestring != $lastsizestring) { $size /= 1024; }
544 544
 		}
545 545
 
546 546
 		if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -81,20 +81,20 @@  discard block
 block discarded – undo
81 81
 										'view_data'
82 82
 										);
83 83
 
84
-	protected $_sections = array();		// Stores _compile_x() results
84
+	protected $_sections = array(); // Stores _compile_x() results
85 85
 
86
-	protected $_query_toggle_count 	= 25;
86
+	protected $_query_toggle_count = 25;
87 87
 
88 88
 	// --------------------------------------------------------------------
89 89
 
90 90
 	public function __construct($config = array())
91 91
 	{
92
-		$this->CI =& get_instance();
92
+		$this->CI = & get_instance();
93 93
 		$this->CI->load->language('profiler');
94 94
 
95 95
 		// If the config file has a query_toggle_count,
96 96
 		// use it, but remove it from the config array.
97
-		if ( isset($config['query_toggle_count']) )
97
+		if (isset($config['query_toggle_count']))
98 98
 		{
99 99
 			$this->_query_toggle_count = (int) $config['query_toggle_count'];
100 100
 			unset($config['query_toggle_count']);
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 		// Let's determine which databases are currently connected to
196 196
 		foreach (get_object_vars($this->CI) as $CI_object)
197 197
 		{
198
-			if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB') )
198
+			if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB'))
199 199
 			{
200 200
 				$dbs[] = $CI_object;
201 201
 			}
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 
230 230
 					foreach ($highlight as $bold)
231 231
 					{
232
-						$val = str_replace($bold, '<b>'. $bold .'</b>', $val);
232
+						$val = str_replace($bold, '<b>'.$bold.'</b>', $val);
233 233
 					}
234 234
 
235 235
 					$output[][$time] = $val;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 			{
269 269
 				if (is_array($val))
270 270
 				{
271
-					$output[$key] = "<pre>" . htmlspecialchars(stripslashes(print_r($val, true))) . "</pre>";
271
+					$output[$key] = "<pre>".htmlspecialchars(stripslashes(print_r($val, true)))."</pre>";
272 272
 				}
273 273
 				else
274 274
 				{
@@ -306,11 +306,11 @@  discard block
 block discarded – undo
306 306
 
307 307
 				if (is_array($val))
308 308
 				{
309
-					$output['&#36;_POST['. $key .']'] = '<pre>'. htmlspecialchars(stripslashes(print_r($val, TRUE))) . '</pre>';
309
+					$output['&#36;_POST['.$key.']'] = '<pre>'.htmlspecialchars(stripslashes(print_r($val, TRUE))).'</pre>';
310 310
 				}
311 311
 				else
312 312
 				{
313
-					$output['&#36;_POST['. $key .']'] = htmlspecialchars(stripslashes($val));
313
+					$output['&#36;_POST['.$key.']'] = htmlspecialchars(stripslashes($val));
314 314
 				}
315 315
 			}
316 316
 		}
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 	{
367 367
 		if (function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '')
368 368
 		{
369
-			$output = number_format($usage) .' bytes';
369
+			$output = number_format($usage).' bytes';
370 370
 		}
371 371
 		else
372 372
 		{
@@ -389,10 +389,10 @@  discard block
 block discarded – undo
389 389
 	{
390 390
 		$output = array();
391 391
 
392
-		foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD',' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR') as $header)
392
+		foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD', ' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR') as $header)
393 393
 		{
394 394
 			$val = (isset($_SERVER[$header])) ? $_SERVER[$header] : '';
395
-			$output[$header] =  $val;
395
+			$output[$header] = $val;
396 396
 		}
397 397
 
398 398
 		return $output;
Please login to merge, or discard this patch.
Braces   +13 added lines, -21 removed lines patch added patch discarded remove patch
@@ -217,8 +217,7 @@  discard block
 block discarded – undo
217 217
 			if (count($db->queries) == 0)
218 218
 			{
219 219
 				$output = $this->CI->lang->line('profiler_no_queries');
220
-			}
221
-			else
220
+			} else
222 221
 			{
223 222
 				$total = 0; // total query time
224 223
 
@@ -261,16 +260,14 @@  discard block
 block discarded – undo
261 260
 		if (count($get) == 0 || $get === false)
262 261
 		{
263 262
 			$output = $this->CI->lang->line('profiler_no_get');
264
-		}
265
-		else
263
+		} else
266 264
 		{
267 265
 			foreach ($get as $key => $val)
268 266
 			{
269 267
 				if (is_array($val))
270 268
 				{
271 269
 					$output[$key] = "<pre>" . htmlspecialchars(stripslashes(print_r($val, true))) . "</pre>";
272
-				}
273
-				else
270
+				} else
274 271
 				{
275 272
 					$output[$key] = htmlspecialchars(stripslashes($val));
276 273
 				}
@@ -294,8 +291,7 @@  discard block
 block discarded – undo
294 291
 		if (count($_POST) == 0)
295 292
 		{
296 293
 			$output = $this->CI->lang->line('profiler_no_post');
297
-		}
298
-		else
294
+		} else
299 295
 		{
300 296
 			foreach ($_POST as $key => $val)
301 297
 			{
@@ -307,8 +303,7 @@  discard block
 block discarded – undo
307 303
 				if (is_array($val))
308 304
 				{
309 305
 					$output['&#36;_POST['. $key .']'] = '<pre>'. htmlspecialchars(stripslashes(print_r($val, TRUE))) . '</pre>';
310
-				}
311
-				else
306
+				} else
312 307
 				{
313 308
 					$output['&#36;_POST['. $key .']'] = htmlspecialchars(stripslashes($val));
314 309
 				}
@@ -330,8 +325,7 @@  discard block
 block discarded – undo
330 325
 		if ($this->CI->uri->uri_string == '')
331 326
 		{
332 327
 			$output = $this->CI->lang->line('profiler_no_uri');
333
-		}
334
-		else
328
+		} else
335 329
 		{
336 330
 			$output = $this->CI->uri->uri_string;
337 331
 		}
@@ -367,8 +361,7 @@  discard block
 block discarded – undo
367 361
 		if (function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '')
368 362
 		{
369 363
 			$output = number_format($usage) .' bytes';
370
-		}
371
-		else
364
+		} else
372 365
 		{
373 366
 			$output = $this->CI->lang->line('profiler_no_memory_usage');
374 367
 		}
@@ -448,8 +441,7 @@  discard block
 block discarded – undo
448 441
 				if ($log['type'] == 'log')
449 442
 				{
450 443
 					$logs['console'][$key]['data'] = print_r($log['data'], true);
451
-				}
452
-				elseif ($log['type'] == 'memory')
444
+				} elseif ($log['type'] == 'memory')
453 445
 				{
454 446
 					$logs['console'][$key]['data'] = $this->get_file_size($log['data']);
455 447
 				}
@@ -482,8 +474,7 @@  discard block
 block discarded – undo
482 474
 					if (is_array($val) || is_object($val))
483 475
 					{
484 476
 						$output[$key] = htmlspecialchars(stripslashes(print_r($val, true)));
485
-					}
486
-					else
477
+					} else
487 478
 					{
488 479
 						$output[$key] = htmlspecialchars(stripslashes($val));
489 480
 					}
@@ -517,8 +508,7 @@  discard block
 block discarded – undo
517 508
 			if (is_array($val) || is_object($val))
518 509
 			{
519 510
 				$output[$key] = htmlspecialchars(stripslashes(print_r($val, true)));
520
-			}
521
-			else
511
+			} else
522 512
 			{
523 513
 				$output[$key] = htmlspecialchars(stripslashes($val));
524 514
 			}
@@ -565,7 +555,9 @@  discard block
 block discarded – undo
565 555
 			if ($this->_compile_{$section} !== FALSE)
566 556
 			{
567 557
 				$func = "_compile_{$section}";
568
-				if ($section == 'http_headers') $section = 'headers';
558
+				if ($section == 'http_headers') {
559
+					$section = 'headers';
560
+				}
569 561
 				$this->_sections[$section] = $this->{$func}();
570 562
 				$fields_displayed++;
571 563
 			}
Please login to merge, or discard this patch.
myth/Forge/BaseGenerator.php 4 patches
Doc Comments   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -167,10 +167,10 @@  discard block
 block discarded – undo
167 167
     /**
168 168
      * Creates a new directory at the specified path.
169 169
      *
170
-     * @param $path
171
-     * @param int|string $perms
170
+     * @param string $path
171
+     * @param integer $perms
172 172
      *
173
-     * @return bool
173
+     * @return BaseGenerator
174 174
      */
175 175
     public function createDirectory($path, $perms=0755)
176 176
     {
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
      * parses it with the passed in data, and writes to the new location.
222 222
      *
223 223
      * @param $template
224
-     * @param $destination
224
+     * @param string $destination
225 225
      * @param array $data
226 226
      * @param bool $overwrite
227 227
      *
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
      *      replace => ''   - a simple string to be replaced. All locations will be replaced.
254 254
      *      regex   => ''   - a pregex pattern to use to replace all locations.
255 255
      *
256
-     * @param $path
256
+     * @param string $path
257 257
      * @param $content
258 258
      * @param array $options
259 259
      *
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 	 * the next command.
319 319
 	 *
320 320
 	 * @param $command
321
-	 * @param null $options
321
+	 * @param string|null $options
322 322
 	 */
323 323
     public function generate($command, $options = '', $quiet=false)
324 324
     {
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 	/**
545 545
 	 * Scans through the collections for the folder for this generator.
546 546
 	 *
547
-	 * @param $name
547
+	 * @param string $name
548 548
 	 *
549 549
 	 * @return null|string
550 550
 	 */
Please login to merge, or discard this patch.
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
 		    if (is_array($folders))
81 81
 		    {
82
-			    $this->module_path = $folders[0] . strtolower($module) .'/';
82
+			    $this->module_path = $folders[0].strtolower($module).'/';
83 83
 		    }
84 84
 		}
85 85
 
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
      * @param bool  $quiet      If true, models should accept default values.
102 102
      * @return mixed
103 103
      */
104
-    abstract function run($segments=[], $quiet=false);
104
+    abstract function run($segments = [], $quiet = false);
105 105
 
106 106
     //--------------------------------------------------------------------
107 107
 
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
      *
115 115
      * @return bool
116 116
      */
117
-    public function createFile($path, $contents=null, $overwrite=false, $perms=0644)
117
+    public function createFile($path, $contents = null, $overwrite = false, $perms = 0644)
118 118
     {
119 119
 	    $path = $this->sandbox($path);
120 120
 
@@ -123,8 +123,8 @@  discard block
 block discarded – undo
123 123
         // Does file already exist?
124 124
         if ($file_exists)
125 125
         {
126
-	        if (! $overwrite) {
127
-		        CLI::write( CLI::color("\t". strtolower(lang('exists')) .": ", 'blue') . str_replace(APPPATH, '', $path ) );
126
+	        if ( ! $overwrite) {
127
+		        CLI::write(CLI::color("\t".strtolower(lang('exists')).": ", 'blue').str_replace(APPPATH, '', $path));
128 128
 		        return true;
129 129
 	        }
130 130
 
@@ -136,27 +136,27 @@  discard block
 block discarded – undo
136 136
 		array_pop($segments);
137 137
 		$folder = implode('/', $segments);
138 138
 
139
-	    if (! is_dir($folder))
139
+	    if ( ! is_dir($folder))
140 140
 	    {
141 141
 		    $this->createDirectory($folder);
142 142
 	    }
143 143
 
144 144
         get_instance()->load->helper('file');
145 145
 
146
-        if (! write_file($path, $contents))
146
+        if ( ! write_file($path, $contents))
147 147
         {
148
-            throw new \RuntimeException( sprintf( lang('errors.writing_file'),  $path) );
148
+            throw new \RuntimeException(sprintf(lang('errors.writing_file'), $path));
149 149
         }
150 150
 
151 151
         chmod($path, $perms);
152 152
 
153 153
 	    if ($overwrite && $file_exists)
154 154
 	    {
155
-		    CLI::write( CLI::color("\t". strtolower( lang('overwrote') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
155
+		    CLI::write(CLI::color("\t".strtolower(lang('overwrote'))." ", 'light_red').str_replace(APPPATH, '', $path));
156 156
 	    }
157 157
 	    else
158 158
 	    {
159
-		    CLI::write( CLI::color("\t". strtolower( lang('created') ) ." ", 'yellow') . str_replace(APPPATH, '', $path ) );
159
+		    CLI::write(CLI::color("\t".strtolower(lang('created'))." ", 'yellow').str_replace(APPPATH, '', $path));
160 160
 	    }
161 161
 
162 162
         return $this;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
      *
173 173
      * @return bool
174 174
      */
175
-    public function createDirectory($path, $perms=0755)
175
+    public function createDirectory($path, $perms = 0755)
176 176
     {
177 177
 	    $path = $this->sandbox($path);
178 178
 
@@ -181,9 +181,9 @@  discard block
 block discarded – undo
181 181
             return $this;
182 182
         }
183 183
 
184
-        if (! mkdir($path, $perms, true) )
184
+        if ( ! mkdir($path, $perms, true))
185 185
         {
186
-            throw new \RuntimeException( sprintf( lang('errors.creating_dir'), $path) );
186
+            throw new \RuntimeException(sprintf(lang('errors.creating_dir'), $path));
187 187
         }
188 188
 
189 189
         return $this;
@@ -200,11 +200,11 @@  discard block
 block discarded – undo
200 200
      *
201 201
      * @return bool
202 202
      */
203
-    public function copyFile($source, $destination, $overwrite=false)
203
+    public function copyFile($source, $destination, $overwrite = false)
204 204
     {
205 205
 	    $source = $this->sandbox($source);
206 206
 
207
-	    if (! file_exists($source))
207
+	    if ( ! file_exists($source))
208 208
 	    {
209 209
 		    return null;
210 210
 	    }
@@ -227,9 +227,9 @@  discard block
 block discarded – undo
227 227
      *
228 228
      * @return $this
229 229
      */
230
-    public function copyTemplate($template, $destination, $data=[], $overwrite=false)
230
+    public function copyTemplate($template, $destination, $data = [], $overwrite = false)
231 231
     {
232
-	    if (! is_array($data))
232
+	    if ( ! is_array($data))
233 233
 	    {
234 234
 		    $data = array($data);
235 235
 	    }
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
      *
260 260
      * @return $this
261 261
      */
262
-    public function injectIntoFile($path, $content, $options='append')
262
+    public function injectIntoFile($path, $content, $options = 'append')
263 263
     {
264 264
         $kit = new FileKit();
265 265
 
@@ -270,11 +270,11 @@  discard block
 block discarded – undo
270 270
         else if (is_array($options) && count($options))
271 271
         {
272 272
             $keys = array_keys($options);
273
-            $action = array_shift( $keys );
273
+            $action = array_shift($keys);
274 274
             $param = $options[$action];
275 275
         }
276 276
 
277
-        switch ( strtolower($action) )
277
+        switch (strtolower($action))
278 278
         {
279 279
             case 'prepend':
280 280
                 $success = $kit->prepend($path, $content);
@@ -299,11 +299,11 @@  discard block
 block discarded – undo
299 299
 
300 300
         if ($success)
301 301
         {
302
-            CLI::write( CLI::color("\t". strtolower( lang('modified') ) ." ", 'cyan') . str_replace(APPPATH, '', $path ) );
302
+            CLI::write(CLI::color("\t".strtolower(lang('modified'))." ", 'cyan').str_replace(APPPATH, '', $path));
303 303
         }
304 304
         else
305 305
         {
306
-            CLI::write( CLI::color("\t". strtolower( lang('error') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
306
+            CLI::write(CLI::color("\t".strtolower(lang('error'))." ", 'light_red').str_replace(APPPATH, '', $path));
307 307
         }
308 308
 
309 309
         return $this;
@@ -320,10 +320,10 @@  discard block
 block discarded – undo
320 320
 	 * @param $command
321 321
 	 * @param null $options
322 322
 	 */
323
-    public function generate($command, $options = '', $quiet=false)
323
+    public function generate($command, $options = '', $quiet = false)
324 324
     {
325 325
 		$orig_options = CLI::optionString();
326
-	    $options = $orig_options .' '. $options;
326
+	    $options = $orig_options.' '.$options;
327 327
 
328 328
 	    if ($quiet === true)
329 329
 	    {
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
 		    $options .= ' -overwrite';
336 336
 	    }
337 337
 
338
-	    passthru( "php sprint forge {$command} {$options}" );
338
+	    passthru("php sprint forge {$command} {$options}");
339 339
     }
340 340
 
341 341
     //--------------------------------------------------------------------
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
      *
349 349
      * @return \Myth\Forge\BaseGenerator
350 350
      */
351
-    public function route($left, $right, $options=[], $method='any')
351
+    public function route($left, $right, $options = [], $method = 'any')
352 352
     {
353 353
         $option_str = '[';
354 354
 
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 
362 362
         $content = "\$routes->{$method}('{$left}', '{$right}', {$option_str});\n";
363 363
 
364
-        return $this->injectIntoFile(APPPATH .'config/routes.php', $content, ['after' => "// Auto-generated routes go here\n"]);
364
+        return $this->injectIntoFile(APPPATH.'config/routes.php', $content, ['after' => "// Auto-generated routes go here\n"]);
365 365
     }
366 366
     
367 367
     //--------------------------------------------------------------------
@@ -369,21 +369,21 @@  discard block
 block discarded – undo
369 369
     /**
370 370
      * Outputs the contents of the file in the template's source path.
371 371
      */
372
-    public function readme($file='readme.txt')
372
+    public function readme($file = 'readme.txt')
373 373
     {
374 374
 	    $name = str_replace('Generator', '', get_class($this));
375 375
 
376 376
 	    $path = $this->locateGenerator($name);
377 377
 
378
-        if (! file_exists($path . $file))
378
+        if ( ! file_exists($path.$file))
379 379
         {
380
-            CLI::error(sprintf( lang('forge.cant_find_readme'), $file) );
380
+            CLI::error(sprintf(lang('forge.cant_find_readme'), $file));
381 381
         }
382 382
 
383
-	    $contents = file_get_contents($path . $file);
383
+	    $contents = file_get_contents($path.$file);
384 384
 
385 385
         CLI::new_line(2);
386
-        CLI::write( CLI::wrap($contents), 'green' );
386
+        CLI::write(CLI::wrap($contents), 'green');
387 387
         CLI::new_line();
388 388
     }
389 389
 
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
      *
400 400
      * @return string The rendered template
401 401
      */
402
-    public function render($template_name, $data=[], $folder=null)
402
+    public function render($template_name, $data = [], $folder = null)
403 403
     {
404 404
         if (empty($this->themer))
405 405
         {
@@ -410,27 +410,27 @@  discard block
 block discarded – undo
410 410
 
411 411
         $output = null;
412 412
 
413
-	    $view = $template_name .'.tpl';
413
+	    $view = $template_name.'.tpl';
414 414
 
415 415
         $groups = config_item('forge.collections');
416 416
 
417
-	    $name = str_replace('Generator', '', get_class($this) );
417
+	    $name = str_replace('Generator', '', get_class($this));
418 418
 
419 419
         foreach ($groups as $group => $path)
420 420
         {
421
-	        $path = rtrim($path, '/ ') .'/';
421
+	        $path = rtrim($path, '/ ').'/';
422 422
 	        $folders = scandir($path);
423 423
 
424
-	        if (! $i = array_search(ucfirst($name), $folders))
424
+	        if ( ! $i = array_search(ucfirst($name), $folders))
425 425
 	        {
426 426
 		        continue;
427 427
 	        }
428 428
 
429
-	        $view = $folders[$i] . '/'. $view;
429
+	        $view = $folders[$i].'/'.$view;
430 430
 
431
-            if (realpath($path . $view .'.php'))
431
+            if (realpath($path.$view.'.php'))
432 432
             {
433
-                $output = $this->themer->display($group .':'. $view, $data);
433
+                $output = $this->themer->display($group.':'.$view, $data);
434 434
                 break;
435 435
             }
436 436
         }
@@ -461,24 +461,24 @@  discard block
 block discarded – undo
461 461
         $path = $this->normalizePath($path);
462 462
 
463 463
 		// If it's writing to BASEPATH - FIX IT
464
-		if (strpos($path, $this->normalizePath(BASEPATH) ) === 0)
464
+		if (strpos($path, $this->normalizePath(BASEPATH)) === 0)
465 465
 		{
466
-			return APPPATH . $path;
466
+			return APPPATH.$path;
467 467
 		}
468 468
 
469 469
 		// Exact match for FCPATH?
470
-		if (strpos($path, $this->normalizePath(FCPATH) ) === 0)
470
+		if (strpos($path, $this->normalizePath(FCPATH)) === 0)
471 471
 		{
472 472
 			return $path;
473 473
 		}
474 474
 
475 475
 		// Exact match for APPPATH?
476
-		if (strpos($path, $this->normalizePath(APPPATH) ) === 0)
476
+		if (strpos($path, $this->normalizePath(APPPATH)) === 0)
477 477
 		{
478 478
 			return $path;
479 479
 		}
480 480
 
481
-	    return APPPATH . $path;
481
+	    return APPPATH.$path;
482 482
 	}
483 483
 
484 484
 	//--------------------------------------------------------------------
@@ -493,12 +493,12 @@  discard block
 block discarded – undo
493 493
     {
494 494
         $themer_name = config_item('forge.themer');
495 495
 
496
-        if (! $themer_name)
496
+        if ( ! $themer_name)
497 497
         {
498
-            throw new \RuntimeException( lang('forge.no_themer') );
498
+            throw new \RuntimeException(lang('forge.no_themer'));
499 499
         }
500 500
 
501
-        $this->themer = new $themer_name( get_instance() );
501
+        $this->themer = new $themer_name(get_instance());
502 502
 
503 503
         // Register our paths with the themer
504 504
         $paths = config_item('forge.collections');
@@ -514,9 +514,9 @@  discard block
 block discarded – undo
514 514
 	{
515 515
 		$kit_name = config_item('theme.uikit');
516 516
 
517
-		if (! $kit_name)
517
+		if ( ! $kit_name)
518 518
 		{
519
-			throw new \RuntimeException( lang('forge.no_uikit') );
519
+			throw new \RuntimeException(lang('forge.no_uikit'));
520 520
 		}
521 521
 
522 522
 		$uikit = new $kit_name();
@@ -527,16 +527,16 @@  discard block
 block discarded – undo
527 527
 	//--------------------------------------------------------------------
528 528
 
529 529
 
530
-	protected function determineOutputPath($folder='')
530
+	protected function determineOutputPath($folder = '')
531 531
 	{
532
-		$path = APPPATH . $folder;
532
+		$path = APPPATH.$folder;
533 533
 
534
-		if (! empty($this->module_path))
534
+		if ( ! empty($this->module_path))
535 535
 		{
536
-			$path = $this->module_path . $folder;
536
+			$path = $this->module_path.$folder;
537 537
 		}
538 538
 
539
-		return rtrim($path, '/ ') .'/';
539
+		return rtrim($path, '/ ').'/';
540 540
 	}
541 541
 
542 542
 	//--------------------------------------------------------------------
@@ -552,22 +552,22 @@  discard block
 block discarded – undo
552 552
 	{
553 553
 		$collections = config_item('forge.collections');
554 554
 
555
-		if (! is_array($collections) || ! count($collections) )
555
+		if ( ! is_array($collections) || ! count($collections))
556 556
 		{
557
-			return CLI::error( lang('forge.no_collections') );
557
+			return CLI::error(lang('forge.no_collections'));
558 558
 		}
559 559
 
560 560
 		foreach ($collections as $alias => $path)
561 561
 		{
562
-			$path = rtrim($path, '/ ') .'/';
562
+			$path = rtrim($path, '/ ').'/';
563 563
 			$folders = scandir($path);
564 564
 
565
-			if (! $i = array_search(ucfirst($name), $folders))
565
+			if ( ! $i = array_search(ucfirst($name), $folders))
566 566
 			{
567 567
 				continue;
568 568
 			}
569 569
 
570
-			$this->gen_path = $path . $folders[$i] .'/';
570
+			$this->gen_path = $path.$folders[$i].'/';
571 571
 
572 572
 			return $this->gen_path;
573 573
 		}
@@ -584,9 +584,9 @@  discard block
 block discarded – undo
584 584
 	 *
585 585
 	 * @return string
586 586
 	 */
587
-	protected function stringify($array, $depth=0)
587
+	protected function stringify($array, $depth = 0)
588 588
 	{
589
-		if (! is_array($array))
589
+		if ( ! is_array($array))
590 590
 		{
591 591
 			return '';
592 592
 		}
@@ -606,9 +606,9 @@  discard block
 block discarded – undo
606 606
 
607 607
 		foreach ($array as $key => $value)
608 608
 		{
609
-			$str .= str_repeat("\t", $depth +1);
609
+			$str .= str_repeat("\t", $depth + 1);
610 610
 
611
-			if (! is_numeric($key))
611
+			if ( ! is_numeric($key))
612 612
 			{
613 613
 				$str .= "'{$key}' => ";
614 614
 			}
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 			}
633 633
 		}
634 634
 
635
-		$str .= str_repeat("\t", $depth) ."],";
635
+		$str .= str_repeat("\t", $depth)."],";
636 636
 
637 637
 		return $str;
638 638
 	}
@@ -667,13 +667,13 @@  discard block
 block discarded – undo
667 667
         // Initialize testing variable
668 668
         $test = '';
669 669
 
670
-        foreach($segments as $segment)
670
+        foreach ($segments as $segment)
671 671
         {
672
-            if($segment != '.')
672
+            if ($segment != '.')
673 673
             {
674 674
                 $test = array_pop($parts);
675 675
 
676
-                if(is_null($test))
676
+                if (is_null($test))
677 677
                 {
678 678
                     $parts[] = $segment;
679 679
                 }
Please login to merge, or discard this patch.
Braces   +8 added lines, -16 removed lines patch added patch discarded remove patch
@@ -153,8 +153,7 @@  discard block
 block discarded – undo
153 153
 	    if ($overwrite && $file_exists)
154 154
 	    {
155 155
 		    CLI::write( CLI::color("\t". strtolower( lang('overwrote') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
156
-	    }
157
-	    else
156
+	    } else
158 157
 	    {
159 158
 		    CLI::write( CLI::color("\t". strtolower( lang('created') ) ." ", 'yellow') . str_replace(APPPATH, '', $path ) );
160 159
 	    }
@@ -266,8 +265,7 @@  discard block
 block discarded – undo
266 265
         if (is_string($options))
267 266
         {
268 267
             $action = $options;
269
-        }
270
-        else if (is_array($options) && count($options))
268
+        } else if (is_array($options) && count($options))
271 269
         {
272 270
             $keys = array_keys($options);
273 271
             $action = array_shift( $keys );
@@ -300,8 +298,7 @@  discard block
 block discarded – undo
300 298
         if ($success)
301 299
         {
302 300
             CLI::write( CLI::color("\t". strtolower( lang('modified') ) ." ", 'cyan') . str_replace(APPPATH, '', $path ) );
303
-        }
304
-        else
301
+        } else
305 302
         {
306 303
             CLI::write( CLI::color("\t". strtolower( lang('error') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
307 304
         }
@@ -616,17 +613,14 @@  discard block
 block discarded – undo
616 613
 			if (is_array($value))
617 614
 			{
618 615
 				$str .= $this->stringify($value, $depth);
619
-			}
620
-			else if (is_bool($value))
616
+			} else if (is_bool($value))
621 617
 			{
622 618
 				$b = $value === true ? 'true' : 'false';
623 619
 				$str .= "{$b},\n";
624
-			}
625
-			else if (is_numeric($value))
620
+			} else if (is_numeric($value))
626 621
 			{
627 622
 				$str .= "{$value},\n";
628
-			}
629
-			else
623
+			} else
630 624
 			{
631 625
 				$str .= "'{$value}',\n";
632 626
 			}
@@ -676,8 +670,7 @@  discard block
 block discarded – undo
676 670
                 if(is_null($test))
677 671
                 {
678 672
                     $parts[] = $segment;
679
-                }
680
-                else if ($segment == '..')
673
+                } else if ($segment == '..')
681 674
                 {
682 675
                     if ($test == '..')
683 676
                     {
@@ -688,8 +681,7 @@  discard block
 block discarded – undo
688 681
                     {
689 682
                         $parts[] = $segment;
690 683
                     }
691
-                }
692
-                else
684
+                } else
693 685
                 {
694 686
                     $parts[] = $test;
695 687
                     $parts[] = $segment;
Please login to merge, or discard this patch.
Indentation   +412 added lines, -412 removed lines patch added patch discarded remove patch
@@ -43,13 +43,13 @@  discard block
 block discarded – undo
43 43
  */
44 44
 abstract class BaseGenerator extends CLIController {
45 45
 
46
-    /**
47
-     * Instance of the active themer.
48
-     * @var null
49
-     */
50
-    protected $themer = null;
46
+	/**
47
+	 * Instance of the active themer.
48
+	 * @var null
49
+	 */
50
+	protected $themer = null;
51 51
 
52
-    protected $gen_path = null;
52
+	protected $gen_path = null;
53 53
 
54 54
 	/**
55 55
 	 * The name of the module being used, if any.
@@ -62,254 +62,254 @@  discard block
 block discarded – undo
62 62
 
63 63
 	protected $overwrite = false;
64 64
 
65
-    //--------------------------------------------------------------------
65
+	//--------------------------------------------------------------------
66 66
 
67
-    public function __construct()
68
-    {
69
-        parent::__construct();
67
+	public function __construct()
68
+	{
69
+		parent::__construct();
70 70
 
71
-        $this->load->config('forge');
71
+		$this->load->config('forge');
72 72
 
73
-	    // Detect if we're genning in a module
74
-	    if ($module = CLI::option('module'))
75
-	    {
76
-		    $this->module = $module;
73
+		// Detect if we're genning in a module
74
+		if ($module = CLI::option('module'))
75
+		{
76
+			$this->module = $module;
77 77
 
78
-		    $folders = config_item('modules_locations');
78
+			$folders = config_item('modules_locations');
79 79
 
80
-		    if (is_array($folders))
81
-		    {
82
-			    $this->module_path = $folders[0] . strtolower($module) .'/';
83
-		    }
80
+			if (is_array($folders))
81
+			{
82
+				$this->module_path = $folders[0] . strtolower($module) .'/';
83
+			}
84 84
 		}
85 85
 
86
-	    // Should we overwrite files?
87
-	    if (CLI::option('overwrite'))
88
-	    {
89
-		    $this->overwrite = true;
90
-	    }
91
-    }
86
+		// Should we overwrite files?
87
+		if (CLI::option('overwrite'))
88
+		{
89
+			$this->overwrite = true;
90
+		}
91
+	}
92 92
 
93
-    //--------------------------------------------------------------------
93
+	//--------------------------------------------------------------------
94 94
 
95 95
 
96
-    /**
97
-     * The method called by the main generator script. This must be
98
-     * overridden by child classes to implement the actual logic used.
99
-     *
100
-     * @param array $segments
101
-     * @param bool  $quiet      If true, models should accept default values.
102
-     * @return mixed
103
-     */
104
-    abstract function run($segments=[], $quiet=false);
96
+	/**
97
+	 * The method called by the main generator script. This must be
98
+	 * overridden by child classes to implement the actual logic used.
99
+	 *
100
+	 * @param array $segments
101
+	 * @param bool  $quiet      If true, models should accept default values.
102
+	 * @return mixed
103
+	 */
104
+	abstract function run($segments=[], $quiet=false);
105 105
 
106
-    //--------------------------------------------------------------------
106
+	//--------------------------------------------------------------------
107 107
 
108 108
 
109
-    /**
110
-     * Creates a file at the specified path with the given contents.
111
-     *
112
-     * @param $path
113
-     * @param null $contents
114
-     *
115
-     * @return bool
116
-     */
117
-    public function createFile($path, $contents=null, $overwrite=false, $perms=0644)
118
-    {
119
-	    $path = $this->sandbox($path);
109
+	/**
110
+	 * Creates a file at the specified path with the given contents.
111
+	 *
112
+	 * @param $path
113
+	 * @param null $contents
114
+	 *
115
+	 * @return bool
116
+	 */
117
+	public function createFile($path, $contents=null, $overwrite=false, $perms=0644)
118
+	{
119
+		$path = $this->sandbox($path);
120 120
 
121
-	    $file_exists = is_file($path);
121
+		$file_exists = is_file($path);
122 122
 
123
-        // Does file already exist?
124
-        if ($file_exists)
125
-        {
126
-	        if (! $overwrite) {
127
-		        CLI::write( CLI::color("\t". strtolower(lang('exists')) .": ", 'blue') . str_replace(APPPATH, '', $path ) );
128
-		        return true;
129
-	        }
123
+		// Does file already exist?
124
+		if ($file_exists)
125
+		{
126
+			if (! $overwrite) {
127
+				CLI::write( CLI::color("\t". strtolower(lang('exists')) .": ", 'blue') . str_replace(APPPATH, '', $path ) );
128
+				return true;
129
+			}
130 130
 
131
-	        unlink($path);
132
-        }
131
+			unlink($path);
132
+		}
133 133
 
134
-	    // Do we need to create the directory?
135
-	    $segments = explode('/', $path);
134
+		// Do we need to create the directory?
135
+		$segments = explode('/', $path);
136 136
 		array_pop($segments);
137 137
 		$folder = implode('/', $segments);
138 138
 
139
-	    if (! is_dir($folder))
140
-	    {
141
-		    $this->createDirectory($folder);
142
-	    }
139
+		if (! is_dir($folder))
140
+		{
141
+			$this->createDirectory($folder);
142
+		}
143 143
 
144
-        get_instance()->load->helper('file');
144
+		get_instance()->load->helper('file');
145 145
 
146
-        if (! write_file($path, $contents))
147
-        {
148
-            throw new \RuntimeException( sprintf( lang('errors.writing_file'),  $path) );
149
-        }
146
+		if (! write_file($path, $contents))
147
+		{
148
+			throw new \RuntimeException( sprintf( lang('errors.writing_file'),  $path) );
149
+		}
150 150
 
151
-        chmod($path, $perms);
151
+		chmod($path, $perms);
152 152
 
153
-	    if ($overwrite && $file_exists)
154
-	    {
155
-		    CLI::write( CLI::color("\t". strtolower( lang('overwrote') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
156
-	    }
157
-	    else
158
-	    {
159
-		    CLI::write( CLI::color("\t". strtolower( lang('created') ) ." ", 'yellow') . str_replace(APPPATH, '', $path ) );
160
-	    }
153
+		if ($overwrite && $file_exists)
154
+		{
155
+			CLI::write( CLI::color("\t". strtolower( lang('overwrote') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
156
+		}
157
+		else
158
+		{
159
+			CLI::write( CLI::color("\t". strtolower( lang('created') ) ." ", 'yellow') . str_replace(APPPATH, '', $path ) );
160
+		}
161 161
 
162
-        return $this;
163
-    }
162
+		return $this;
163
+	}
164 164
     
165
-    //--------------------------------------------------------------------
166
-
167
-    /**
168
-     * Creates a new directory at the specified path.
169
-     *
170
-     * @param $path
171
-     * @param int|string $perms
172
-     *
173
-     * @return bool
174
-     */
175
-    public function createDirectory($path, $perms=0755)
176
-    {
177
-	    $path = $this->sandbox($path);
178
-
179
-        if (is_dir($path))
180
-        {
181
-            return $this;
182
-        }
183
-
184
-        if (! mkdir($path, $perms, true) )
185
-        {
186
-            throw new \RuntimeException( sprintf( lang('errors.creating_dir'), $path) );
187
-        }
188
-
189
-        return $this;
190
-    }
191
-
192
-    //--------------------------------------------------------------------
193
-
194
-    /**
195
-     * Copies a file from the current template group to the destination.
196
-     *
197
-     * @param $source
198
-     * @param $destination
199
-     * @param bool $overwrite
200
-     *
201
-     * @return bool
202
-     */
203
-    public function copyFile($source, $destination, $overwrite=false)
204
-    {
205
-	    $source = $this->sandbox($source);
206
-
207
-	    if (! file_exists($source))
208
-	    {
209
-		    return null;
210
-	    }
211
-
212
-	    $content = file_get_contents($source);
213
-
214
-	    return $this->createFile($destination, $content, $overwrite);
215
-    }
216
-
217
-    //--------------------------------------------------------------------
218
-
219
-    /**
220
-     * Attempts to locate a template within the current template group,
221
-     * parses it with the passed in data, and writes to the new location.
222
-     *
223
-     * @param $template
224
-     * @param $destination
225
-     * @param array $data
226
-     * @param bool $overwrite
227
-     *
228
-     * @return $this
229
-     */
230
-    public function copyTemplate($template, $destination, $data=[], $overwrite=false)
231
-    {
232
-	    if (! is_array($data))
233
-	    {
234
-		    $data = array($data);
235
-	    }
236
-
237
-        $content = $this->render($template, $data);
238
-
239
-        return $this->createFile($destination, $content, $overwrite);
240
-    }
241
-
242
-    //--------------------------------------------------------------------
243
-
244
-
245
-    /**
246
-     * Injects a block of code into an existing file. Using options
247
-     * you can specify where the code should be inserted. Available options
248
-     * are:
249
-     *      prepend         - Place at beginning of file
250
-     *      append          - Place at end of file
251
-     *      before  => ''   - Insert just prior to this line of text (don't forget the line ending "\n")
252
-     *      after   => ''   - Insert just after this line of text (don't forget the line ending "\n")
253
-     *      replace => ''   - a simple string to be replaced. All locations will be replaced.
254
-     *      regex   => ''   - a pregex pattern to use to replace all locations.
255
-     *
256
-     * @param $path
257
-     * @param $content
258
-     * @param array $options
259
-     *
260
-     * @return $this
261
-     */
262
-    public function injectIntoFile($path, $content, $options='append')
263
-    {
264
-        $kit = new FileKit();
265
-
266
-        if (is_string($options))
267
-        {
268
-            $action = $options;
269
-        }
270
-        else if (is_array($options) && count($options))
271
-        {
272
-            $keys = array_keys($options);
273
-            $action = array_shift( $keys );
274
-            $param = $options[$action];
275
-        }
276
-
277
-        switch ( strtolower($action) )
278
-        {
279
-            case 'prepend':
280
-                $success = $kit->prepend($path, $content);
281
-                break;
282
-            case 'before':
283
-                $success = $kit->before($path, $param, $content);
284
-                break;
285
-            case 'after':
286
-                $success = $kit->after($path, $param, $content);
287
-                break;
288
-            case 'replace':
289
-                $success = $kit->replaceIn($path, $param, $content);
290
-                break;
291
-            case 'regex':
292
-                $success = $kit->replaceWithRegex($path, $param, $content);
293
-                break;
294
-            case 'append':
295
-            default:
296
-                $success = $kit->append($path, $content);
297
-                break;
298
-        }
299
-
300
-        if ($success)
301
-        {
302
-            CLI::write( CLI::color("\t". strtolower( lang('modified') ) ." ", 'cyan') . str_replace(APPPATH, '', $path ) );
303
-        }
304
-        else
305
-        {
306
-            CLI::write( CLI::color("\t". strtolower( lang('error') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
307
-        }
308
-
309
-        return $this;
310
-    }
165
+	//--------------------------------------------------------------------
166
+
167
+	/**
168
+	 * Creates a new directory at the specified path.
169
+	 *
170
+	 * @param $path
171
+	 * @param int|string $perms
172
+	 *
173
+	 * @return bool
174
+	 */
175
+	public function createDirectory($path, $perms=0755)
176
+	{
177
+		$path = $this->sandbox($path);
178
+
179
+		if (is_dir($path))
180
+		{
181
+			return $this;
182
+		}
183
+
184
+		if (! mkdir($path, $perms, true) )
185
+		{
186
+			throw new \RuntimeException( sprintf( lang('errors.creating_dir'), $path) );
187
+		}
188
+
189
+		return $this;
190
+	}
191
+
192
+	//--------------------------------------------------------------------
193
+
194
+	/**
195
+	 * Copies a file from the current template group to the destination.
196
+	 *
197
+	 * @param $source
198
+	 * @param $destination
199
+	 * @param bool $overwrite
200
+	 *
201
+	 * @return bool
202
+	 */
203
+	public function copyFile($source, $destination, $overwrite=false)
204
+	{
205
+		$source = $this->sandbox($source);
206
+
207
+		if (! file_exists($source))
208
+		{
209
+			return null;
210
+		}
211
+
212
+		$content = file_get_contents($source);
213
+
214
+		return $this->createFile($destination, $content, $overwrite);
215
+	}
216
+
217
+	//--------------------------------------------------------------------
218
+
219
+	/**
220
+	 * Attempts to locate a template within the current template group,
221
+	 * parses it with the passed in data, and writes to the new location.
222
+	 *
223
+	 * @param $template
224
+	 * @param $destination
225
+	 * @param array $data
226
+	 * @param bool $overwrite
227
+	 *
228
+	 * @return $this
229
+	 */
230
+	public function copyTemplate($template, $destination, $data=[], $overwrite=false)
231
+	{
232
+		if (! is_array($data))
233
+		{
234
+			$data = array($data);
235
+		}
236
+
237
+		$content = $this->render($template, $data);
238
+
239
+		return $this->createFile($destination, $content, $overwrite);
240
+	}
241
+
242
+	//--------------------------------------------------------------------
243
+
244
+
245
+	/**
246
+	 * Injects a block of code into an existing file. Using options
247
+	 * you can specify where the code should be inserted. Available options
248
+	 * are:
249
+	 *      prepend         - Place at beginning of file
250
+	 *      append          - Place at end of file
251
+	 *      before  => ''   - Insert just prior to this line of text (don't forget the line ending "\n")
252
+	 *      after   => ''   - Insert just after this line of text (don't forget the line ending "\n")
253
+	 *      replace => ''   - a simple string to be replaced. All locations will be replaced.
254
+	 *      regex   => ''   - a pregex pattern to use to replace all locations.
255
+	 *
256
+	 * @param $path
257
+	 * @param $content
258
+	 * @param array $options
259
+	 *
260
+	 * @return $this
261
+	 */
262
+	public function injectIntoFile($path, $content, $options='append')
263
+	{
264
+		$kit = new FileKit();
265
+
266
+		if (is_string($options))
267
+		{
268
+			$action = $options;
269
+		}
270
+		else if (is_array($options) && count($options))
271
+		{
272
+			$keys = array_keys($options);
273
+			$action = array_shift( $keys );
274
+			$param = $options[$action];
275
+		}
276
+
277
+		switch ( strtolower($action) )
278
+		{
279
+			case 'prepend':
280
+				$success = $kit->prepend($path, $content);
281
+				break;
282
+			case 'before':
283
+				$success = $kit->before($path, $param, $content);
284
+				break;
285
+			case 'after':
286
+				$success = $kit->after($path, $param, $content);
287
+				break;
288
+			case 'replace':
289
+				$success = $kit->replaceIn($path, $param, $content);
290
+				break;
291
+			case 'regex':
292
+				$success = $kit->replaceWithRegex($path, $param, $content);
293
+				break;
294
+			case 'append':
295
+			default:
296
+				$success = $kit->append($path, $content);
297
+				break;
298
+		}
299
+
300
+		if ($success)
301
+		{
302
+			CLI::write( CLI::color("\t". strtolower( lang('modified') ) ." ", 'cyan') . str_replace(APPPATH, '', $path ) );
303
+		}
304
+		else
305
+		{
306
+			CLI::write( CLI::color("\t". strtolower( lang('error') ) ." ", 'light_red') . str_replace(APPPATH, '', $path ) );
307
+		}
308
+
309
+		return $this;
310
+	}
311 311
     
312
-    //--------------------------------------------------------------------
312
+	//--------------------------------------------------------------------
313 313
 
314 314
 	/**
315 315
 	 * Runs another generator. The first parameter is the name of the
@@ -320,130 +320,130 @@  discard block
 block discarded – undo
320 320
 	 * @param $command
321 321
 	 * @param null $options
322 322
 	 */
323
-    public function generate($command, $options = '', $quiet=false)
324
-    {
323
+	public function generate($command, $options = '', $quiet=false)
324
+	{
325 325
 		$orig_options = CLI::optionString();
326
-	    $options = $orig_options .' '. $options;
327
-
328
-	    if ($quiet === true)
329
-	    {
330
-		    $options .= ' -quiet';
331
-	    }
332
-
333
-	    if ($this->overwrite === true)
334
-	    {
335
-		    $options .= ' -overwrite';
336
-	    }
337
-
338
-	    passthru( "php sprint forge {$command} {$options}" );
339
-    }
340
-
341
-    //--------------------------------------------------------------------
342
-
343
-    /**
344
-     * Adds a new route to the application's route file.
345
-     *
346
-     * @param $left
347
-     * @param $right
348
-     *
349
-     * @return \Myth\Forge\BaseGenerator
350
-     */
351
-    public function route($left, $right, $options=[], $method='any')
352
-    {
353
-        $option_str = '[';
354
-
355
-        foreach ($options as $key => $value)
356
-        {
357
-            $option_str .= "";
358
-        }
359
-
360
-        $option_str .= ']';
361
-
362
-        $content = "\$routes->{$method}('{$left}', '{$right}', {$option_str});\n";
363
-
364
-        return $this->injectIntoFile(APPPATH .'config/routes.php', $content, ['after' => "// Auto-generated routes go here\n"]);
365
-    }
326
+		$options = $orig_options .' '. $options;
327
+
328
+		if ($quiet === true)
329
+		{
330
+			$options .= ' -quiet';
331
+		}
332
+
333
+		if ($this->overwrite === true)
334
+		{
335
+			$options .= ' -overwrite';
336
+		}
337
+
338
+		passthru( "php sprint forge {$command} {$options}" );
339
+	}
340
+
341
+	//--------------------------------------------------------------------
342
+
343
+	/**
344
+	 * Adds a new route to the application's route file.
345
+	 *
346
+	 * @param $left
347
+	 * @param $right
348
+	 *
349
+	 * @return \Myth\Forge\BaseGenerator
350
+	 */
351
+	public function route($left, $right, $options=[], $method='any')
352
+	{
353
+		$option_str = '[';
354
+
355
+		foreach ($options as $key => $value)
356
+		{
357
+			$option_str .= "";
358
+		}
359
+
360
+		$option_str .= ']';
361
+
362
+		$content = "\$routes->{$method}('{$left}', '{$right}', {$option_str});\n";
363
+
364
+		return $this->injectIntoFile(APPPATH .'config/routes.php', $content, ['after' => "// Auto-generated routes go here\n"]);
365
+	}
366 366
     
367
-    //--------------------------------------------------------------------
367
+	//--------------------------------------------------------------------
368 368
 
369
-    /**
370
-     * Outputs the contents of the file in the template's source path.
371
-     */
372
-    public function readme($file='readme.txt')
373
-    {
374
-	    $name = str_replace('Generator', '', get_class($this));
369
+	/**
370
+	 * Outputs the contents of the file in the template's source path.
371
+	 */
372
+	public function readme($file='readme.txt')
373
+	{
374
+		$name = str_replace('Generator', '', get_class($this));
375 375
 
376
-	    $path = $this->locateGenerator($name);
376
+		$path = $this->locateGenerator($name);
377 377
 
378
-        if (! file_exists($path . $file))
379
-        {
380
-            CLI::error(sprintf( lang('forge.cant_find_readme'), $file) );
381
-        }
378
+		if (! file_exists($path . $file))
379
+		{
380
+			CLI::error(sprintf( lang('forge.cant_find_readme'), $file) );
381
+		}
382 382
 
383
-	    $contents = file_get_contents($path . $file);
383
+		$contents = file_get_contents($path . $file);
384 384
 
385
-        CLI::new_line(2);
386
-        CLI::write( CLI::wrap($contents), 'green' );
387
-        CLI::new_line();
388
-    }
385
+		CLI::new_line(2);
386
+		CLI::write( CLI::wrap($contents), 'green' );
387
+		CLI::new_line();
388
+	}
389 389
 
390
-    //--------------------------------------------------------------------
390
+	//--------------------------------------------------------------------
391 391
 
392
-    /**
393
-     * Renders a single generator template. The file must be in a folder
394
-     * under the template group named the same as $this->generator_name.
395
-     * The file must have a '.tpl.php' file extension.
396
-     *
397
-     * @param $template_name
398
-     * @param array $data
399
-     *
400
-     * @return string The rendered template
401
-     */
402
-    public function render($template_name, $data=[], $folder=null)
403
-    {
404
-        if (empty($this->themer))
405
-        {
406
-            $this->setupThemer();
407
-        }
392
+	/**
393
+	 * Renders a single generator template. The file must be in a folder
394
+	 * under the template group named the same as $this->generator_name.
395
+	 * The file must have a '.tpl.php' file extension.
396
+	 *
397
+	 * @param $template_name
398
+	 * @param array $data
399
+	 *
400
+	 * @return string The rendered template
401
+	 */
402
+	public function render($template_name, $data=[], $folder=null)
403
+	{
404
+		if (empty($this->themer))
405
+		{
406
+			$this->setupThemer();
407
+		}
408 408
 
409
-	    $data['uikit'] = $this->loadUIKit();
409
+		$data['uikit'] = $this->loadUIKit();
410 410
 
411
-        $output = null;
411
+		$output = null;
412 412
 
413
-	    $view = $template_name .'.tpl';
413
+		$view = $template_name .'.tpl';
414 414
 
415
-        $groups = config_item('forge.collections');
415
+		$groups = config_item('forge.collections');
416 416
 
417
-	    $name = str_replace('Generator', '', get_class($this) );
417
+		$name = str_replace('Generator', '', get_class($this) );
418 418
 
419
-        foreach ($groups as $group => $path)
420
-        {
421
-	        $path = rtrim($path, '/ ') .'/';
422
-	        $folders = scandir($path);
419
+		foreach ($groups as $group => $path)
420
+		{
421
+			$path = rtrim($path, '/ ') .'/';
422
+			$folders = scandir($path);
423 423
 
424
-	        if (! $i = array_search(ucfirst($name), $folders))
425
-	        {
426
-		        continue;
427
-	        }
424
+			if (! $i = array_search(ucfirst($name), $folders))
425
+			{
426
+				continue;
427
+			}
428 428
 
429
-	        $view = $folders[$i] . '/'. $view;
429
+			$view = $folders[$i] . '/'. $view;
430 430
 
431
-            if (realpath($path . $view .'.php'))
432
-            {
433
-                $output = $this->themer->display($group .':'. $view, $data);
434
-                break;
435
-            }
436
-        }
431
+			if (realpath($path . $view .'.php'))
432
+			{
433
+				$output = $this->themer->display($group .':'. $view, $data);
434
+				break;
435
+			}
436
+		}
437 437
 
438
-	    // To allow for including any PHP code in the templates,
439
-	    // replace any '@php' and '@=' tags with their correct PHP syntax.
440
-	    $output = str_replace('@php', '<?php', $output);
441
-	    $output = str_replace('@=', '<?=', $output);
438
+		// To allow for including any PHP code in the templates,
439
+		// replace any '@php' and '@=' tags with their correct PHP syntax.
440
+		$output = str_replace('@php', '<?php', $output);
441
+		$output = str_replace('@=', '<?=', $output);
442 442
 
443
-        return $output;
444
-    }
443
+		return $output;
444
+	}
445 445
 
446
-    //--------------------------------------------------------------------
446
+	//--------------------------------------------------------------------
447 447
 
448 448
 	/**
449 449
 	 * Forces a path to exist within the current application's folder.
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 	 */
459 459
 	public function sandbox($path)
460 460
 	{
461
-        $path = $this->normalizePath($path);
461
+		$path = $this->normalizePath($path);
462 462
 
463 463
 		// If it's writing to BASEPATH - FIX IT
464 464
 		if (strpos($path, $this->normalizePath(BASEPATH) ) === 0)
@@ -478,37 +478,37 @@  discard block
 block discarded – undo
478 478
 			return $path;
479 479
 		}
480 480
 
481
-	    return APPPATH . $path;
481
+		return APPPATH . $path;
482 482
 	}
483 483
 
484 484
 	//--------------------------------------------------------------------
485 485
 
486 486
 
487 487
 
488
-    //--------------------------------------------------------------------
489
-    // Private Methods
490
-    //--------------------------------------------------------------------
488
+	//--------------------------------------------------------------------
489
+	// Private Methods
490
+	//--------------------------------------------------------------------
491 491
 
492
-    protected function setupThemer()
493
-    {
494
-        $themer_name = config_item('forge.themer');
492
+	protected function setupThemer()
493
+	{
494
+		$themer_name = config_item('forge.themer');
495 495
 
496
-        if (! $themer_name)
497
-        {
498
-            throw new \RuntimeException( lang('forge.no_themer') );
499
-        }
496
+		if (! $themer_name)
497
+		{
498
+			throw new \RuntimeException( lang('forge.no_themer') );
499
+		}
500 500
 
501
-        $this->themer = new $themer_name( get_instance() );
501
+		$this->themer = new $themer_name( get_instance() );
502 502
 
503
-        // Register our paths with the themer
504
-        $paths = config_item('forge.collections');
503
+		// Register our paths with the themer
504
+		$paths = config_item('forge.collections');
505 505
 
506
-        foreach ($paths as $key => $path) {
507
-            $this->themer->addThemePath($key, $path);
508
-        }
509
-    }
506
+		foreach ($paths as $key => $path) {
507
+			$this->themer->addThemePath($key, $path);
508
+		}
509
+	}
510 510
 
511
-    //--------------------------------------------------------------------
511
+	//--------------------------------------------------------------------
512 512
 
513 513
 	public function loadUIKit()
514 514
 	{
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 		$uikit = new $kit_name();
523 523
 
524
-	    return $uikit;
524
+		return $uikit;
525 525
 	}
526 526
 
527 527
 	//--------------------------------------------------------------------
@@ -639,66 +639,66 @@  discard block
 block discarded – undo
639 639
 
640 640
 	//--------------------------------------------------------------------
641 641
 
642
-    /**
643
-     * Normalizes a path and cleans it up for healthy use within
644
-     * realpath() and helps to mitigate changes between Windows and *nix
645
-     * operating systems.
646
-     *
647
-     * Found at http://php.net/manual/en/function.realpath.php#112367
648
-     *
649
-     * @param $path
650
-     *
651
-     * @return string
652
-     */
653
-    protected function normalizePath($path)
654
-    {
655
-        // Array to build a new path from the good parts
656
-        $parts = array();
657
-
658
-        // Replace backslashes with forward slashes
659
-        $path = str_replace('\\', '/', $path);
660
-
661
-        // Combine multiple slashes into a single slash
662
-        $path = preg_replace('/\/+/', '/', $path);
663
-
664
-        // Collect path segments
665
-        $segments = explode('/', $path);
666
-
667
-        // Initialize testing variable
668
-        $test = '';
669
-
670
-        foreach($segments as $segment)
671
-        {
672
-            if($segment != '.')
673
-            {
674
-                $test = array_pop($parts);
675
-
676
-                if(is_null($test))
677
-                {
678
-                    $parts[] = $segment;
679
-                }
680
-                else if ($segment == '..')
681
-                {
682
-                    if ($test == '..')
683
-                    {
684
-                        $parts[] = $test;
685
-                    }
686
-
687
-                    if ($test == '..' || $test == '')
688
-                    {
689
-                        $parts[] = $segment;
690
-                    }
691
-                }
692
-                else
693
-                {
694
-                    $parts[] = $test;
695
-                    $parts[] = $segment;
696
-                }
697
-            }
698
-        }
699
-        return implode('/', $parts);
700
-    }
701
-
702
-    //--------------------------------------------------------------------
642
+	/**
643
+	 * Normalizes a path and cleans it up for healthy use within
644
+	 * realpath() and helps to mitigate changes between Windows and *nix
645
+	 * operating systems.
646
+	 *
647
+	 * Found at http://php.net/manual/en/function.realpath.php#112367
648
+	 *
649
+	 * @param $path
650
+	 *
651
+	 * @return string
652
+	 */
653
+	protected function normalizePath($path)
654
+	{
655
+		// Array to build a new path from the good parts
656
+		$parts = array();
657
+
658
+		// Replace backslashes with forward slashes
659
+		$path = str_replace('\\', '/', $path);
660
+
661
+		// Combine multiple slashes into a single slash
662
+		$path = preg_replace('/\/+/', '/', $path);
663
+
664
+		// Collect path segments
665
+		$segments = explode('/', $path);
666
+
667
+		// Initialize testing variable
668
+		$test = '';
669
+
670
+		foreach($segments as $segment)
671
+		{
672
+			if($segment != '.')
673
+			{
674
+				$test = array_pop($parts);
675
+
676
+				if(is_null($test))
677
+				{
678
+					$parts[] = $segment;
679
+				}
680
+				else if ($segment == '..')
681
+				{
682
+					if ($test == '..')
683
+					{
684
+						$parts[] = $test;
685
+					}
686
+
687
+					if ($test == '..' || $test == '')
688
+					{
689
+						$parts[] = $segment;
690
+					}
691
+				}
692
+				else
693
+				{
694
+					$parts[] = $test;
695
+					$parts[] = $segment;
696
+				}
697
+			}
698
+		}
699
+		return implode('/', $parts);
700
+	}
701
+
702
+	//--------------------------------------------------------------------
703 703
 
704 704
 }
Please login to merge, or discard this patch.