Completed
Push — master ( 8df45b...9d0042 )
by Sherif
02:28 queued 11s
created
src/Modules/Roles/Http/Controllers/RoleController.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -10,51 +10,51 @@
 block discarded – undo
10 10
 
11 11
 class RoleController extends BaseApiController
12 12
 {
13
-    /**
14
-     * List of all route actions that the base api controller
15
-     * will skip permissions check for them.
16
-     * @var array
17
-     */
18
-    protected $skipPermissionCheck = [];
13
+	/**
14
+	 * List of all route actions that the base api controller
15
+	 * will skip permissions check for them.
16
+	 * @var array
17
+	 */
18
+	protected $skipPermissionCheck = [];
19 19
 
20
-    /**
21
-     * List of all route actions that the base api controller
22
-     * will skip login check for them.
23
-     * @var array
24
-     */
25
-    protected $skipLoginCheck = [];
20
+	/**
21
+	 * List of all route actions that the base api controller
22
+	 * will skip login check for them.
23
+	 * @var array
24
+	 */
25
+	protected $skipLoginCheck = [];
26 26
 
27
-    /**
28
-     * Init new object.
29
-     *
30
-     * @param   RoleRepository $repo
31
-     * @param   CoreConfig      $config
32
-     * @return  void
33
-     */
34
-    public function __construct(RoleRepository $repo, CoreConfig $config)
35
-    {
36
-        parent::__construct($repo, $config, 'App\Modules\Roles\Http\Resources\Role');
37
-    }
27
+	/**
28
+	 * Init new object.
29
+	 *
30
+	 * @param   RoleRepository $repo
31
+	 * @param   CoreConfig      $config
32
+	 * @return  void
33
+	 */
34
+	public function __construct(RoleRepository $repo, CoreConfig $config)
35
+	{
36
+		parent::__construct($repo, $config, 'App\Modules\Roles\Http\Resources\Role');
37
+	}
38 38
 
39
-    /**
40
-     * Insert the given model to storage.
41
-     *
42
-     * @param InsertRole $request
43
-     * @return \Illuminate\Http\Response
44
-     */
45
-    public function insert(InsertRole $request)
46
-    {
47
-        return new $this->modelResource($this->repo->save($request->all()));
48
-    }
39
+	/**
40
+	 * Insert the given model to storage.
41
+	 *
42
+	 * @param InsertRole $request
43
+	 * @return \Illuminate\Http\Response
44
+	 */
45
+	public function insert(InsertRole $request)
46
+	{
47
+		return new $this->modelResource($this->repo->save($request->all()));
48
+	}
49 49
 
50
-    /**
51
-     * Update the given model to storage.
52
-     *
53
-     * @param UpdateRole $request
54
-     * @return \Illuminate\Http\Response
55
-     */
56
-    public function update(UpdateRole $request)
57
-    {
58
-        return new $this->modelResource($this->repo->save($request->all()));
59
-    }
50
+	/**
51
+	 * Update the given model to storage.
52
+	 *
53
+	 * @param UpdateRole $request
54
+	 * @return \Illuminate\Http\Response
55
+	 */
56
+	public function update(UpdateRole $request)
57
+	{
58
+		return new $this->modelResource($this->repo->save($request->all()));
59
+	}
60 60
 }
Please login to merge, or discard this patch.
src/Modules/Roles/Reppsitories/RoleRepository.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -5,14 +5,14 @@
 block discarded – undo
5 5
 
6 6
 class RoleRepository extends BaseRepository
7 7
 {
8
-    /**
9
-     * Init new object.
10
-     *
11
-     * @param   Role $model
12
-     * @return  void
13
-     */
14
-    public function __construct(Role $model)
15
-    {
16
-        parent::__construct($model);
17
-    }
8
+	/**
9
+	 * Init new object.
10
+	 *
11
+	 * @param   Role $model
12
+	 * @return  void
13
+	 */
14
+	public function __construct(Role $model)
15
+	{
16
+		parent::__construct($model);
17
+	}
18 18
 }
Please login to merge, or discard this patch.
src/Modules/Roles/Routes/api.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -15,11 +15,11 @@
 block discarded – undo
15 15
 
16 16
 Route::group(['prefix' => 'roles'], function () {
17 17
 
18
-    Route::get('/', 'RoleController@index');
19
-    Route::get('/{id}', 'RoleController@find');
20
-    Route::post('/', 'RoleController@insert');
21
-    Route::put('/', 'RoleController@update');
22
-    Route::delete('/{id}', 'RoleController@delete');
23
-    Route::get('list/deleted', 'RoleController@deleted');
24
-    Route::patch('restore/{id}', 'RoleController@restore');
18
+	Route::get('/', 'RoleController@index');
19
+	Route::get('/{id}', 'RoleController@find');
20
+	Route::post('/', 'RoleController@insert');
21
+	Route::put('/', 'RoleController@update');
22
+	Route::delete('/{id}', 'RoleController@delete');
23
+	Route::get('list/deleted', 'RoleController@deleted');
24
+	Route::patch('restore/{id}', 'RoleController@restore');
25 25
 });
Please login to merge, or discard this patch.
src/Modules/Users/Reppsitories/UserRepository.php 1 patch
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -6,391 +6,391 @@
 block discarded – undo
6 6
 
7 7
 class UserRepository extends BaseRepository
8 8
 {
9
-    /**
10
-     * Init new object.
11
-     *
12
-     * @param   AclUser $model
13
-     * @return  void
14
-     */
15
-    public function __construct(AclUser $model)
16
-    {
17
-        parent::__construct($model);
18
-    }
19
-
20
-    /**
21
-     * Return the logged in user account.
22
-     *
23
-     * @param  array   $relations
24
-     * @return boolean
25
-     */
26
-    public function account($relations = [])
27
-    {
28
-        $permissions = [];
29
-        $user        = $this->find(\Auth::id(), $relations);
30
-        foreach ($user->groups()->get() as $group) {
31
-            $group->permissions->each(function ($permission) use (&$permissions) {
32
-                $permissions[$permission->model][$permission->id] = $permission->name;
33
-            });
34
-        }
35
-        $user->permissions = $permissions;
36
-
37
-        return $user;
38
-    }
39
-
40
-    /**
41
-     * Check if the logged in user or the given user
42
-     * has the given permissions on the given model.
43
-     *
44
-     * @param  string $nameOfPermission
45
-     * @param  string $model
46
-     * @param  mixed  $user
47
-     * @return boolean
48
-     */
49
-    public function can($nameOfPermission, $model, $user = false)
50
-    {
51
-        $user        = $user ?: $this->find(\Auth::id(), ['groups.permissions']);
52
-        $permissions = [];
53
-
54
-        $user->groups->pluck('permissions')->each(function ($permission) use (&$permissions, $model) {
55
-            $permissions = array_merge($permissions, $permission->where('model', $model)->pluck('name')->toArray());
56
-        });
57
-
58
-        return in_array($nameOfPermission, $permissions);
59
-    }
60
-
61
-    /**
62
-     * Check if the logged in user has the given group.
63
-     *
64
-     * @param  string[] $groups
65
-     * @param  mixed $user
66
-     * @return boolean
67
-     */
68
-    public function hasGroup($groups, $user = false)
69
-    {
70
-        $user = $user ?: $this->find(\Auth::id());
71
-        return $user->groups->whereIn('name', $groups)->count() ? true : false;
72
-    }
73
-
74
-    /**
75
-     * Assign the given group ids to the given user.
76
-     *
77
-     * @param  integer $userId
78
-     * @param  array   $groupIds
79
-     * @return object
80
-     */
81
-    public function assignGroups($userId, $groupIds)
82
-    {
83
-        \DB::transaction(function () use ($userId, $groupIds) {
84
-            $user = $this->find($userId);
85
-            $user->groups()->detach();
86
-            $user->groups()->attach($groupIds);
87
-        });
88
-
89
-        return $this->find($userId);
90
-    }
91
-
92
-
93
-    /**
94
-     * Handle a login request to the application.
95
-     *
96
-     * @param  array   $credentials
97
-     * @param  boolean $adminLogin
98
-     * @return object
99
-     */
100
-    public function login($credentials, $adminLogin = false)
101
-    {
102
-        if (! $user = $this->first(['email' => $credentials['email']])) {
103
-            \ErrorHandler::loginFailed();
104
-        } elseif ($adminLogin && ! $user->groups->whereIn('name', ['Admin'])->count()) {
105
-            \ErrorHandler::loginFailed();
106
-        } elseif (! $adminLogin && $user->groups->whereIn('name', ['Admin'])->count()) {
107
-            \ErrorHandler::loginFailed();
108
-        } elseif ($user->blocked) {
109
-            \ErrorHandler::userIsBlocked();
110
-        } elseif (! config('skeleton.disable_confirm_email') && ! $user->confirmed) {
111
-            \ErrorHandler::emailNotConfirmed();
112
-        }
113
-
114
-        return $user;
115
-    }
116
-
117
-    /**
118
-     * Handle a social login request of the none admin to the application.
119
-     *
120
-     * @param  string $authCode
121
-     * @param  string $accessToken
122
-     * @param  string $type
123
-     * @return array
124
-     */
125
-    public function loginSocial($authCode, $accessToken, $type)
126
-    {
127
-        $access_token = $authCode ? Arr::get(\Socialite::driver($type)->getAccessTokenResponse($authCode), 'access_token') : $accessToken;
128
-        $user         = \Socialite::driver($type)->userFromToken($access_token);
129
-
130
-        if (! $user->email) {
131
-            \ErrorHandler::noSocialEmail();
132
-        }
133
-
134
-        if (! $this->model->where('email', $user->email)->first()) {
135
-            $this->register(['email' => $user->email, 'password' => ''], true);
136
-        }
137
-
138
-        $loginProxy = \App::make('App\Modules\Users\Proxy\LoginProxy');
139
-        return $loginProxy->login(['email' => $user->email, 'password' => config('skeleton.social_pass')], 0);
140
-    }
9
+	/**
10
+	 * Init new object.
11
+	 *
12
+	 * @param   AclUser $model
13
+	 * @return  void
14
+	 */
15
+	public function __construct(AclUser $model)
16
+	{
17
+		parent::__construct($model);
18
+	}
19
+
20
+	/**
21
+	 * Return the logged in user account.
22
+	 *
23
+	 * @param  array   $relations
24
+	 * @return boolean
25
+	 */
26
+	public function account($relations = [])
27
+	{
28
+		$permissions = [];
29
+		$user        = $this->find(\Auth::id(), $relations);
30
+		foreach ($user->groups()->get() as $group) {
31
+			$group->permissions->each(function ($permission) use (&$permissions) {
32
+				$permissions[$permission->model][$permission->id] = $permission->name;
33
+			});
34
+		}
35
+		$user->permissions = $permissions;
36
+
37
+		return $user;
38
+	}
39
+
40
+	/**
41
+	 * Check if the logged in user or the given user
42
+	 * has the given permissions on the given model.
43
+	 *
44
+	 * @param  string $nameOfPermission
45
+	 * @param  string $model
46
+	 * @param  mixed  $user
47
+	 * @return boolean
48
+	 */
49
+	public function can($nameOfPermission, $model, $user = false)
50
+	{
51
+		$user        = $user ?: $this->find(\Auth::id(), ['groups.permissions']);
52
+		$permissions = [];
53
+
54
+		$user->groups->pluck('permissions')->each(function ($permission) use (&$permissions, $model) {
55
+			$permissions = array_merge($permissions, $permission->where('model', $model)->pluck('name')->toArray());
56
+		});
57
+
58
+		return in_array($nameOfPermission, $permissions);
59
+	}
60
+
61
+	/**
62
+	 * Check if the logged in user has the given group.
63
+	 *
64
+	 * @param  string[] $groups
65
+	 * @param  mixed $user
66
+	 * @return boolean
67
+	 */
68
+	public function hasGroup($groups, $user = false)
69
+	{
70
+		$user = $user ?: $this->find(\Auth::id());
71
+		return $user->groups->whereIn('name', $groups)->count() ? true : false;
72
+	}
73
+
74
+	/**
75
+	 * Assign the given group ids to the given user.
76
+	 *
77
+	 * @param  integer $userId
78
+	 * @param  array   $groupIds
79
+	 * @return object
80
+	 */
81
+	public function assignGroups($userId, $groupIds)
82
+	{
83
+		\DB::transaction(function () use ($userId, $groupIds) {
84
+			$user = $this->find($userId);
85
+			$user->groups()->detach();
86
+			$user->groups()->attach($groupIds);
87
+		});
88
+
89
+		return $this->find($userId);
90
+	}
91
+
92
+
93
+	/**
94
+	 * Handle a login request to the application.
95
+	 *
96
+	 * @param  array   $credentials
97
+	 * @param  boolean $adminLogin
98
+	 * @return object
99
+	 */
100
+	public function login($credentials, $adminLogin = false)
101
+	{
102
+		if (! $user = $this->first(['email' => $credentials['email']])) {
103
+			\ErrorHandler::loginFailed();
104
+		} elseif ($adminLogin && ! $user->groups->whereIn('name', ['Admin'])->count()) {
105
+			\ErrorHandler::loginFailed();
106
+		} elseif (! $adminLogin && $user->groups->whereIn('name', ['Admin'])->count()) {
107
+			\ErrorHandler::loginFailed();
108
+		} elseif ($user->blocked) {
109
+			\ErrorHandler::userIsBlocked();
110
+		} elseif (! config('skeleton.disable_confirm_email') && ! $user->confirmed) {
111
+			\ErrorHandler::emailNotConfirmed();
112
+		}
113
+
114
+		return $user;
115
+	}
116
+
117
+	/**
118
+	 * Handle a social login request of the none admin to the application.
119
+	 *
120
+	 * @param  string $authCode
121
+	 * @param  string $accessToken
122
+	 * @param  string $type
123
+	 * @return array
124
+	 */
125
+	public function loginSocial($authCode, $accessToken, $type)
126
+	{
127
+		$access_token = $authCode ? Arr::get(\Socialite::driver($type)->getAccessTokenResponse($authCode), 'access_token') : $accessToken;
128
+		$user         = \Socialite::driver($type)->userFromToken($access_token);
129
+
130
+		if (! $user->email) {
131
+			\ErrorHandler::noSocialEmail();
132
+		}
133
+
134
+		if (! $this->model->where('email', $user->email)->first()) {
135
+			$this->register(['email' => $user->email, 'password' => ''], true);
136
+		}
137
+
138
+		$loginProxy = \App::make('App\Modules\Users\Proxy\LoginProxy');
139
+		return $loginProxy->login(['email' => $user->email, 'password' => config('skeleton.social_pass')], 0);
140
+	}
141 141
     
142
-    /**
143
-     * Handle a registration request.
144
-     *
145
-     * @param  array   $credentials
146
-     * @param  boolean $skipConfirmEmail
147
-     * @return boolean
148
-     */
149
-    public function register($credentials, $skipConfirmEmail = false)
150
-    {
151
-        $user = $this->save($credentials);
152
-
153
-        if ($skipConfirmEmail) {
154
-            $user->confirmed = 1;
155
-            $user->save();
156
-        } elseif (! config('skeleton.disable_confirm_email')) {
157
-            $this->sendConfirmationEmail($user->email);
158
-        }
159
-
160
-        return $user;
161
-    }
142
+	/**
143
+	 * Handle a registration request.
144
+	 *
145
+	 * @param  array   $credentials
146
+	 * @param  boolean $skipConfirmEmail
147
+	 * @return boolean
148
+	 */
149
+	public function register($credentials, $skipConfirmEmail = false)
150
+	{
151
+		$user = $this->save($credentials);
152
+
153
+		if ($skipConfirmEmail) {
154
+			$user->confirmed = 1;
155
+			$user->save();
156
+		} elseif (! config('skeleton.disable_confirm_email')) {
157
+			$this->sendConfirmationEmail($user->email);
158
+		}
159
+
160
+		return $user;
161
+	}
162 162
     
163
-    /**
164
-     * Block the user.
165
-     *
166
-     * @param  integer $userId
167
-     * @return object
168
-     */
169
-    public function block($userId)
170
-    {
171
-        if (! $user = $this->find($userId)) {
172
-            \ErrorHandler::notFound('user');
173
-        }
174
-        if (! $this->hasGroup(['Admin'])) {
175
-            \ErrorHandler::noPermissions();
176
-        } elseif (\Auth::id() == $userId) {
177
-            \ErrorHandler::noPermissions();
178
-        } elseif ($user->groups->pluck('name')->search('Admin', true) !== false) {
179
-            \ErrorHandler::noPermissions();
180
-        }
181
-
182
-        $user->blocked = 1;
183
-        $user->save();
163
+	/**
164
+	 * Block the user.
165
+	 *
166
+	 * @param  integer $userId
167
+	 * @return object
168
+	 */
169
+	public function block($userId)
170
+	{
171
+		if (! $user = $this->find($userId)) {
172
+			\ErrorHandler::notFound('user');
173
+		}
174
+		if (! $this->hasGroup(['Admin'])) {
175
+			\ErrorHandler::noPermissions();
176
+		} elseif (\Auth::id() == $userId) {
177
+			\ErrorHandler::noPermissions();
178
+		} elseif ($user->groups->pluck('name')->search('Admin', true) !== false) {
179
+			\ErrorHandler::noPermissions();
180
+		}
181
+
182
+		$user->blocked = 1;
183
+		$user->save();
184 184
         
185
-        return $user;
186
-    }
187
-
188
-    /**
189
-     * Unblock the user.
190
-     *
191
-     * @param  integer $userId
192
-     * @return object
193
-     */
194
-    public function unblock($userId)
195
-    {
196
-        if (! $this->hasGroup(['Admin'])) {
197
-            \ErrorHandler::noPermissions();
198
-        }
199
-
200
-        $user          = $this->find($userId);
201
-        $user->blocked = 0;
202
-        $user->save();
203
-
204
-        return $user;
205
-    }
206
-
207
-    /**
208
-     * Send a reset link to the given user.
209
-     *
210
-     * @param  string  $email
211
-     * @return void
212
-     */
213
-    public function sendReset($email)
214
-    {
215
-        if (! $user = $this->model->where('email', $email)->first()) {
216
-            \ErrorHandler::notFound('email');
217
-        }
218
-
219
-        $token = \Password::getRepository()->create($user);
220
-        \Core::notifications()->notify($user, 'ResetPassword', $token);
221
-    }
222
-
223
-    /**
224
-     * Reset the given user's password.
225
-     *
226
-     * @param  array  $credentials
227
-     * @return string|null
228
-     */
229
-    public function resetPassword($credentials)
230
-    {
231
-        $response = \Password::reset($credentials, function ($user, $password) {
232
-            $user->password = $password;
233
-            $user->save();
234
-        });
235
-
236
-        switch ($response) {
237
-            case \Password::PASSWORD_RESET:
238
-                return 'success';
239
-
240
-            case \Password::INVALID_TOKEN:
241
-                \ErrorHandler::invalidResetToken('token');
242
-                //no break
243
-
244
-            case \Password::INVALID_PASSWORD:
245
-                \ErrorHandler::invalidResetPassword('email');
246
-                //no break
247
-
248
-            case \Password::INVALID_USER:
249
-                \ErrorHandler::notFound('user');
250
-                //no break
251
-
252
-            default:
253
-                \ErrorHandler::generalError();
254
-        }
255
-    }
256
-
257
-    /**
258
-     * Change the logged in user password.
259
-     *
260
-     * @param  array  $credentials
261
-     * @return void
262
-     */
263
-    public function changePassword($credentials)
264
-    {
265
-        $user = \Auth::user();
266
-        if (! \Hash::check($credentials['old_password'], $user->password)) {
267
-            \ErrorHandler::invalidOldPassword();
268
-        }
269
-
270
-        $user->password = $credentials['password'];
271
-        $user->save();
272
-    }
273
-
274
-    /**
275
-     * Confirm email using the confirmation code.
276
-     *
277
-     * @param  string $confirmationCode
278
-     * @return void
279
-     */
280
-    public function confirmEmail($confirmationCode)
281
-    {
282
-        if (! $user = $this->first(['confirmation_code' => $confirmationCode])) {
283
-            \ErrorHandler::invalidConfirmationCode();
284
-        }
285
-
286
-        $user->confirmed         = 1;
287
-        $user->confirmation_code = null;
288
-        $user->save();
289
-    }
290
-
291
-    /**
292
-     * Send the confirmation mail.
293
-     *
294
-     * @param  string $email
295
-     * @return void
296
-     */
297
-    public function sendConfirmationEmail($email)
298
-    {
299
-        $user = $this->first(['email' => $email]);
300
-        if ($user->confirmed) {
301
-            \ErrorHandler::emailAlreadyConfirmed();
302
-        }
303
-
304
-        $user->confirmed         = 0;
305
-        $user->confirmation_code = sha1(microtime());
306
-        $user->save();
307
-        \Core::notifications()->notify($user, 'ConfirmEmail');
308
-    }
309
-
310
-    /**
311
-     * Paginate all users in the given group based on the given conditions.
312
-     *
313
-     * @param  string  $groupName
314
-     * @param  array   $relations
315
-     * @param  integer $perPage
316
-     * @param  string  $sortBy
317
-     * @param  boolean $desc
318
-     * @return \Illuminate\Http\Response
319
-     */
320
-    public function group($conditions, $groupName, $relations, $perPage, $sortBy, $desc)
321
-    {
322
-        unset($conditions['page']);
323
-        $conditions = $this->constructConditions($conditions, $this->model);
324
-        $sort       = $desc ? 'desc' : 'asc';
325
-        $model      = $this->model->with($relations);
326
-
327
-        $model->whereHas('groups', function ($q) use ($groupName) {
328
-            $q->where('name', $groupName);
329
-        });
185
+		return $user;
186
+	}
187
+
188
+	/**
189
+	 * Unblock the user.
190
+	 *
191
+	 * @param  integer $userId
192
+	 * @return object
193
+	 */
194
+	public function unblock($userId)
195
+	{
196
+		if (! $this->hasGroup(['Admin'])) {
197
+			\ErrorHandler::noPermissions();
198
+		}
199
+
200
+		$user          = $this->find($userId);
201
+		$user->blocked = 0;
202
+		$user->save();
203
+
204
+		return $user;
205
+	}
206
+
207
+	/**
208
+	 * Send a reset link to the given user.
209
+	 *
210
+	 * @param  string  $email
211
+	 * @return void
212
+	 */
213
+	public function sendReset($email)
214
+	{
215
+		if (! $user = $this->model->where('email', $email)->first()) {
216
+			\ErrorHandler::notFound('email');
217
+		}
218
+
219
+		$token = \Password::getRepository()->create($user);
220
+		\Core::notifications()->notify($user, 'ResetPassword', $token);
221
+	}
222
+
223
+	/**
224
+	 * Reset the given user's password.
225
+	 *
226
+	 * @param  array  $credentials
227
+	 * @return string|null
228
+	 */
229
+	public function resetPassword($credentials)
230
+	{
231
+		$response = \Password::reset($credentials, function ($user, $password) {
232
+			$user->password = $password;
233
+			$user->save();
234
+		});
235
+
236
+		switch ($response) {
237
+			case \Password::PASSWORD_RESET:
238
+				return 'success';
239
+
240
+			case \Password::INVALID_TOKEN:
241
+				\ErrorHandler::invalidResetToken('token');
242
+				//no break
243
+
244
+			case \Password::INVALID_PASSWORD:
245
+				\ErrorHandler::invalidResetPassword('email');
246
+				//no break
247
+
248
+			case \Password::INVALID_USER:
249
+				\ErrorHandler::notFound('user');
250
+				//no break
251
+
252
+			default:
253
+				\ErrorHandler::generalError();
254
+		}
255
+	}
256
+
257
+	/**
258
+	 * Change the logged in user password.
259
+	 *
260
+	 * @param  array  $credentials
261
+	 * @return void
262
+	 */
263
+	public function changePassword($credentials)
264
+	{
265
+		$user = \Auth::user();
266
+		if (! \Hash::check($credentials['old_password'], $user->password)) {
267
+			\ErrorHandler::invalidOldPassword();
268
+		}
269
+
270
+		$user->password = $credentials['password'];
271
+		$user->save();
272
+	}
273
+
274
+	/**
275
+	 * Confirm email using the confirmation code.
276
+	 *
277
+	 * @param  string $confirmationCode
278
+	 * @return void
279
+	 */
280
+	public function confirmEmail($confirmationCode)
281
+	{
282
+		if (! $user = $this->first(['confirmation_code' => $confirmationCode])) {
283
+			\ErrorHandler::invalidConfirmationCode();
284
+		}
285
+
286
+		$user->confirmed         = 1;
287
+		$user->confirmation_code = null;
288
+		$user->save();
289
+	}
290
+
291
+	/**
292
+	 * Send the confirmation mail.
293
+	 *
294
+	 * @param  string $email
295
+	 * @return void
296
+	 */
297
+	public function sendConfirmationEmail($email)
298
+	{
299
+		$user = $this->first(['email' => $email]);
300
+		if ($user->confirmed) {
301
+			\ErrorHandler::emailAlreadyConfirmed();
302
+		}
303
+
304
+		$user->confirmed         = 0;
305
+		$user->confirmation_code = sha1(microtime());
306
+		$user->save();
307
+		\Core::notifications()->notify($user, 'ConfirmEmail');
308
+	}
309
+
310
+	/**
311
+	 * Paginate all users in the given group based on the given conditions.
312
+	 *
313
+	 * @param  string  $groupName
314
+	 * @param  array   $relations
315
+	 * @param  integer $perPage
316
+	 * @param  string  $sortBy
317
+	 * @param  boolean $desc
318
+	 * @return \Illuminate\Http\Response
319
+	 */
320
+	public function group($conditions, $groupName, $relations, $perPage, $sortBy, $desc)
321
+	{
322
+		unset($conditions['page']);
323
+		$conditions = $this->constructConditions($conditions, $this->model);
324
+		$sort       = $desc ? 'desc' : 'asc';
325
+		$model      = $this->model->with($relations);
326
+
327
+		$model->whereHas('groups', function ($q) use ($groupName) {
328
+			$q->where('name', $groupName);
329
+		});
330 330
 
331 331
         
332
-        if (count($conditions['conditionValues'])) {
333
-            $model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
334
-        }
335
-
336
-        if ($perPage) {
337
-            return $model->orderBy($sortBy, $sort)->paginate($perPage);
338
-        }
339
-
340
-        return $model->orderBy($sortBy, $sort)->get();
341
-    }
342
-
343
-    /**
344
-     * Save the given data to the logged in user.
345
-     *
346
-     * @param  array $data
347
-     * @return boolean
348
-     */
349
-    public function saveProfile($data)
350
-    {
351
-        if (Arr::has($data, 'profile_picture')) {
352
-            $data['profile_picture'] = \Media::uploadImageBas64($data['profile_picture'], 'admins/profile_pictures');
353
-        }
332
+		if (count($conditions['conditionValues'])) {
333
+			$model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
334
+		}
335
+
336
+		if ($perPage) {
337
+			return $model->orderBy($sortBy, $sort)->paginate($perPage);
338
+		}
339
+
340
+		return $model->orderBy($sortBy, $sort)->get();
341
+	}
342
+
343
+	/**
344
+	 * Save the given data to the logged in user.
345
+	 *
346
+	 * @param  array $data
347
+	 * @return boolean
348
+	 */
349
+	public function saveProfile($data)
350
+	{
351
+		if (Arr::has($data, 'profile_picture')) {
352
+			$data['profile_picture'] = \Media::uploadImageBas64($data['profile_picture'], 'admins/profile_pictures');
353
+		}
354 354
         
355
-        $data['id'] = \Auth::id();
356
-        return $this->save($data);
357
-    }
358
-
359
-    /**
360
-     * Ensure access token hasn't expired or revoked.
361
-     *
362
-     * @param  string $accessToken
363
-     * @return boolean
364
-     */
365
-    public function accessTokenExpiredOrRevoked($accessToken)
366
-    {
367
-        $accessTokenId = json_decode($accessToken, true)['id'];
368
-        $accessToken   = \DB::table('oauth_access_tokens')
369
-                ->where('id', $accessTokenId)
370
-                ->first();
355
+		$data['id'] = \Auth::id();
356
+		return $this->save($data);
357
+	}
358
+
359
+	/**
360
+	 * Ensure access token hasn't expired or revoked.
361
+	 *
362
+	 * @param  string $accessToken
363
+	 * @return boolean
364
+	 */
365
+	public function accessTokenExpiredOrRevoked($accessToken)
366
+	{
367
+		$accessTokenId = json_decode($accessToken, true)['id'];
368
+		$accessToken   = \DB::table('oauth_access_tokens')
369
+				->where('id', $accessTokenId)
370
+				->first();
371 371
         
372
-        if (\Carbon\Carbon::parse($accessToken->expires_at)->isPast() || $accessToken->revoked) {
373
-            return true;
374
-        }
375
-
376
-        return false;
377
-    }
378
-
379
-    /**
380
-     * Revoke the given access token and all
381
-     * associated refresh tokens.
382
-     *
383
-     * @param  oject $accessToken
384
-     * @return void
385
-     */
386
-    public function revokeAccessToken($accessToken)
387
-    {
388
-        \DB::table('oauth_refresh_tokens')
389
-            ->where('access_token_id', $accessToken->id)
390
-            ->update([
391
-                'revoked' => true
392
-            ]);
393
-
394
-        $accessToken->revoke();
395
-    }
372
+		if (\Carbon\Carbon::parse($accessToken->expires_at)->isPast() || $accessToken->revoked) {
373
+			return true;
374
+		}
375
+
376
+		return false;
377
+	}
378
+
379
+	/**
380
+	 * Revoke the given access token and all
381
+	 * associated refresh tokens.
382
+	 *
383
+	 * @param  oject $accessToken
384
+	 * @return void
385
+	 */
386
+	public function revokeAccessToken($accessToken)
387
+	{
388
+		\DB::table('oauth_refresh_tokens')
389
+			->where('access_token_id', $accessToken->id)
390
+			->update([
391
+				'revoked' => true
392
+			]);
393
+
394
+		$accessToken->revoke();
395
+	}
396 396
 }
Please login to merge, or discard this patch.
PushNotificationDevices/Repositories/PushNotificationDeviceRepository.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -8,60 +8,60 @@
 block discarded – undo
8 8
 
9 9
 class PushNotificationDeviceRepository extends BaseRepository
10 10
 {
11
-    /**
12
-     * Init new object.
13
-     *
14
-     * @param   PushNotificationDevice $model
15
-     * @return  void
16
-     */
17
-    public function __construct(PushNotificationDevice $model)
18
-    {
19
-        parent::__construct($model);
20
-    }
11
+	/**
12
+	 * Init new object.
13
+	 *
14
+	 * @param   PushNotificationDevice $model
15
+	 * @return  void
16
+	 */
17
+	public function __construct(PushNotificationDevice $model)
18
+	{
19
+		parent::__construct($model);
20
+	}
21 21
 
22
-    /**
23
-     * Register the given device to the logged in user.
24
-     *
25
-     * @param  array $data
26
-     * @return boolean
27
-     */
28
-    public function registerDevice($data)
29
-    {
30
-        $data['access_token'] = \Auth::user()->token();
31
-        $data['user_id']      = \Auth::id();
32
-        $device               = $this->model->where('device_token', $data['device_token'])->
33
-                                              where('user_id', $data['user_id'])->
34
-                                              first();
22
+	/**
23
+	 * Register the given device to the logged in user.
24
+	 *
25
+	 * @param  array $data
26
+	 * @return boolean
27
+	 */
28
+	public function registerDevice($data)
29
+	{
30
+		$data['access_token'] = \Auth::user()->token();
31
+		$data['user_id']      = \Auth::id();
32
+		$device               = $this->model->where('device_token', $data['device_token'])->
33
+											  where('user_id', $data['user_id'])->
34
+											  first();
35 35
 
36
-        if ($device) {
37
-            $data['id'] = $device->id;
38
-        }
36
+		if ($device) {
37
+			$data['id'] = $device->id;
38
+		}
39 39
 
40
-        return $this->save($data);
41
-    }
40
+		return $this->save($data);
41
+	}
42 42
 
43
-    /**
44
-     * Generate the given message data.
45
-     *
46
-     * @param  string $title
47
-     * @param  string $message
48
-     * @param  array  $data
49
-     * @return void
50
-     */
51
-    public function generateMessageData($title, $message, $data = [])
52
-    {
53
-        $optionBuilder       = new OptionsBuilder();
54
-        $notificationBuilder = new PayloadNotificationBuilder($title);
55
-        $dataBuilder         = new PayloadDataBuilder();
43
+	/**
44
+	 * Generate the given message data.
45
+	 *
46
+	 * @param  string $title
47
+	 * @param  string $message
48
+	 * @param  array  $data
49
+	 * @return void
50
+	 */
51
+	public function generateMessageData($title, $message, $data = [])
52
+	{
53
+		$optionBuilder       = new OptionsBuilder();
54
+		$notificationBuilder = new PayloadNotificationBuilder($title);
55
+		$dataBuilder         = new PayloadDataBuilder();
56 56
 
57
-        $optionBuilder->setTimeToLive(60 * 20);
58
-        $notificationBuilder->setBody($message);
59
-        $dataBuilder->addData($data);
57
+		$optionBuilder->setTimeToLive(60 * 20);
58
+		$notificationBuilder->setBody($message);
59
+		$dataBuilder->addData($data);
60 60
 
61
-        $options             = $optionBuilder->build();
62
-        $notification        = $notificationBuilder->build();
63
-        $data                = $dataBuilder->build();
61
+		$options             = $optionBuilder->build();
62
+		$notification        = $notificationBuilder->build();
63
+		$data                = $dataBuilder->build();
64 64
 
65
-        return compact('options', 'notification', 'data');
66
-    }
65
+		return compact('options', 'notification', 'data');
66
+	}
67 67
 }
Please login to merge, or discard this patch.
src/Modules/Core/Utl/ApiConsumer.php 1 patch
Indentation   +198 added lines, -198 removed lines patch added patch discarded remove patch
@@ -7,202 +7,202 @@
 block discarded – undo
7 7
 class ApiConsumer
8 8
 {
9 9
 
10
-    private $app;
11
-
12
-    private $router;
13
-
14
-    private $request;
15
-
16
-    private $disableMiddleware = false;
17
-
18
-    /**
19
-     * @param \Illuminate\Foundation\Application $app
20
-     * @param \Illuminate\Http\Request $request,
21
-     * @param \Illuminate\Routing\Router $router
22
-     */
23
-    public function __construct(Application $app, Request $request, LaravelRouter $router)
24
-    {
25
-        $this->app = $app;
26
-        $this->request = $request;
27
-        $this->router = $router;
28
-    }
29
-
30
-    /**
31
-     * @return \Illuminate\Http\Response
32
-     */
33
-    public function get()
34
-    {
35
-        return $this->quickCall('GET', func_get_args());
36
-    }
37
-
38
-    /**
39
-     * @return \Illuminate\Http\Response
40
-     */
41
-    public function post()
42
-    {
43
-        return $this->quickCall('POST', func_get_args());
44
-    }
45
-
46
-    /**
47
-     * @return \Illuminate\Http\Response
48
-     */
49
-    public function put()
50
-    {
51
-        return $this->quickCall('PUT', func_get_args());
52
-    }
53
-
54
-    /**
55
-     * @return \Illuminate\Http\Response
56
-     */
57
-    public function delete()
58
-    {
59
-        return $this->quickCall('DELETE', func_get_args());
60
-    }
61
-
62
-    /**
63
-     * @param  array $requests An array of requests
64
-     * @return array
65
-     */
66
-    public function batchRequest(array $requests)
67
-    {
68
-        foreach ($requests as $i => $request) {
69
-            $requests[$i] = call_user_func_array([$this, 'singleRequest'], $request);
70
-        }
71
-
72
-        return $requests;
73
-    }
74
-
75
-    /**
76
-     * @param  string $method
77
-     * @param  array  $args
78
-     * @return \Illuminate\Http\Response
79
-     */
80
-    public function quickCall($method, array $args)
81
-    {
82
-        array_unshift($args, $method);
83
-        return call_user_func_array([$this, "singleRequest"], $args);
84
-    }
85
-
86
-    /**
87
-     * @param  string $method
88
-     * @param  string $uri
89
-     * @param  array  $data
90
-     * @param  array  $headers
91
-     * @param  string $content
92
-     * @return \Illuminate\Http\Response
93
-     */
94
-    public function singleRequest($method, $uri, array $data = [], array $headers = [], $content = null)
95
-    {
96
-        // Save the current request so we can reset the router back to it
97
-        // after we've completed our internal request.
98
-        $currentRequest = $this->request->instance()->duplicate();
99
-
100
-        $headers = $this->overrideHeaders($currentRequest->server->getHeaders(), $headers);
101
-
102
-        if ($this->disableMiddleware) {
103
-            $this->app->instance('middleware.disable', true);
104
-        }
105
-
106
-        $response = $this->request($method, $uri, $data, $headers, $content);
107
-
108
-        if ($this->disableMiddleware) {
109
-            $this->app->instance('middleware.disable', false);
110
-        }
111
-
112
-        // Once the request has completed we reset the currentRequest of the router
113
-        // to match the original request.
114
-        $this->request->instance()->initialize(
115
-            $currentRequest->query->all(),
116
-            $currentRequest->request->all(),
117
-            $currentRequest->attributes->all(),
118
-            $currentRequest->cookies->all(),
119
-            $currentRequest->files->all(),
120
-            $currentRequest->server->all(),
121
-            $currentRequest->content
122
-        );
123
-
124
-        return $response;
125
-    }
126
-
127
-    private function overrideHeaders(array $default, array $headers)
128
-    {
129
-        $headers = $this->transformHeadersToUppercaseUnderscoreType($headers);
130
-        return array_merge($default, $headers);
131
-    }
132
-
133
-    public function enableMiddleware()
134
-    {
135
-        $this->disableMiddleware = false;
136
-    }
137
-
138
-    public function disableMiddleware()
139
-    {
140
-        $this->disableMiddleware = true;
141
-    }
142
-
143
-    /**
144
-     * @param  string $method
145
-     * @param  string $uri
146
-     * @param  array  $data
147
-     * @param  array  $headers
148
-     * @param  string $content
149
-     * @return \Illuminate\Http\Response
150
-     */
151
-    private function request($method, $uri, array $data = [], array $headers = [], $content = null)
152
-    {
153
-        // Create a new request object for the internal request
154
-        $request = $this->createRequest($method, $uri, $data, $headers, $content);
155
-
156
-        // Handle the request in the kernel and prepare a response
157
-        $response = $this->router->prepareResponse($request, $this->app->handle($request));
158
-
159
-        return $response;
160
-    }
161
-
162
-    /**
163
-     * @param  string $method
164
-     * @param  string $uri
165
-     * @param  array  $data
166
-     * @param  array  $headers
167
-     * @param  string $content
168
-     * @return \Illuminate\Http\Request
169
-     */
170
-    private function createRequest($method, $uri, array $data = [], array $headers = [], $content = null)
171
-    {
172
-        $server = $this->transformHeadersToServerVariables($headers);
173
-
174
-        return $this->request->create($uri, $method, $data, [], [], $server, $content);
175
-    }
176
-
177
-    private function transformHeadersToUppercaseUnderscoreType($headers)
178
-    {
179
-        $transformed = [];
180
-
181
-        foreach ($headers as $headerType => $headerValue) {
182
-            $headerType = strtoupper(str_replace('-', '_', $headerType));
183
-
184
-            $transformed[$headerType] = $headerValue;
185
-        }
186
-
187
-        return $transformed;
188
-    }
189
-
190
-    /**
191
-     * https://github.com/symfony/symfony/issues/5074
192
-     *
193
-     * @param  array $headers
194
-     * @return array
195
-     */
196
-    private function transformHeadersToServerVariables($headers)
197
-    {
198
-        $server = [];
199
-
200
-        foreach ($headers as $headerType => $headerValue) {
201
-            $headerType = 'HTTP_' . $headerType;
202
-
203
-            $server[$headerType] = $headerValue;
204
-        }
205
-
206
-        return $server;
207
-    }
10
+	private $app;
11
+
12
+	private $router;
13
+
14
+	private $request;
15
+
16
+	private $disableMiddleware = false;
17
+
18
+	/**
19
+	 * @param \Illuminate\Foundation\Application $app
20
+	 * @param \Illuminate\Http\Request $request,
21
+	 * @param \Illuminate\Routing\Router $router
22
+	 */
23
+	public function __construct(Application $app, Request $request, LaravelRouter $router)
24
+	{
25
+		$this->app = $app;
26
+		$this->request = $request;
27
+		$this->router = $router;
28
+	}
29
+
30
+	/**
31
+	 * @return \Illuminate\Http\Response
32
+	 */
33
+	public function get()
34
+	{
35
+		return $this->quickCall('GET', func_get_args());
36
+	}
37
+
38
+	/**
39
+	 * @return \Illuminate\Http\Response
40
+	 */
41
+	public function post()
42
+	{
43
+		return $this->quickCall('POST', func_get_args());
44
+	}
45
+
46
+	/**
47
+	 * @return \Illuminate\Http\Response
48
+	 */
49
+	public function put()
50
+	{
51
+		return $this->quickCall('PUT', func_get_args());
52
+	}
53
+
54
+	/**
55
+	 * @return \Illuminate\Http\Response
56
+	 */
57
+	public function delete()
58
+	{
59
+		return $this->quickCall('DELETE', func_get_args());
60
+	}
61
+
62
+	/**
63
+	 * @param  array $requests An array of requests
64
+	 * @return array
65
+	 */
66
+	public function batchRequest(array $requests)
67
+	{
68
+		foreach ($requests as $i => $request) {
69
+			$requests[$i] = call_user_func_array([$this, 'singleRequest'], $request);
70
+		}
71
+
72
+		return $requests;
73
+	}
74
+
75
+	/**
76
+	 * @param  string $method
77
+	 * @param  array  $args
78
+	 * @return \Illuminate\Http\Response
79
+	 */
80
+	public function quickCall($method, array $args)
81
+	{
82
+		array_unshift($args, $method);
83
+		return call_user_func_array([$this, "singleRequest"], $args);
84
+	}
85
+
86
+	/**
87
+	 * @param  string $method
88
+	 * @param  string $uri
89
+	 * @param  array  $data
90
+	 * @param  array  $headers
91
+	 * @param  string $content
92
+	 * @return \Illuminate\Http\Response
93
+	 */
94
+	public function singleRequest($method, $uri, array $data = [], array $headers = [], $content = null)
95
+	{
96
+		// Save the current request so we can reset the router back to it
97
+		// after we've completed our internal request.
98
+		$currentRequest = $this->request->instance()->duplicate();
99
+
100
+		$headers = $this->overrideHeaders($currentRequest->server->getHeaders(), $headers);
101
+
102
+		if ($this->disableMiddleware) {
103
+			$this->app->instance('middleware.disable', true);
104
+		}
105
+
106
+		$response = $this->request($method, $uri, $data, $headers, $content);
107
+
108
+		if ($this->disableMiddleware) {
109
+			$this->app->instance('middleware.disable', false);
110
+		}
111
+
112
+		// Once the request has completed we reset the currentRequest of the router
113
+		// to match the original request.
114
+		$this->request->instance()->initialize(
115
+			$currentRequest->query->all(),
116
+			$currentRequest->request->all(),
117
+			$currentRequest->attributes->all(),
118
+			$currentRequest->cookies->all(),
119
+			$currentRequest->files->all(),
120
+			$currentRequest->server->all(),
121
+			$currentRequest->content
122
+		);
123
+
124
+		return $response;
125
+	}
126
+
127
+	private function overrideHeaders(array $default, array $headers)
128
+	{
129
+		$headers = $this->transformHeadersToUppercaseUnderscoreType($headers);
130
+		return array_merge($default, $headers);
131
+	}
132
+
133
+	public function enableMiddleware()
134
+	{
135
+		$this->disableMiddleware = false;
136
+	}
137
+
138
+	public function disableMiddleware()
139
+	{
140
+		$this->disableMiddleware = true;
141
+	}
142
+
143
+	/**
144
+	 * @param  string $method
145
+	 * @param  string $uri
146
+	 * @param  array  $data
147
+	 * @param  array  $headers
148
+	 * @param  string $content
149
+	 * @return \Illuminate\Http\Response
150
+	 */
151
+	private function request($method, $uri, array $data = [], array $headers = [], $content = null)
152
+	{
153
+		// Create a new request object for the internal request
154
+		$request = $this->createRequest($method, $uri, $data, $headers, $content);
155
+
156
+		// Handle the request in the kernel and prepare a response
157
+		$response = $this->router->prepareResponse($request, $this->app->handle($request));
158
+
159
+		return $response;
160
+	}
161
+
162
+	/**
163
+	 * @param  string $method
164
+	 * @param  string $uri
165
+	 * @param  array  $data
166
+	 * @param  array  $headers
167
+	 * @param  string $content
168
+	 * @return \Illuminate\Http\Request
169
+	 */
170
+	private function createRequest($method, $uri, array $data = [], array $headers = [], $content = null)
171
+	{
172
+		$server = $this->transformHeadersToServerVariables($headers);
173
+
174
+		return $this->request->create($uri, $method, $data, [], [], $server, $content);
175
+	}
176
+
177
+	private function transformHeadersToUppercaseUnderscoreType($headers)
178
+	{
179
+		$transformed = [];
180
+
181
+		foreach ($headers as $headerType => $headerValue) {
182
+			$headerType = strtoupper(str_replace('-', '_', $headerType));
183
+
184
+			$transformed[$headerType] = $headerValue;
185
+		}
186
+
187
+		return $transformed;
188
+	}
189
+
190
+	/**
191
+	 * https://github.com/symfony/symfony/issues/5074
192
+	 *
193
+	 * @param  array $headers
194
+	 * @return array
195
+	 */
196
+	private function transformHeadersToServerVariables($headers)
197
+	{
198
+		$server = [];
199
+
200
+		foreach ($headers as $headerType => $headerValue) {
201
+			$headerType = 'HTTP_' . $headerType;
202
+
203
+			$server[$headerType] = $headerValue;
204
+		}
205
+
206
+		return $server;
207
+	}
208 208
 }
Please login to merge, or discard this patch.
src/Modules/Core/Console/Commands/MakeModuleCommand.php 1 patch
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -10,242 +10,242 @@
 block discarded – undo
10 10
 
11 11
 class MakeModuleCommand extends Command
12 12
 {
13
-    /**
14
-     * The name and signature of the console command.
15
-     *
16
-     * @var string
17
-     */
18
-    protected $signature = 'generate:module
13
+	/**
14
+	 * The name and signature of the console command.
15
+	 *
16
+	 * @var string
17
+	 */
18
+	protected $signature = 'generate:module
19 19
         {slug : The slug of the module}';
20 20
 
21
-    /**
22
-     * The console command description.
23
-     *
24
-     * @var string
25
-     */
26
-    protected $description = 'Create a new module';
27
-
28
-    /**
29
-     * The modules instance.
30
-     *
31
-     * @var RepositoryManager
32
-     */
33
-    protected $module;
34
-
35
-    /**
36
-     * The filesystem instance.
37
-     *
38
-     * @var Filesystem
39
-     */
40
-    protected $files;
41
-
42
-    /**
43
-     * Array to store the configuration details.
44
-     *
45
-     * @var array
46
-     */
47
-    protected $container;
48
-
49
-    /**
50
-     * Array of folder mappings.
51
-     *
52
-     * @var Array
53
-     */
54
-    protected $mapping = [
55
-        'Database/Factories'  => 'Database/Factories',
56
-        'Database/Migrations' => 'Database/Migrations',
57
-        'Database/Seeds'      => 'Database/Seeds',
58
-        'Http/Controllers'    => 'Http/Controllers',
59
-        'Http/Requests'       => 'Http/Requests',
60
-        'Http/Resources'      => 'Http/Resources',
61
-        'ModelObservers'      => 'ModelObservers',
62
-        'Providers'           => 'Providers',
63
-        'Repositories'        => 'Repositories',
64
-        'Routes'              => 'Routes'
65
-    ];
66
-
67
-    /**
68
-     * Create a new command instance.
69
-     *
70
-     * @param Filesystem $files
71
-     * @param RepositoryManager $module
72
-     */
73
-    public function __construct(Filesystem $files, RepositoryManager $module)
74
-    {
75
-        parent::__construct();
76
-
77
-        $this->files = $files;
78
-        $this->module = $module;
79
-    }
80
-
81
-    /**
82
-     * Execute the console command.
83
-     *
84
-     * @return mixed
85
-     */
86
-    public function handle()
87
-    {
88
-        $this->container['slug']        = Str::slug($this->argument('slug'));
89
-        $this->container['name']        = Str::studly($this->container['slug']);
90
-        $this->container['version']     = '1.0';
91
-        $this->container['description'] = 'This is the description for the ' . $this->container['name'] . ' module.';
92
-        $this->container['location']    = config('modules.default_location');
93
-        $this->container['provider']    = config("modules.locations.{$this->container['location']}.provider");
94
-        $this->container['basename']    = Str::studly($this->container['slug']);
95
-        $this->container['namespace']   = config("modules.locations.{$this->container['location']}.namespace").$this->container['basename'];
96
-
97
-        return $this->generate();
98
-    }
99
-
100
-    /**
101
-     * Generate the module.
102
-     */
103
-    protected function generate()
104
-    {
105
-        $steps = [
106
-            'Generating module...' => 'generateModule',
107
-            'Optimizing module cache...' => 'optimizeModules',
108
-            'Generating migrations...' => 'generateMigration',
109
-        ];
110
-
111
-        $progress = new ProgressBar($this->output, count($steps));
112
-        $progress->start();
113
-
114
-        foreach ($steps as $message => $function) {
115
-            $progress->setMessage($message);
116
-
117
-            $this->$function();
118
-
119
-            $progress->advance();
120
-        }
121
-
122
-        $progress->finish();
123
-
124
-        event($this->container['slug'] . '.module.made');
125
-
126
-        $this->info("\nModule generated successfully.");
127
-    }
128
-
129
-    /**
130
-     * Generate defined module folders.
131
-     */
132
-    protected function generateModule()
133
-    {
134
-        $location = $this->container['location'];
135
-        $root     = module_path(null, '', $location);
136
-        $manifest = config("modules.locations.$location.manifest") ?: 'module.json';
137
-        $provider = config("modules.locations.$location.provider") ?: 'ModuleServiceProvider';
138
-
139
-        if (!$this->files->isDirectory($root)) {
140
-            $this->files->makeDirectory($root);
141
-        }
142
-
143
-        $directory = module_path(null, $this->container['basename'], $location);
144
-        $source    = __DIR__ . '/Stubs/Module';
145
-
146
-        $this->files->makeDirectory($directory);
147
-
148
-        $sourceFiles = $this->files->allFiles($source, true);
149
-
150
-        if (!empty($this->mapping)) {
151
-            $search = array_keys($this->mapping);
152
-            $replace = array_values($this->mapping);
153
-        }
154
-
155
-        foreach ($sourceFiles as $file) {
156
-            $contents = $this->replacePlaceholders($file->getContents());
157
-            $subPath = $file->getRelativePathname();
158
-
159
-            if (!empty($this->mapping)) {
160
-                $subPath = str_replace($search, $replace, $subPath);
161
-            }
162
-
163
-            $filePath = $directory . '/' . $subPath;
21
+	/**
22
+	 * The console command description.
23
+	 *
24
+	 * @var string
25
+	 */
26
+	protected $description = 'Create a new module';
27
+
28
+	/**
29
+	 * The modules instance.
30
+	 *
31
+	 * @var RepositoryManager
32
+	 */
33
+	protected $module;
34
+
35
+	/**
36
+	 * The filesystem instance.
37
+	 *
38
+	 * @var Filesystem
39
+	 */
40
+	protected $files;
41
+
42
+	/**
43
+	 * Array to store the configuration details.
44
+	 *
45
+	 * @var array
46
+	 */
47
+	protected $container;
48
+
49
+	/**
50
+	 * Array of folder mappings.
51
+	 *
52
+	 * @var Array
53
+	 */
54
+	protected $mapping = [
55
+		'Database/Factories'  => 'Database/Factories',
56
+		'Database/Migrations' => 'Database/Migrations',
57
+		'Database/Seeds'      => 'Database/Seeds',
58
+		'Http/Controllers'    => 'Http/Controllers',
59
+		'Http/Requests'       => 'Http/Requests',
60
+		'Http/Resources'      => 'Http/Resources',
61
+		'ModelObservers'      => 'ModelObservers',
62
+		'Providers'           => 'Providers',
63
+		'Repositories'        => 'Repositories',
64
+		'Routes'              => 'Routes'
65
+	];
66
+
67
+	/**
68
+	 * Create a new command instance.
69
+	 *
70
+	 * @param Filesystem $files
71
+	 * @param RepositoryManager $module
72
+	 */
73
+	public function __construct(Filesystem $files, RepositoryManager $module)
74
+	{
75
+		parent::__construct();
76
+
77
+		$this->files = $files;
78
+		$this->module = $module;
79
+	}
80
+
81
+	/**
82
+	 * Execute the console command.
83
+	 *
84
+	 * @return mixed
85
+	 */
86
+	public function handle()
87
+	{
88
+		$this->container['slug']        = Str::slug($this->argument('slug'));
89
+		$this->container['name']        = Str::studly($this->container['slug']);
90
+		$this->container['version']     = '1.0';
91
+		$this->container['description'] = 'This is the description for the ' . $this->container['name'] . ' module.';
92
+		$this->container['location']    = config('modules.default_location');
93
+		$this->container['provider']    = config("modules.locations.{$this->container['location']}.provider");
94
+		$this->container['basename']    = Str::studly($this->container['slug']);
95
+		$this->container['namespace']   = config("modules.locations.{$this->container['location']}.namespace").$this->container['basename'];
96
+
97
+		return $this->generate();
98
+	}
99
+
100
+	/**
101
+	 * Generate the module.
102
+	 */
103
+	protected function generate()
104
+	{
105
+		$steps = [
106
+			'Generating module...' => 'generateModule',
107
+			'Optimizing module cache...' => 'optimizeModules',
108
+			'Generating migrations...' => 'generateMigration',
109
+		];
110
+
111
+		$progress = new ProgressBar($this->output, count($steps));
112
+		$progress->start();
113
+
114
+		foreach ($steps as $message => $function) {
115
+			$progress->setMessage($message);
116
+
117
+			$this->$function();
118
+
119
+			$progress->advance();
120
+		}
121
+
122
+		$progress->finish();
123
+
124
+		event($this->container['slug'] . '.module.made');
125
+
126
+		$this->info("\nModule generated successfully.");
127
+	}
128
+
129
+	/**
130
+	 * Generate defined module folders.
131
+	 */
132
+	protected function generateModule()
133
+	{
134
+		$location = $this->container['location'];
135
+		$root     = module_path(null, '', $location);
136
+		$manifest = config("modules.locations.$location.manifest") ?: 'module.json';
137
+		$provider = config("modules.locations.$location.provider") ?: 'ModuleServiceProvider';
138
+
139
+		if (!$this->files->isDirectory($root)) {
140
+			$this->files->makeDirectory($root);
141
+		}
142
+
143
+		$directory = module_path(null, $this->container['basename'], $location);
144
+		$source    = __DIR__ . '/Stubs/Module';
145
+
146
+		$this->files->makeDirectory($directory);
147
+
148
+		$sourceFiles = $this->files->allFiles($source, true);
149
+
150
+		if (!empty($this->mapping)) {
151
+			$search = array_keys($this->mapping);
152
+			$replace = array_values($this->mapping);
153
+		}
154
+
155
+		foreach ($sourceFiles as $file) {
156
+			$contents = $this->replacePlaceholders($file->getContents());
157
+			$subPath = $file->getRelativePathname();
158
+
159
+			if (!empty($this->mapping)) {
160
+				$subPath = str_replace($search, $replace, $subPath);
161
+			}
162
+
163
+			$filePath = $directory . '/' . $subPath;
164 164
             
165
-            // if the file is module.json, replace it with the custom manifest file name
166
-            if ($file->getFilename() === 'module.json' && $manifest) {
167
-                $filePath = str_replace('module.json', $manifest, $filePath);
168
-            }
165
+			// if the file is module.json, replace it with the custom manifest file name
166
+			if ($file->getFilename() === 'module.json' && $manifest) {
167
+				$filePath = str_replace('module.json', $manifest, $filePath);
168
+			}
169 169
             
170
-            // if the file is ModuleServiceProvider.php, replace it with the custom provider file name
171
-            if ($file->getFilename() === 'ModuleServiceProvider.php') {
172
-                $filePath = str_replace('ModuleServiceProvider', $provider, $filePath);
173
-            }
174
-            $filePath = $this->replacePlaceholders($filePath);
170
+			// if the file is ModuleServiceProvider.php, replace it with the custom provider file name
171
+			if ($file->getFilename() === 'ModuleServiceProvider.php') {
172
+				$filePath = str_replace('ModuleServiceProvider', $provider, $filePath);
173
+			}
174
+			$filePath = $this->replacePlaceholders($filePath);
175 175
             
176
-            $dir = dirname($filePath);
176
+			$dir = dirname($filePath);
177 177
             
178
-            if (! $this->files->isDirectory($dir)) {
179
-                $this->files->makeDirectory($dir, 0755, true);
180
-            }
181
-
182
-            $this->files->put($filePath, $contents);
183
-        }
184
-    }
185
-
186
-    /**
187
-     * @param string $contents
188
-     *
189
-     * @return string
190
-     */
191
-    protected function replacePlaceholders($contents)
192
-    {
193
-        $modelName = \Str::camel($this->container['slug']);
194
-        $modelNameSingular = \Str::singular($modelName);
195
-
196
-        $find = [
197
-            'DummyFactory',
198
-            'DummyModelName',
199
-            'DummyModuleSlug',
200
-            'DummyModule',
201
-            'DummyModel',
202
-            'DummyDatabaseSeeder',
203
-            'DummyTableSeeder',
204
-            'DummyController',
205
-            'DummyRepository',
206
-            'InsertDummy',
207
-            'UpdateDummy',
208
-            'DummyResource',
209
-            'DummyObserver',
210
-            'DummyTableName',
211
-            'DummyRoutePrefix',
212
-        ];
213
-
214
-        $replace = [
215
-            ucfirst($modelNameSingular) . 'Factory',
216
-            $modelNameSingular,
217
-            $this->container['slug'],
218
-            ucfirst($modelName),
219
-            ucfirst($modelNameSingular),
220
-            ucfirst($modelName) . 'DatabaseSeeder',
221
-            ucfirst($modelName) . 'TableSeeder',
222
-            ucfirst($modelNameSingular) . 'Controller',
223
-            ucfirst($modelNameSingular) . 'Repository',
224
-            'Insert' . ucfirst($modelNameSingular),
225
-            'Update' . ucfirst($modelNameSingular),
226
-            ucfirst($modelNameSingular),
227
-            ucfirst($modelNameSingular) . 'Observer',
228
-            $modelName,
229
-            $modelName,
230
-        ];
231
-
232
-        return str_replace($find, $replace, $contents);
233
-    }
234
-
235
-    /**
236
-     * Reset module cache of enabled and disabled modules.
237
-     */
238
-    protected function optimizeModules()
239
-    {
240
-        return $this->callSilent('module:optimize');
241
-    }
242
-
243
-    /**
244
-     * Generate table migrations.
245
-     */
246
-    protected function generateMigration()
247
-    {
248
-        $modelName = $this->container['slug'];
249
-        return $this->callSilent('make:module:migration', ['slug' => $modelName, 'name' => 'create_' . $modelName . '_table']);
250
-    }
178
+			if (! $this->files->isDirectory($dir)) {
179
+				$this->files->makeDirectory($dir, 0755, true);
180
+			}
181
+
182
+			$this->files->put($filePath, $contents);
183
+		}
184
+	}
185
+
186
+	/**
187
+	 * @param string $contents
188
+	 *
189
+	 * @return string
190
+	 */
191
+	protected function replacePlaceholders($contents)
192
+	{
193
+		$modelName = \Str::camel($this->container['slug']);
194
+		$modelNameSingular = \Str::singular($modelName);
195
+
196
+		$find = [
197
+			'DummyFactory',
198
+			'DummyModelName',
199
+			'DummyModuleSlug',
200
+			'DummyModule',
201
+			'DummyModel',
202
+			'DummyDatabaseSeeder',
203
+			'DummyTableSeeder',
204
+			'DummyController',
205
+			'DummyRepository',
206
+			'InsertDummy',
207
+			'UpdateDummy',
208
+			'DummyResource',
209
+			'DummyObserver',
210
+			'DummyTableName',
211
+			'DummyRoutePrefix',
212
+		];
213
+
214
+		$replace = [
215
+			ucfirst($modelNameSingular) . 'Factory',
216
+			$modelNameSingular,
217
+			$this->container['slug'],
218
+			ucfirst($modelName),
219
+			ucfirst($modelNameSingular),
220
+			ucfirst($modelName) . 'DatabaseSeeder',
221
+			ucfirst($modelName) . 'TableSeeder',
222
+			ucfirst($modelNameSingular) . 'Controller',
223
+			ucfirst($modelNameSingular) . 'Repository',
224
+			'Insert' . ucfirst($modelNameSingular),
225
+			'Update' . ucfirst($modelNameSingular),
226
+			ucfirst($modelNameSingular),
227
+			ucfirst($modelNameSingular) . 'Observer',
228
+			$modelName,
229
+			$modelName,
230
+		];
231
+
232
+		return str_replace($find, $replace, $contents);
233
+	}
234
+
235
+	/**
236
+	 * Reset module cache of enabled and disabled modules.
237
+	 */
238
+	protected function optimizeModules()
239
+	{
240
+		return $this->callSilent('module:optimize');
241
+	}
242
+
243
+	/**
244
+	 * Generate table migrations.
245
+	 */
246
+	protected function generateMigration()
247
+	{
248
+		$modelName = $this->container['slug'];
249
+		return $this->callSilent('make:module:migration', ['slug' => $modelName, 'name' => 'create_' . $modelName . '_table']);
250
+	}
251 251
 }
Please login to merge, or discard this patch.
src/Modules/Core/Console/Commands/GenerateDoc.php 1 patch
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -7,255 +7,255 @@
 block discarded – undo
7 7
 
8 8
 class GenerateDoc extends Command
9 9
 {
10
-    /**
11
-     * The name and signature of the console command.
12
-     *
13
-     * @var string
14
-     */
15
-    protected $signature = 'doc:generate';
10
+	/**
11
+	 * The name and signature of the console command.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $signature = 'doc:generate';
16 16
 
17
-    /**
18
-     * The console command description.
19
-     *
20
-     * @var string
21
-     */
22
-    protected $description = 'Generate api documentation';
17
+	/**
18
+	 * The console command description.
19
+	 *
20
+	 * @var string
21
+	 */
22
+	protected $description = 'Generate api documentation';
23 23
 
24
-    /**
25
-     * Init new object.
26
-     *
27
-     * @return  void
28
-     */
29
-    public function __construct()
30
-    {
31
-        parent::__construct();
32
-    }
24
+	/**
25
+	 * Init new object.
26
+	 *
27
+	 * @return  void
28
+	 */
29
+	public function __construct()
30
+	{
31
+		parent::__construct();
32
+	}
33 33
 
34
-    /**
35
-     * Execute the console command.
36
-     *
37
-     * @return mixed
38
-     */
39
-    public function handle()
40
-    {
41
-        $docData           = [];
42
-        $docData['models'] = [];
43
-        $routes            = $this->getRoutes();
44
-        foreach ($routes as $route) {
45
-            if ($route) {
46
-                $actoinArray = explode('@', $route['action']);
47
-                if (Arr::get($actoinArray, 1, false)) {
48
-                    $controller       = $actoinArray[0];
49
-                    $method           = $actoinArray[1];
50
-                    $route['name']    = $method !== 'index' ? $method : 'list';
34
+	/**
35
+	 * Execute the console command.
36
+	 *
37
+	 * @return mixed
38
+	 */
39
+	public function handle()
40
+	{
41
+		$docData           = [];
42
+		$docData['models'] = [];
43
+		$routes            = $this->getRoutes();
44
+		foreach ($routes as $route) {
45
+			if ($route) {
46
+				$actoinArray = explode('@', $route['action']);
47
+				if (Arr::get($actoinArray, 1, false)) {
48
+					$controller       = $actoinArray[0];
49
+					$method           = $actoinArray[1];
50
+					$route['name']    = $method !== 'index' ? $method : 'list';
51 51
                     
52
-                    $reflectionClass  = new \ReflectionClass($controller);
53
-                    $reflectionMethod = $reflectionClass->getMethod($method);
54
-                    $classProperties  = $reflectionClass->getDefaultProperties();
55
-                    $skipLoginCheck   = Arr::get($classProperties, 'skipLoginCheck', false);
56
-                    $validationRules  = Arr::get($classProperties, 'validationRules', false);
52
+					$reflectionClass  = new \ReflectionClass($controller);
53
+					$reflectionMethod = $reflectionClass->getMethod($method);
54
+					$classProperties  = $reflectionClass->getDefaultProperties();
55
+					$skipLoginCheck   = Arr::get($classProperties, 'skipLoginCheck', false);
56
+					$validationRules  = Arr::get($classProperties, 'validationRules', false);
57 57
 
58
-                    dd($classProperties);
59
-                    $this->processDocBlock($route, $reflectionMethod);
60
-                    $this->getHeaders($route, $method, $skipLoginCheck);
61
-                    $this->getPostData($route, $reflectionMethod, $validationRules);
58
+					dd($classProperties);
59
+					$this->processDocBlock($route, $reflectionMethod);
60
+					$this->getHeaders($route, $method, $skipLoginCheck);
61
+					$this->getPostData($route, $reflectionMethod, $validationRules);
62 62
 
63
-                    $route['response'] = $this->getResponseObject($classProperties['model'], $route['name'], $route['returnDocBlock']);
63
+					$route['response'] = $this->getResponseObject($classProperties['model'], $route['name'], $route['returnDocBlock']);
64 64
 
65
-                    preg_match('/api\/([^#]+)\//iU', $route['uri'], $module);
66
-                    $docData['modules'][$module[1]][substr($route['prefix'], strlen('/api/'.$module[1].'/') - 1)][] = $route;
65
+					preg_match('/api\/([^#]+)\//iU', $route['uri'], $module);
66
+					$docData['modules'][$module[1]][substr($route['prefix'], strlen('/api/'.$module[1].'/') - 1)][] = $route;
67 67
 
68
-                    $this->getModels($classProperties['model'], $docData);
69
-                }
70
-            }
71
-        }
68
+					$this->getModels($classProperties['model'], $docData);
69
+				}
70
+			}
71
+		}
72 72
         
73
-        $docData['errors']  = $this->getErrors();
74
-        $docData['reports'] = \Core::reports()->all();
75
-        \File::put(app_path('Modules/Core/Resources/api.json'), json_encode($docData));
76
-    }
73
+		$docData['errors']  = $this->getErrors();
74
+		$docData['reports'] = \Core::reports()->all();
75
+		\File::put(app_path('Modules/Core/Resources/api.json'), json_encode($docData));
76
+	}
77 77
 
78
-    /**
79
-     * Get list of all registered routes.
80
-     *
81
-     * @return collection
82
-     */
83
-    protected function getRoutes()
84
-    {
85
-        return collect(\Route::getRoutes())->map(function ($route) {
86
-            if (strpos($route->uri(), 'api/') !== false) {
87
-                return [
88
-                    'method' => $route->methods()[0],
89
-                    'uri'    => $route->uri(),
90
-                    'action' => $route->getActionName(),
91
-                    'prefix' => $route->getPrefix()
92
-                ];
93
-            }
94
-            return false;
95
-        })->all();
96
-    }
78
+	/**
79
+	 * Get list of all registered routes.
80
+	 *
81
+	 * @return collection
82
+	 */
83
+	protected function getRoutes()
84
+	{
85
+		return collect(\Route::getRoutes())->map(function ($route) {
86
+			if (strpos($route->uri(), 'api/') !== false) {
87
+				return [
88
+					'method' => $route->methods()[0],
89
+					'uri'    => $route->uri(),
90
+					'action' => $route->getActionName(),
91
+					'prefix' => $route->getPrefix()
92
+				];
93
+			}
94
+			return false;
95
+		})->all();
96
+	}
97 97
 
98
-    /**
99
-     * Generate headers for the given route.
100
-     *
101
-     * @param  array  &$route
102
-     * @param  string $method
103
-     * @param  array  $skipLoginCheck
104
-     * @return void
105
-     */
106
-    protected function getHeaders(&$route, $method, $skipLoginCheck)
107
-    {
108
-        $route['headers'] = [
109
-        'Accept'       => 'application/json',
110
-        'Content-Type' => 'application/json',
111
-        'locale'       => 'The language of the returned data: ar, en or all.',
112
-        'time-zone'    => 'Your locale time zone',
113
-        ];
98
+	/**
99
+	 * Generate headers for the given route.
100
+	 *
101
+	 * @param  array  &$route
102
+	 * @param  string $method
103
+	 * @param  array  $skipLoginCheck
104
+	 * @return void
105
+	 */
106
+	protected function getHeaders(&$route, $method, $skipLoginCheck)
107
+	{
108
+		$route['headers'] = [
109
+		'Accept'       => 'application/json',
110
+		'Content-Type' => 'application/json',
111
+		'locale'       => 'The language of the returned data: ar, en or all.',
112
+		'time-zone'    => 'Your locale time zone',
113
+		];
114 114
 
115 115
 
116
-        if (! $skipLoginCheck || ! in_array($method, $skipLoginCheck)) {
117
-            $route['headers']['Authorization'] = 'Bearer {token}';
118
-        }
119
-    }
116
+		if (! $skipLoginCheck || ! in_array($method, $skipLoginCheck)) {
117
+			$route['headers']['Authorization'] = 'Bearer {token}';
118
+		}
119
+	}
120 120
 
121
-    /**
122
-     * Generate description and params for the given route
123
-     * based on the docblock.
124
-     *
125
-     * @param  array  &$route
126
-     * @param  \ReflectionMethod $reflectionMethod
127
-     * @return void
128
-     */
129
-    protected function processDocBlock(&$route, $reflectionMethod)
130
-    {
131
-        $factory                 = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
132
-        $docblock                = $factory->create($reflectionMethod->getDocComment());
133
-        $route['description']    = trim(preg_replace('/\s+/', ' ', $docblock->getSummary()));
134
-        $params                  = $docblock->getTagsByName('param');
135
-        $route['returnDocBlock'] = $docblock->getTagsByName('return')[0]->getType()->getFqsen()->getName();
136
-        foreach ($params as $param) {
137
-            $name = $param->getVariableName();
138
-            if ($name !== 'request') {
139
-                $route['parametars'][$param->getVariableName()] = $param->getDescription()->render();
140
-            }
141
-        }
142
-    }
121
+	/**
122
+	 * Generate description and params for the given route
123
+	 * based on the docblock.
124
+	 *
125
+	 * @param  array  &$route
126
+	 * @param  \ReflectionMethod $reflectionMethod
127
+	 * @return void
128
+	 */
129
+	protected function processDocBlock(&$route, $reflectionMethod)
130
+	{
131
+		$factory                 = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
132
+		$docblock                = $factory->create($reflectionMethod->getDocComment());
133
+		$route['description']    = trim(preg_replace('/\s+/', ' ', $docblock->getSummary()));
134
+		$params                  = $docblock->getTagsByName('param');
135
+		$route['returnDocBlock'] = $docblock->getTagsByName('return')[0]->getType()->getFqsen()->getName();
136
+		foreach ($params as $param) {
137
+			$name = $param->getVariableName();
138
+			if ($name !== 'request') {
139
+				$route['parametars'][$param->getVariableName()] = $param->getDescription()->render();
140
+			}
141
+		}
142
+	}
143 143
 
144
-    /**
145
-     * Generate post body for the given route.
146
-     *
147
-     * @param  array  &$route
148
-     * @param  \ReflectionMethod $reflectionMethod
149
-     * @param  array  $validationRules
150
-     * @return void
151
-     */
152
-    protected function getPostData(&$route, $reflectionMethod, $validationRules)
153
-    {
154
-        if ($route['method'] == 'POST') {
155
-            $body = $this->getMethodBody($reflectionMethod);
144
+	/**
145
+	 * Generate post body for the given route.
146
+	 *
147
+	 * @param  array  &$route
148
+	 * @param  \ReflectionMethod $reflectionMethod
149
+	 * @param  array  $validationRules
150
+	 * @return void
151
+	 */
152
+	protected function getPostData(&$route, $reflectionMethod, $validationRules)
153
+	{
154
+		if ($route['method'] == 'POST') {
155
+			$body = $this->getMethodBody($reflectionMethod);
156 156
 
157
-            preg_match('/\$this->validate\(\$request,([^#]+)\);/iU', $body, $match);
158
-            if (count($match)) {
159
-                if ($match[1] == '$this->validationRules') {
160
-                    $route['body'] = $validationRules;
161
-                } else {
162
-                    $route['body'] = eval('return '.str_replace(',\'.$request->get(\'id\')', ',{id}\'', $match[1]).';');
163
-                }
157
+			preg_match('/\$this->validate\(\$request,([^#]+)\);/iU', $body, $match);
158
+			if (count($match)) {
159
+				if ($match[1] == '$this->validationRules') {
160
+					$route['body'] = $validationRules;
161
+				} else {
162
+					$route['body'] = eval('return '.str_replace(',\'.$request->get(\'id\')', ',{id}\'', $match[1]).';');
163
+				}
164 164
 
165
-                foreach ($route['body'] as &$rule) {
166
-                    if (strpos($rule, 'unique')) {
167
-                        $rule = substr($rule, 0, strpos($rule, 'unique') + 6);
168
-                    } elseif (strpos($rule, 'exists')) {
169
-                        $rule = substr($rule, 0, strpos($rule, 'exists') - 1);
170
-                    }
171
-                }
172
-            } else {
173
-                $route['body'] = 'conditions';
174
-            }
175
-        }
176
-    }
165
+				foreach ($route['body'] as &$rule) {
166
+					if (strpos($rule, 'unique')) {
167
+						$rule = substr($rule, 0, strpos($rule, 'unique') + 6);
168
+					} elseif (strpos($rule, 'exists')) {
169
+						$rule = substr($rule, 0, strpos($rule, 'exists') - 1);
170
+					}
171
+				}
172
+			} else {
173
+				$route['body'] = 'conditions';
174
+			}
175
+		}
176
+	}
177 177
 
178
-    /**
179
-     * Generate application errors.
180
-     *
181
-     * @return array
182
-     */
183
-    protected function getErrors()
184
-    {
185
-        $errors          = [];
186
-        $reflectionClass = new \ReflectionClass('App\Modules\Core\Utl\ErrorHandler');
187
-        foreach ($reflectionClass->getMethods() as $method) {
188
-            $methodName       = $method->name;
189
-            $reflectionMethod = $reflectionClass->getMethod($methodName);
190
-            $body             = $this->getMethodBody($reflectionMethod);
178
+	/**
179
+	 * Generate application errors.
180
+	 *
181
+	 * @return array
182
+	 */
183
+	protected function getErrors()
184
+	{
185
+		$errors          = [];
186
+		$reflectionClass = new \ReflectionClass('App\Modules\Core\Utl\ErrorHandler');
187
+		foreach ($reflectionClass->getMethods() as $method) {
188
+			$methodName       = $method->name;
189
+			$reflectionMethod = $reflectionClass->getMethod($methodName);
190
+			$body             = $this->getMethodBody($reflectionMethod);
191 191
 
192
-            preg_match('/\$error=\[\'status\'=>([^#]+)\,/iU', $body, $match);
192
+			preg_match('/\$error=\[\'status\'=>([^#]+)\,/iU', $body, $match);
193 193
 
194
-            if (count($match)) {
195
-                $errors[$match[1]][] = $methodName;
196
-            }
197
-        }
194
+			if (count($match)) {
195
+				$errors[$match[1]][] = $methodName;
196
+			}
197
+		}
198 198
 
199
-        return $errors;
200
-    }
199
+		return $errors;
200
+	}
201 201
 
202
-    /**
203
-     * Get the given method body code.
204
-     *
205
-     * @param  \ReflectionMethod $reflectionMethod
206
-     * @return string
207
-     */
208
-    protected function getMethodBody($reflectionMethod)
209
-    {
210
-        $filename   = $reflectionMethod->getFileName();
211
-        $start_line = $reflectionMethod->getStartLine() - 1;
212
-        $end_line   = $reflectionMethod->getEndLine();
213
-        $length     = $end_line - $start_line;
214
-        $source     = file($filename);
215
-        $body       = implode("", array_slice($source, $start_line, $length));
216
-        $body       = trim(preg_replace('/\s+/', '', $body));
202
+	/**
203
+	 * Get the given method body code.
204
+	 *
205
+	 * @param  \ReflectionMethod $reflectionMethod
206
+	 * @return string
207
+	 */
208
+	protected function getMethodBody($reflectionMethod)
209
+	{
210
+		$filename   = $reflectionMethod->getFileName();
211
+		$start_line = $reflectionMethod->getStartLine() - 1;
212
+		$end_line   = $reflectionMethod->getEndLine();
213
+		$length     = $end_line - $start_line;
214
+		$source     = file($filename);
215
+		$body       = implode("", array_slice($source, $start_line, $length));
216
+		$body       = trim(preg_replace('/\s+/', '', $body));
217 217
 
218
-        return $body;
219
-    }
218
+		return $body;
219
+	}
220 220
 
221
-    /**
222
-     * Get example object of all availble models.
223
-     *
224
-     * @param  string $modelName
225
-     * @param  array  $docData
226
-     * @return string
227
-     */
228
-    protected function getModels($modelName, &$docData)
229
-    {
230
-        if ($modelName && ! Arr::has($docData['models'], $modelName)) {
231
-            $modelClass = call_user_func_array("\Core::{$modelName}", [])->modelClass;
232
-            $model      = factory($modelClass)->make();
233
-            $modelArr   = $model->toArray();
221
+	/**
222
+	 * Get example object of all availble models.
223
+	 *
224
+	 * @param  string $modelName
225
+	 * @param  array  $docData
226
+	 * @return string
227
+	 */
228
+	protected function getModels($modelName, &$docData)
229
+	{
230
+		if ($modelName && ! Arr::has($docData['models'], $modelName)) {
231
+			$modelClass = call_user_func_array("\Core::{$modelName}", [])->modelClass;
232
+			$model      = factory($modelClass)->make();
233
+			$modelArr   = $model->toArray();
234 234
 
235
-            if ($model->trans && ! $model->trans->count()) {
236
-                $modelArr['trans'] = [
237
-                    'en' => factory($modelClass.'Translation')->make()->toArray()
238
-                ];
239
-            }
235
+			if ($model->trans && ! $model->trans->count()) {
236
+				$modelArr['trans'] = [
237
+					'en' => factory($modelClass.'Translation')->make()->toArray()
238
+				];
239
+			}
240 240
 
241
-            $docData['models'][$modelName] = json_encode($modelArr, JSON_PRETTY_PRINT);
242
-        }
243
-    }
241
+			$docData['models'][$modelName] = json_encode($modelArr, JSON_PRETTY_PRINT);
242
+		}
243
+	}
244 244
 
245
-    /**
246
-     * Get the route response object type.
247
-     *
248
-     * @param  string $modelName
249
-     * @param  string $method
250
-     * @param  string $returnDocBlock
251
-     * @return array
252
-     */
253
-    protected function getResponseObject($modelName, $method, $returnDocBlock)
254
-    {
255
-        $config    = \CoreConfig::getConfig();
256
-        $relations = Arr::has($config['relations'], $modelName) ? Arr::has($config['relations'][$modelName], $method) ? $config['relations'][$modelName] : false : false;
257
-        $modelName = call_user_func_array("\Core::{$returnDocBlock}", []) ? $returnDocBlock : $modelName;
245
+	/**
246
+	 * Get the route response object type.
247
+	 *
248
+	 * @param  string $modelName
249
+	 * @param  string $method
250
+	 * @param  string $returnDocBlock
251
+	 * @return array
252
+	 */
253
+	protected function getResponseObject($modelName, $method, $returnDocBlock)
254
+	{
255
+		$config    = \CoreConfig::getConfig();
256
+		$relations = Arr::has($config['relations'], $modelName) ? Arr::has($config['relations'][$modelName], $method) ? $config['relations'][$modelName] : false : false;
257
+		$modelName = call_user_func_array("\Core::{$returnDocBlock}", []) ? $returnDocBlock : $modelName;
258 258
 
259
-        return $relations ? [$modelName => $relations && $relations[$method] ? $relations[$method] : []] : false;
260
-    }
259
+		return $relations ? [$modelName => $relations && $relations[$method] ? $relations[$method] : []] : false;
260
+	}
261 261
 }
Please login to merge, or discard this patch.
src/Modules/Core/BaseClasses/BaseApiController.php 1 patch
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -10,204 +10,204 @@
 block discarded – undo
10 10
 
11 11
 class BaseApiController extends Controller
12 12
 {
13
-    /**
14
-     * The config implementation.
15
-     *
16
-     * @var array
17
-     */
18
-    protected $config;
19
-
20
-    /**
21
-     * The relations implementation.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $relations;
26
-
27
-    /**
28
-     * The repo implementation.
29
-     *
30
-     * @var object
31
-     */
32
-    protected $repo;
33
-
34
-    /**
35
-     * Init new object.
36
-     *
37
-     * @param   mixed      $repo
38
-     * @param   \App\Modules\Core\Utl\CoreConfig $config
39
-     * @param   string     $modelResource
40
-     * @return  void
41
-     */
42
-    public function __construct($repo, $config, $modelResource)
43
-    {
44
-        $this->repo = new CachingDecorator($repo, \App::make('Illuminate\Contracts\Cache\Repository'));
45
-        $this->modelResource = $modelResource;
46
-        $this->config = $config->getConfig();
47
-        $this->modelName = explode('\\', get_called_class());
48
-        $this->modelName = lcfirst(str_replace('Controller', '', end($this->modelName)));
49
-        $this->validationRules = property_exists($this, 'validationRules') ? $this->validationRules : false;
50
-        $this->skipPermissionCheck = property_exists($this, 'skipPermissionCheck') ? $this->skipPermissionCheck : [];
51
-        $this->skipLoginCheck = property_exists($this, 'skipLoginCheck') ? $this->skipLoginCheck : [];
52
-        $route = explode('@', \Route::currentRouteAction())[1];
53
-
54
-        $this->setSessions();
55
-        $this->checkPermission($route);
56
-        $this->setRelations($route);
57
-    }
58
-
59
-    /**
60
-     * Fetch all records with relations from storage.
61
-     *
62
-     * @param Request $request
63
-     * @return \Illuminate\Http\Response
64
-     */
65
-    public function index(Request $request)
66
-    {
67
-        return $this->modelResource::collection($this->repo->list($this->relations, $request->query(), $request->query('perPage'), $request->query('sortBy'), $request->query('desc')));
68
-    }
69
-
70
-    /**
71
-     * Fetch the single object with relations from storage.
72
-     *
73
-     * @param  integer $id Id of the requested model.
74
-     * @return \Illuminate\Http\Response
75
-     */
76
-    public function find($id)
77
-    {
78
-        return new $this->modelResource($this->repo->find($id, $this->relations));
79
-    }
80
-
81
-    /**
82
-     * Delete by the given id from storage.
83
-     *
84
-     * @param  integer $id Id of the deleted model.
85
-     * @return \Illuminate\Http\Response
86
-     */
87
-    public function delete($id)
88
-    {
89
-        return new GeneralResource($this->repo->delete($id));
90
-    }
91
-
92
-    /**
93
-     * Return the deleted models in pages based on the given conditions.
94
-     *
95
-     * @param Request $request
96
-     * @return \Illuminate\Http\Response
97
-     */
98
-    public function deleted(Request $request)
99
-    {
100
-        return $this->modelResource::collection($this->repo->deleted($request->all(), $request->query('perPage'), $request->query('sortBy'), $request->query('desc')));
101
-    }
102
-
103
-    /**
104
-     * Restore the deleted model.
105
-     *
106
-     * @param  integer $id Id of the restored model.
107
-     * @return \Illuminate\Http\Response
108
-     */
109
-    public function restore($id)
110
-    {
111
-        return new GeneralResource($this->repo->restore($id));
112
-    }
113
-
114
-    /**
115
-     * Check if the logged in user can do the given permission.
116
-     *
117
-     * @param  string $permission
118
-     * @return void
119
-     */
120
-    private function checkPermission($permission)
121
-    {
122
-        \Auth::shouldUse('api');
123
-        $this->middleware('auth:api', ['except' => $this->skipLoginCheck]);
13
+	/**
14
+	 * The config implementation.
15
+	 *
16
+	 * @var array
17
+	 */
18
+	protected $config;
19
+
20
+	/**
21
+	 * The relations implementation.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $relations;
26
+
27
+	/**
28
+	 * The repo implementation.
29
+	 *
30
+	 * @var object
31
+	 */
32
+	protected $repo;
33
+
34
+	/**
35
+	 * Init new object.
36
+	 *
37
+	 * @param   mixed      $repo
38
+	 * @param   \App\Modules\Core\Utl\CoreConfig $config
39
+	 * @param   string     $modelResource
40
+	 * @return  void
41
+	 */
42
+	public function __construct($repo, $config, $modelResource)
43
+	{
44
+		$this->repo = new CachingDecorator($repo, \App::make('Illuminate\Contracts\Cache\Repository'));
45
+		$this->modelResource = $modelResource;
46
+		$this->config = $config->getConfig();
47
+		$this->modelName = explode('\\', get_called_class());
48
+		$this->modelName = lcfirst(str_replace('Controller', '', end($this->modelName)));
49
+		$this->validationRules = property_exists($this, 'validationRules') ? $this->validationRules : false;
50
+		$this->skipPermissionCheck = property_exists($this, 'skipPermissionCheck') ? $this->skipPermissionCheck : [];
51
+		$this->skipLoginCheck = property_exists($this, 'skipLoginCheck') ? $this->skipLoginCheck : [];
52
+		$route = explode('@', \Route::currentRouteAction())[1];
53
+
54
+		$this->setSessions();
55
+		$this->checkPermission($route);
56
+		$this->setRelations($route);
57
+	}
58
+
59
+	/**
60
+	 * Fetch all records with relations from storage.
61
+	 *
62
+	 * @param Request $request
63
+	 * @return \Illuminate\Http\Response
64
+	 */
65
+	public function index(Request $request)
66
+	{
67
+		return $this->modelResource::collection($this->repo->list($this->relations, $request->query(), $request->query('perPage'), $request->query('sortBy'), $request->query('desc')));
68
+	}
69
+
70
+	/**
71
+	 * Fetch the single object with relations from storage.
72
+	 *
73
+	 * @param  integer $id Id of the requested model.
74
+	 * @return \Illuminate\Http\Response
75
+	 */
76
+	public function find($id)
77
+	{
78
+		return new $this->modelResource($this->repo->find($id, $this->relations));
79
+	}
80
+
81
+	/**
82
+	 * Delete by the given id from storage.
83
+	 *
84
+	 * @param  integer $id Id of the deleted model.
85
+	 * @return \Illuminate\Http\Response
86
+	 */
87
+	public function delete($id)
88
+	{
89
+		return new GeneralResource($this->repo->delete($id));
90
+	}
91
+
92
+	/**
93
+	 * Return the deleted models in pages based on the given conditions.
94
+	 *
95
+	 * @param Request $request
96
+	 * @return \Illuminate\Http\Response
97
+	 */
98
+	public function deleted(Request $request)
99
+	{
100
+		return $this->modelResource::collection($this->repo->deleted($request->all(), $request->query('perPage'), $request->query('sortBy'), $request->query('desc')));
101
+	}
102
+
103
+	/**
104
+	 * Restore the deleted model.
105
+	 *
106
+	 * @param  integer $id Id of the restored model.
107
+	 * @return \Illuminate\Http\Response
108
+	 */
109
+	public function restore($id)
110
+	{
111
+		return new GeneralResource($this->repo->restore($id));
112
+	}
113
+
114
+	/**
115
+	 * Check if the logged in user can do the given permission.
116
+	 *
117
+	 * @param  string $permission
118
+	 * @return void
119
+	 */
120
+	private function checkPermission($permission)
121
+	{
122
+		\Auth::shouldUse('api');
123
+		$this->middleware('auth:api', ['except' => $this->skipLoginCheck]);
124 124
         
125
-        if (! in_array($permission, $this->skipLoginCheck) && $user = \Auth::user()) {
126
-            $user             = \Auth::user();
127
-            $isPasswordClient = $user->token()->client->password_client;
128
-            $this->updateLocaleAndTimezone($user);
129
-
130
-            if ($user->blocked) {
131
-                \ErrorHandler::userIsBlocked();
132
-            }
133
-
134
-            if ($isPasswordClient && (in_array($permission, $this->skipPermissionCheck) || \Core::users()->can($permission, $this->modelName))) {
135
-            } elseif (! $isPasswordClient && $user->tokenCan($this->modelName.'-'.$permission)) {
136
-            } else {
137
-                \ErrorHandler::noPermissions();
138
-            }
139
-        }
140
-    }
141
-
142
-    /**
143
-     * Set sessions based on the given headers in the request.
144
-     *
145
-     * @return void
146
-     */
147
-    private function setSessions()
148
-    {
149
-        \Session::put('time-zone', \Request::header('time-zone') ?: 0);
150
-
151
-        $locale = \Request::header('locale');
152
-        switch ($locale) {
153
-            case 'en':
154
-                \App::setLocale('en');
155
-                \Session::put('locale', 'en');
156
-                break;
157
-
158
-            case 'ar':
159
-                \App::setLocale('ar');
160
-                \Session::put('locale', 'ar');
161
-                break;
162
-
163
-            case 'all':
164
-                \App::setLocale('en');
165
-                \Session::put('locale', 'all');
166
-                break;
167
-
168
-            default:
169
-                \App::setLocale('en');
170
-                \Session::put('locale', 'en');
171
-                break;
172
-        }
173
-    }
174
-
175
-    /**
176
-     * Set relation based on the called api.
177
-     *
178
-     * @param  string $route
179
-     * @return void
180
-     */
181
-    private function setRelations($route)
182
-    {
183
-        $route           = $route !== 'index' ? $route : 'list';
184
-        $relations       = Arr::get($this->config['relations'], $this->modelName, false);
185
-        $this->relations = $relations && isset($relations[$route]) ? $relations[$route] : [];
186
-    }
187
-
188
-    /**
189
-     * Update the logged in user locale and time zone.
190
-     *
191
-     * @param  object $user
192
-     * @return void
193
-     */
194
-    private function updateLocaleAndTimezone($user)
195
-    {
196
-        $update   = false;
197
-        $locale   = \Session::get('locale');
198
-        $timezone = \Session::get('time-zone');
199
-        if ($locale && $locale !== 'all' && $locale !== $user->locale) {
200
-            $user->locale = $locale;
201
-            $update       = true;
202
-        }
203
-
204
-        if ($timezone && $timezone !== $user->timezone) {
205
-            $user->timezone = $timezone;
206
-            $update       = true;
207
-        }
208
-
209
-        if ($update) {
210
-            $user->save();
211
-        }
212
-    }
125
+		if (! in_array($permission, $this->skipLoginCheck) && $user = \Auth::user()) {
126
+			$user             = \Auth::user();
127
+			$isPasswordClient = $user->token()->client->password_client;
128
+			$this->updateLocaleAndTimezone($user);
129
+
130
+			if ($user->blocked) {
131
+				\ErrorHandler::userIsBlocked();
132
+			}
133
+
134
+			if ($isPasswordClient && (in_array($permission, $this->skipPermissionCheck) || \Core::users()->can($permission, $this->modelName))) {
135
+			} elseif (! $isPasswordClient && $user->tokenCan($this->modelName.'-'.$permission)) {
136
+			} else {
137
+				\ErrorHandler::noPermissions();
138
+			}
139
+		}
140
+	}
141
+
142
+	/**
143
+	 * Set sessions based on the given headers in the request.
144
+	 *
145
+	 * @return void
146
+	 */
147
+	private function setSessions()
148
+	{
149
+		\Session::put('time-zone', \Request::header('time-zone') ?: 0);
150
+
151
+		$locale = \Request::header('locale');
152
+		switch ($locale) {
153
+			case 'en':
154
+				\App::setLocale('en');
155
+				\Session::put('locale', 'en');
156
+				break;
157
+
158
+			case 'ar':
159
+				\App::setLocale('ar');
160
+				\Session::put('locale', 'ar');
161
+				break;
162
+
163
+			case 'all':
164
+				\App::setLocale('en');
165
+				\Session::put('locale', 'all');
166
+				break;
167
+
168
+			default:
169
+				\App::setLocale('en');
170
+				\Session::put('locale', 'en');
171
+				break;
172
+		}
173
+	}
174
+
175
+	/**
176
+	 * Set relation based on the called api.
177
+	 *
178
+	 * @param  string $route
179
+	 * @return void
180
+	 */
181
+	private function setRelations($route)
182
+	{
183
+		$route           = $route !== 'index' ? $route : 'list';
184
+		$relations       = Arr::get($this->config['relations'], $this->modelName, false);
185
+		$this->relations = $relations && isset($relations[$route]) ? $relations[$route] : [];
186
+	}
187
+
188
+	/**
189
+	 * Update the logged in user locale and time zone.
190
+	 *
191
+	 * @param  object $user
192
+	 * @return void
193
+	 */
194
+	private function updateLocaleAndTimezone($user)
195
+	{
196
+		$update   = false;
197
+		$locale   = \Session::get('locale');
198
+		$timezone = \Session::get('time-zone');
199
+		if ($locale && $locale !== 'all' && $locale !== $user->locale) {
200
+			$user->locale = $locale;
201
+			$update       = true;
202
+		}
203
+
204
+		if ($timezone && $timezone !== $user->timezone) {
205
+			$user->timezone = $timezone;
206
+			$update       = true;
207
+		}
208
+
209
+		if ($update) {
210
+			$user->save();
211
+		}
212
+	}
213 213
 }
Please login to merge, or discard this patch.