Completed
Push — master ( 2d22de...e2d103 )
by Sherif
02:14
created
src/Modules/Core/Http/Resources/Setting.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -6,28 +6,28 @@
 block discarded – undo
6 6
 
7 7
 class Setting extends JsonResource
8 8
 {
9
-    /**
10
-     * Indicates if the resource's collection keys should be preserved.
11
-     *
12
-     * @var bool
13
-     */
14
-    public $preserveKeys = true;
9
+	/**
10
+	 * Indicates if the resource's collection keys should be preserved.
11
+	 *
12
+	 * @var bool
13
+	 */
14
+	public $preserveKeys = true;
15 15
 
16
-    /**
17
-     * Transform the resource into an array.
18
-     *
19
-     * @param  \Illuminate\Http\Request  $request
20
-     * @return array
21
-     */
22
-    public function toArray($request)
23
-    {
24
-        return [
25
-            'id' => $this->id,
26
-            'name' => $this->name,
27
-            'value' => $this->value,
28
-            'key' => $this->key,
29
-            'createdAt' => $this->created_at,
30
-            'updatedAt' => $this->updated_at,
31
-        ];
32
-    }
16
+	/**
17
+	 * Transform the resource into an array.
18
+	 *
19
+	 * @param  \Illuminate\Http\Request  $request
20
+	 * @return array
21
+	 */
22
+	public function toArray($request)
23
+	{
24
+		return [
25
+			'id' => $this->id,
26
+			'name' => $this->name,
27
+			'value' => $this->value,
28
+			'key' => $this->key,
29
+			'createdAt' => $this->created_at,
30
+			'updatedAt' => $this->updated_at,
31
+		];
32
+	}
33 33
 }
Please login to merge, or discard this patch.
src/Modules/Core/Http/Controllers/BaseApiController.php 1 patch
Indentation   +297 added lines, -297 removed lines patch added patch discarded remove patch
@@ -9,303 +9,303 @@
 block discarded – undo
9 9
 
10 10
 class BaseApiController extends Controller
11 11
 {
12
-    /**
13
-     * The config implementation.
14
-     *
15
-     * @var array
16
-     */
17
-    protected $config;
18
-
19
-    /**
20
-     * The relations implementation.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $relations;
25
-
26
-    /**
27
-     * The repo implementation.
28
-     *
29
-     * @var object
30
-     */
31
-    protected $repo;
32
-
33
-    /**
34
-     * Init new object.
35
-     *
36
-     * @param   mixed      $repo
37
-     * @param   CoreConfig $config
38
-     * @param   string     $modelResource
39
-     * @return  void
40
-     */
41
-    public function __construct($repo, $config, $modelResource)
42
-    {
43
-        $this->repo = $repo;
44
-        $this->modelResource = $modelResource;
45
-        $this->config = $config->getConfig();
46
-        $this->modelName = explode('\\', get_called_class());
47
-        $this->modelName = lcfirst(str_replace('Controller', '', end($this->modelName)));
48
-        $this->validationRules = property_exists($this, 'validationRules') ? $this->validationRules : false;
49
-        $this->skipPermissionCheck = property_exists($this, 'skipPermissionCheck') ? $this->skipPermissionCheck : [];
50
-        $this->skipLoginCheck = property_exists($this, 'skipLoginCheck') ? $this->skipLoginCheck : [];
51
-        $route = explode('@', \Route::currentRouteAction())[1];
52
-
53
-        $this->setSessions();
54
-        $this->checkPermission($route);
55
-        $this->setRelations($route);
56
-    }
57
-
58
-    /**
59
-     * Fetch all records with relations from storage.
60
-     *
61
-     * @param  string  $sortBy The name of the column to sort by.
62
-     * @param  boolean $desc   Sort ascending or descinding (1: desc, 0: asc).
63
-     * @return \Illuminate\Http\Response
64
-     */
65
-    public function index($sortBy = 'created_at', $desc = 1)
66
-    {
67
-        return $this->modelResource::collection($this->repo->all($this->relations, $sortBy, $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
-     * Paginate all records with relations from storage
83
-     * that matche the given query.
84
-     *
85
-     * @param  string  $query   The search text.
86
-     * @param  integer $perPage Number of rows per page default 15.
87
-     * @param  string  $sortBy  The name of the column to sort by.
88
-     * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
89
-     * @return \Illuminate\Http\Response
90
-     */
91
-    public function search($query = '', $perPage = 15, $sortBy = 'created_at', $desc = 1)
92
-    {
93
-        return $this->modelResource::collection($this->repo->search($query, $perPage, $this->relations, $sortBy, $desc));
94
-    }
95
-
96
-    /**
97
-     * Fetch records from the storage based on the given
98
-     * condition.
99
-     *
100
-     * @param  \Illuminate\Http\Request  $request
101
-     * @param  string  $sortBy The name of the column to sort by.
102
-     * @param  boolean $desc   Sort ascending or descinding (1: desc, 0: asc).
103
-     * @return \Illuminate\Http\Response
104
-     */
105
-    public function findby(Request $request, $sortBy = 'created_at', $desc = 1)
106
-    {
107
-        return $this->modelResource::collection($this->repo->findBy($request->all(), $this->relations, $sortBy, $desc));
108
-    }
109
-
110
-    /**
111
-     * Fetch the first record from the storage based on the given
112
-     * condition.
113
-     *
114
-     * @param  \Illuminate\Http\Request  $request
115
-     * @return \Illuminate\Http\Response
116
-     */
117
-    public function first(Request $request)
118
-    {
119
-        return new $this->modelResource($this->repo->first($request->all(), $this->relations));
120
-    }
121
-
122
-    /**
123
-     * Paginate all records with relations from storage.
124
-     *
125
-     * @param  integer $perPage Number of rows per page default 15.
126
-     * @param  string  $sortBy  The name of the column to sort by.
127
-     * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
128
-     * @return \Illuminate\Http\Response
129
-     */
130
-    public function paginate($perPage = 15, $sortBy = 'created_at', $desc = 1)
131
-    {
132
-        return $this->modelResource::collection($this->repo->paginate($perPage, $this->relations, $sortBy, $desc));
133
-    }
134
-
135
-    /**
136
-     * Fetch all records with relations based on
137
-     * the given condition from storage in pages.
138
-     *
139
-     * @param  \Illuminate\Http\Request  $request
140
-     * @param  integer $perPage Number of rows per page default 15.
141
-     * @param  string  $sortBy  The name of the column to sort by.
142
-     * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
143
-     * @return \Illuminate\Http\Response
144
-     */
145
-    public function paginateby(Request $request, $perPage = 15, $sortBy = 'created_at', $desc = 1)
146
-    {
147
-        return $this->modelResource::collection($this->repo->paginateBy($request->all(), $perPage, $this->relations, $sortBy, $desc));
148
-    }
149
-
150
-    /**
151
-     * Save the given model to storage.
152
-     *
153
-     * @param  \Illuminate\Http\Request  $request
154
-     * @return \Illuminate\Http\Response
155
-     */
156
-    public function save(Request $request)
157
-    {
158
-        foreach ($this->validationRules as &$rule) {
159
-            if (strpos($rule, 'exists') && ! strpos($rule, 'deleted_at,NULL')) {
160
-                $rule .= ',deleted_at,NULL';
161
-            }
162
-
163
-            if ($request->has('id')) {
164
-                $rule = str_replace('{id}', $request->get('id'), $rule);
165
-            } else {
166
-                $rule = str_replace(',{id}', '', $rule);
167
-            }
168
-        }
12
+	/**
13
+	 * The config implementation.
14
+	 *
15
+	 * @var array
16
+	 */
17
+	protected $config;
18
+
19
+	/**
20
+	 * The relations implementation.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $relations;
25
+
26
+	/**
27
+	 * The repo implementation.
28
+	 *
29
+	 * @var object
30
+	 */
31
+	protected $repo;
32
+
33
+	/**
34
+	 * Init new object.
35
+	 *
36
+	 * @param   mixed      $repo
37
+	 * @param   CoreConfig $config
38
+	 * @param   string     $modelResource
39
+	 * @return  void
40
+	 */
41
+	public function __construct($repo, $config, $modelResource)
42
+	{
43
+		$this->repo = $repo;
44
+		$this->modelResource = $modelResource;
45
+		$this->config = $config->getConfig();
46
+		$this->modelName = explode('\\', get_called_class());
47
+		$this->modelName = lcfirst(str_replace('Controller', '', end($this->modelName)));
48
+		$this->validationRules = property_exists($this, 'validationRules') ? $this->validationRules : false;
49
+		$this->skipPermissionCheck = property_exists($this, 'skipPermissionCheck') ? $this->skipPermissionCheck : [];
50
+		$this->skipLoginCheck = property_exists($this, 'skipLoginCheck') ? $this->skipLoginCheck : [];
51
+		$route = explode('@', \Route::currentRouteAction())[1];
52
+
53
+		$this->setSessions();
54
+		$this->checkPermission($route);
55
+		$this->setRelations($route);
56
+	}
57
+
58
+	/**
59
+	 * Fetch all records with relations from storage.
60
+	 *
61
+	 * @param  string  $sortBy The name of the column to sort by.
62
+	 * @param  boolean $desc   Sort ascending or descinding (1: desc, 0: asc).
63
+	 * @return \Illuminate\Http\Response
64
+	 */
65
+	public function index($sortBy = 'created_at', $desc = 1)
66
+	{
67
+		return $this->modelResource::collection($this->repo->all($this->relations, $sortBy, $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
+	 * Paginate all records with relations from storage
83
+	 * that matche the given query.
84
+	 *
85
+	 * @param  string  $query   The search text.
86
+	 * @param  integer $perPage Number of rows per page default 15.
87
+	 * @param  string  $sortBy  The name of the column to sort by.
88
+	 * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
89
+	 * @return \Illuminate\Http\Response
90
+	 */
91
+	public function search($query = '', $perPage = 15, $sortBy = 'created_at', $desc = 1)
92
+	{
93
+		return $this->modelResource::collection($this->repo->search($query, $perPage, $this->relations, $sortBy, $desc));
94
+	}
95
+
96
+	/**
97
+	 * Fetch records from the storage based on the given
98
+	 * condition.
99
+	 *
100
+	 * @param  \Illuminate\Http\Request  $request
101
+	 * @param  string  $sortBy The name of the column to sort by.
102
+	 * @param  boolean $desc   Sort ascending or descinding (1: desc, 0: asc).
103
+	 * @return \Illuminate\Http\Response
104
+	 */
105
+	public function findby(Request $request, $sortBy = 'created_at', $desc = 1)
106
+	{
107
+		return $this->modelResource::collection($this->repo->findBy($request->all(), $this->relations, $sortBy, $desc));
108
+	}
109
+
110
+	/**
111
+	 * Fetch the first record from the storage based on the given
112
+	 * condition.
113
+	 *
114
+	 * @param  \Illuminate\Http\Request  $request
115
+	 * @return \Illuminate\Http\Response
116
+	 */
117
+	public function first(Request $request)
118
+	{
119
+		return new $this->modelResource($this->repo->first($request->all(), $this->relations));
120
+	}
121
+
122
+	/**
123
+	 * Paginate all records with relations from storage.
124
+	 *
125
+	 * @param  integer $perPage Number of rows per page default 15.
126
+	 * @param  string  $sortBy  The name of the column to sort by.
127
+	 * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
128
+	 * @return \Illuminate\Http\Response
129
+	 */
130
+	public function paginate($perPage = 15, $sortBy = 'created_at', $desc = 1)
131
+	{
132
+		return $this->modelResource::collection($this->repo->paginate($perPage, $this->relations, $sortBy, $desc));
133
+	}
134
+
135
+	/**
136
+	 * Fetch all records with relations based on
137
+	 * the given condition from storage in pages.
138
+	 *
139
+	 * @param  \Illuminate\Http\Request  $request
140
+	 * @param  integer $perPage Number of rows per page default 15.
141
+	 * @param  string  $sortBy  The name of the column to sort by.
142
+	 * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
143
+	 * @return \Illuminate\Http\Response
144
+	 */
145
+	public function paginateby(Request $request, $perPage = 15, $sortBy = 'created_at', $desc = 1)
146
+	{
147
+		return $this->modelResource::collection($this->repo->paginateBy($request->all(), $perPage, $this->relations, $sortBy, $desc));
148
+	}
149
+
150
+	/**
151
+	 * Save the given model to storage.
152
+	 *
153
+	 * @param  \Illuminate\Http\Request  $request
154
+	 * @return \Illuminate\Http\Response
155
+	 */
156
+	public function save(Request $request)
157
+	{
158
+		foreach ($this->validationRules as &$rule) {
159
+			if (strpos($rule, 'exists') && ! strpos($rule, 'deleted_at,NULL')) {
160
+				$rule .= ',deleted_at,NULL';
161
+			}
162
+
163
+			if ($request->has('id')) {
164
+				$rule = str_replace('{id}', $request->get('id'), $rule);
165
+			} else {
166
+				$rule = str_replace(',{id}', '', $rule);
167
+			}
168
+		}
169 169
         
170
-        $this->validate($request, $this->validationRules);
171
-
172
-        return $this->modelResource::collection($this->repo->save($request->all()));
173
-    }
174
-
175
-    /**
176
-     * Delete by the given id from storage.
177
-     *
178
-     * @param  integer $id Id of the deleted model.
179
-     * @return \Illuminate\Http\Response
180
-     */
181
-    public function delete($id)
182
-    {
183
-        return new GeneralResource($this->repo->delete($id));
184
-    }
185
-
186
-    /**
187
-     * Return the deleted models in pages based on the given conditions.
188
-     *
189
-     * @param  \Illuminate\Http\Request  $request
190
-     * @param  integer $perPage Number of rows per page default 15.
191
-     * @param  string  $sortBy  The name of the column to sort by.
192
-     * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
193
-     * @return \Illuminate\Http\Response
194
-     */
195
-    public function deleted(Request $request, $perPage = 15, $sortBy = 'created_at', $desc = 1)
196
-    {
197
-        return $this->modelResource::collection($this->repo->deleted($request->all(), $perPage, $sortBy, $desc));
198
-    }
199
-
200
-    /**
201
-     * Restore the deleted model.
202
-     *
203
-     * @param  integer $id Id of the restored model.
204
-     * @return \Illuminate\Http\Response
205
-     */
206
-    public function restore($id)
207
-    {
208
-        return new GeneralResource($this->repo->restore($id));
209
-    }
210
-
211
-    /**
212
-     * Check if the logged in user can do the given permission.
213
-     *
214
-     * @param  string $permission
215
-     * @return void
216
-     */
217
-    private function checkPermission($permission)
218
-    {
219
-        \Auth::shouldUse('api');
220
-        $this->middleware('auth:api', ['except' => $this->skipLoginCheck]);
170
+		$this->validate($request, $this->validationRules);
171
+
172
+		return $this->modelResource::collection($this->repo->save($request->all()));
173
+	}
174
+
175
+	/**
176
+	 * Delete by the given id from storage.
177
+	 *
178
+	 * @param  integer $id Id of the deleted model.
179
+	 * @return \Illuminate\Http\Response
180
+	 */
181
+	public function delete($id)
182
+	{
183
+		return new GeneralResource($this->repo->delete($id));
184
+	}
185
+
186
+	/**
187
+	 * Return the deleted models in pages based on the given conditions.
188
+	 *
189
+	 * @param  \Illuminate\Http\Request  $request
190
+	 * @param  integer $perPage Number of rows per page default 15.
191
+	 * @param  string  $sortBy  The name of the column to sort by.
192
+	 * @param  boolean $desc    Sort ascending or descinding (1: desc, 0: asc).
193
+	 * @return \Illuminate\Http\Response
194
+	 */
195
+	public function deleted(Request $request, $perPage = 15, $sortBy = 'created_at', $desc = 1)
196
+	{
197
+		return $this->modelResource::collection($this->repo->deleted($request->all(), $perPage, $sortBy, $desc));
198
+	}
199
+
200
+	/**
201
+	 * Restore the deleted model.
202
+	 *
203
+	 * @param  integer $id Id of the restored model.
204
+	 * @return \Illuminate\Http\Response
205
+	 */
206
+	public function restore($id)
207
+	{
208
+		return new GeneralResource($this->repo->restore($id));
209
+	}
210
+
211
+	/**
212
+	 * Check if the logged in user can do the given permission.
213
+	 *
214
+	 * @param  string $permission
215
+	 * @return void
216
+	 */
217
+	private function checkPermission($permission)
218
+	{
219
+		\Auth::shouldUse('api');
220
+		$this->middleware('auth:api', ['except' => $this->skipLoginCheck]);
221 221
         
222
-        if (! in_array($permission, $this->skipLoginCheck) && $user = \Auth::user()) {
223
-            $user             = \Auth::user();
224
-            $permission       = $permission !== 'index' ? $permission : 'list';
225
-            $isPasswordClient = $user->token()->client->password_client;
226
-            $this->updateLocaleAndTimezone($user);
227
-
228
-            if ($user->blocked) {
229
-                \ErrorHandler::userIsBlocked();
230
-            }
231
-
232
-            if ($isPasswordClient && (in_array($permission, $this->skipPermissionCheck) || \Core::users()->can($permission, $this->modelName))) {
233
-            } elseif (! $isPasswordClient && $user->tokenCan($this->modelName.'-'.$permission)) {
234
-            } else {
235
-                \ErrorHandler::noPermissions();
236
-            }
237
-        }
238
-    }
239
-
240
-    /**
241
-     * Set sessions based on the given headers in the request.
242
-     *
243
-     * @return void
244
-     */
245
-    private function setSessions()
246
-    {
247
-        \Session::put('time-zone', \Request::header('time-zone') ?: 0);
248
-
249
-        $locale = \Request::header('locale');
250
-        switch ($locale) {
251
-            case 'en':
252
-                \App::setLocale('en');
253
-                \Session::put('locale', 'en');
254
-                break;
255
-
256
-            case 'ar':
257
-                \App::setLocale('ar');
258
-                \Session::put('locale', 'ar');
259
-                break;
260
-
261
-            case 'all':
262
-                \App::setLocale('en');
263
-                \Session::put('locale', 'all');
264
-                break;
265
-
266
-            default:
267
-                \App::setLocale('en');
268
-                \Session::put('locale', 'en');
269
-                break;
270
-        }
271
-    }
272
-
273
-    /**
274
-     * Set relation based on the called api.
275
-     *
276
-     * @param  string $route
277
-     * @return void
278
-     */
279
-    private function setRelations($route)
280
-    {
281
-        $route           = $route !== 'index' ? $route : 'list';
282
-        $relations       = Arr::get($this->config['relations'], $this->modelName, false);
283
-        $this->relations = $relations && isset($relations[$route]) ? $relations[$route] : [];
284
-    }
285
-
286
-    /**
287
-     * Update the logged in user locale and time zone.
288
-     *
289
-     * @param  object $user
290
-     * @return void
291
-     */
292
-    private function updateLocaleAndTimezone($user)
293
-    {
294
-        $update   = false;
295
-        $locale   = \Session::get('locale');
296
-        $timezone = \Session::get('time-zone');
297
-        if ($locale && $locale !== 'all' && $locale !== $user->locale) {
298
-            $user->locale = $locale;
299
-            $update       = true;
300
-        }
301
-
302
-        if ($timezone && $timezone !== $user->timezone) {
303
-            $user->timezone = $timezone;
304
-            $update       = true;
305
-        }
306
-
307
-        if ($update) {
308
-            $user->save();
309
-        }
310
-    }
222
+		if (! in_array($permission, $this->skipLoginCheck) && $user = \Auth::user()) {
223
+			$user             = \Auth::user();
224
+			$permission       = $permission !== 'index' ? $permission : 'list';
225
+			$isPasswordClient = $user->token()->client->password_client;
226
+			$this->updateLocaleAndTimezone($user);
227
+
228
+			if ($user->blocked) {
229
+				\ErrorHandler::userIsBlocked();
230
+			}
231
+
232
+			if ($isPasswordClient && (in_array($permission, $this->skipPermissionCheck) || \Core::users()->can($permission, $this->modelName))) {
233
+			} elseif (! $isPasswordClient && $user->tokenCan($this->modelName.'-'.$permission)) {
234
+			} else {
235
+				\ErrorHandler::noPermissions();
236
+			}
237
+		}
238
+	}
239
+
240
+	/**
241
+	 * Set sessions based on the given headers in the request.
242
+	 *
243
+	 * @return void
244
+	 */
245
+	private function setSessions()
246
+	{
247
+		\Session::put('time-zone', \Request::header('time-zone') ?: 0);
248
+
249
+		$locale = \Request::header('locale');
250
+		switch ($locale) {
251
+			case 'en':
252
+				\App::setLocale('en');
253
+				\Session::put('locale', 'en');
254
+				break;
255
+
256
+			case 'ar':
257
+				\App::setLocale('ar');
258
+				\Session::put('locale', 'ar');
259
+				break;
260
+
261
+			case 'all':
262
+				\App::setLocale('en');
263
+				\Session::put('locale', 'all');
264
+				break;
265
+
266
+			default:
267
+				\App::setLocale('en');
268
+				\Session::put('locale', 'en');
269
+				break;
270
+		}
271
+	}
272
+
273
+	/**
274
+	 * Set relation based on the called api.
275
+	 *
276
+	 * @param  string $route
277
+	 * @return void
278
+	 */
279
+	private function setRelations($route)
280
+	{
281
+		$route           = $route !== 'index' ? $route : 'list';
282
+		$relations       = Arr::get($this->config['relations'], $this->modelName, false);
283
+		$this->relations = $relations && isset($relations[$route]) ? $relations[$route] : [];
284
+	}
285
+
286
+	/**
287
+	 * Update the logged in user locale and time zone.
288
+	 *
289
+	 * @param  object $user
290
+	 * @return void
291
+	 */
292
+	private function updateLocaleAndTimezone($user)
293
+	{
294
+		$update   = false;
295
+		$locale   = \Session::get('locale');
296
+		$timezone = \Session::get('time-zone');
297
+		if ($locale && $locale !== 'all' && $locale !== $user->locale) {
298
+			$user->locale = $locale;
299
+			$update       = true;
300
+		}
301
+
302
+		if ($timezone && $timezone !== $user->timezone) {
303
+			$user->timezone = $timezone;
304
+			$update       = true;
305
+		}
306
+
307
+		if ($update) {
308
+			$user->save();
309
+		}
310
+	}
311 311
 }
Please login to merge, or discard this patch.
src/Modules/Core/Http/Controllers/SettingsController.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -10,36 +10,36 @@
 block discarded – undo
10 10
 
11 11
 class SettingsController extends BaseApiController
12 12
 {
13
-    /**
14
-     * The validations rules used by the base api controller
15
-     * to check before add.
16
-     * @var array
17
-     */
18
-    protected $validationRules = [
19
-        'id'    => 'required|exists:settings,id',
20
-        'value' => 'required|string'
21
-    ];
13
+	/**
14
+	 * The validations rules used by the base api controller
15
+	 * to check before add.
16
+	 * @var array
17
+	 */
18
+	protected $validationRules = [
19
+		'id'    => 'required|exists:settings,id',
20
+		'value' => 'required|string'
21
+	];
22 22
 
23
-    /**
24
-     * Init new object.
25
-     *
26
-     * @param   SettingRepository $repo
27
-     * @param   CoreConfig        $config
28
-     * @return  void
29
-     */
30
-    public function __construct(SettingRepository $repo, CoreConfig $config)
31
-    {
32
-        parent::__construct($repo, $config, 'App\Modules\Core\Http\Resources\Setting');
33
-    }
23
+	/**
24
+	 * Init new object.
25
+	 *
26
+	 * @param   SettingRepository $repo
27
+	 * @param   CoreConfig        $config
28
+	 * @return  void
29
+	 */
30
+	public function __construct(SettingRepository $repo, CoreConfig $config)
31
+	{
32
+		parent::__construct($repo, $config, 'App\Modules\Core\Http\Resources\Setting');
33
+	}
34 34
 
35
-    /**
36
-     * Save list of settings.
37
-     *
38
-     * @param  \Illuminate\Http\Request  $request
39
-     * @return \Illuminate\Http\Response
40
-     */
41
-    public function saveMany(Request $request)
42
-    {
43
-        return new GeneralResource($this->repo->saveMany($request->all()));
44
-    }
35
+	/**
36
+	 * Save list of settings.
37
+	 *
38
+	 * @param  \Illuminate\Http\Request  $request
39
+	 * @return \Illuminate\Http\Response
40
+	 */
41
+	public function saveMany(Request $request)
42
+	{
43
+		return new GeneralResource($this->repo->saveMany($request->all()));
44
+	}
45 45
 }
Please login to merge, or discard this patch.
src/Modules/Core/AbstractRepositories/AbstractRepository.php 1 patch
Indentation   +616 added lines, -616 removed lines patch added patch discarded remove patch
@@ -6,633 +6,633 @@
 block discarded – undo
6 6
 
7 7
 abstract class AbstractRepository implements RepositoryInterface
8 8
 {
9
-    /**
10
-     * The model implementation.
11
-     *
12
-     * @var object
13
-     */
14
-    public $model;
9
+	/**
10
+	 * The model implementation.
11
+	 *
12
+	 * @var object
13
+	 */
14
+	public $model;
15 15
     
16
-    /**
17
-     * The config implementation.
18
-     *
19
-     * @var array
20
-     */
21
-    protected $config;
16
+	/**
17
+	 * The config implementation.
18
+	 *
19
+	 * @var array
20
+	 */
21
+	protected $config;
22 22
     
23
-    /**
24
-     * Create new AbstractRepository instance.
25
-     */
26
-    public function __construct()
27
-    {
28
-        $this->config = \CoreConfig::getConfig();
29
-        $this->model  = \App::make($this->getModel());
30
-    }
31
-
32
-    /**
33
-     * Fetch all records with relations from the storage.
34
-     *
35
-     * @param  array   $relations
36
-     * @param  string  $sortBy
37
-     * @param  boolean $desc
38
-     * @param  array   $columns
39
-     * @return collection
40
-     */
41
-    public function all($relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
42
-    {
43
-        $sort = $desc ? 'desc' : 'asc';
44
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->get($columns);
45
-    }
46
-
47
-    /**
48
-     * Fetch all records with relations from storage in pages
49
-     * that matche the given query.
50
-     *
51
-     * @param  string  $query
52
-     * @param  integer $perPage
53
-     * @param  array   $relations
54
-     * @param  string  $sortBy
55
-     * @param  boolean $desc
56
-     * @param  array   $columns
57
-     * @return collection
58
-     */
59
-    public function search($query, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
60
-    {
61
-        $model            = call_user_func_array("{$this->getModel()}::with", array($relations));
62
-        $conditionColumns = $this->model->searchable;
63
-        $sort             = $desc ? 'desc' : 'asc';
64
-
65
-        /**
66
-         * Construct the select conditions for the model.
67
-         */
68
-        $model->where(function ($q) use ($query, $conditionColumns, $relations) {
69
-
70
-            if (count($conditionColumns)) {
71
-                $column = 'LOWER('.array_shift($conditionColumns).')';
72
-                if (Str::contains($column, '->')) {
73
-                    $column = $this->wrapJsonSelector($column);
74
-                }
75
-
76
-                /**
77
-                 * Use the first element in the model columns to construct the first condition.
78
-                 */
79
-                $q->where(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
80
-            }
81
-
82
-            /**
83
-             * Loop through the rest of the columns to construct or where conditions.
84
-             */
85
-            foreach ($conditionColumns as $column) {
86
-                $column = 'LOWER('.$column.')';
87
-                if (Str::contains($column, '->')) {
88
-                    $column = $this->wrapJsonSelector($column);
89
-                }
90
-
91
-                $q->orWhere(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
92
-            }
93
-
94
-            /**
95
-             * Loop through the model relations.
96
-             */
97
-            foreach ($relations as $relation) {
98
-                /**
99
-                 * Remove the sub relation if exists.
100
-                 */
101
-                $relation = explode('.', $relation)[0];
102
-
103
-                /**
104
-                 * Try to fetch the relation repository from the core.
105
-                 */
106
-                if (\Core::$relation()) {
107
-                    /**
108
-                     * Construct the relation condition.
109
-                     */
110
-                    $q->orWhereHas($relation, function ($subModel) use ($query, $relation) {
111
-
112
-                        $subModel->where(function ($q) use ($query, $relation) {
113
-
114
-                            /**
115
-                             * Get columns of the relation.
116
-                             */
117
-                            $subConditionColumns = \Core::$relation()->model->searchable;
118
-
119
-                            if (count($subConditionColumns)) {
120
-                                $column = 'LOWER('.array_shift($subConditionColumns).')';
121
-                                if (Str::contains($column, '->')) {
122
-                                    $column = $this->wrapJsonSelector($column);
123
-                                }
124
-
125
-                                /**
126
-                                 * Use the first element in the relation model columns to construct the first condition.
127
-                                 */
128
-                                $q->where(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
129
-                            }
130
-
131
-                            /**
132
-                             * Loop through the rest of the columns to construct or where conditions.
133
-                             */
134
-                            foreach ($subConditionColumns as $subConditionColumn) {
135
-                                $column = 'LOWER('.$subConditionColumn.')';
136
-                                if (Str::contains($column, '->')) {
137
-                                    $column = $this->wrapJsonSelector($column);
138
-                                }
23
+	/**
24
+	 * Create new AbstractRepository instance.
25
+	 */
26
+	public function __construct()
27
+	{
28
+		$this->config = \CoreConfig::getConfig();
29
+		$this->model  = \App::make($this->getModel());
30
+	}
31
+
32
+	/**
33
+	 * Fetch all records with relations from the storage.
34
+	 *
35
+	 * @param  array   $relations
36
+	 * @param  string  $sortBy
37
+	 * @param  boolean $desc
38
+	 * @param  array   $columns
39
+	 * @return collection
40
+	 */
41
+	public function all($relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
42
+	{
43
+		$sort = $desc ? 'desc' : 'asc';
44
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->get($columns);
45
+	}
46
+
47
+	/**
48
+	 * Fetch all records with relations from storage in pages
49
+	 * that matche the given query.
50
+	 *
51
+	 * @param  string  $query
52
+	 * @param  integer $perPage
53
+	 * @param  array   $relations
54
+	 * @param  string  $sortBy
55
+	 * @param  boolean $desc
56
+	 * @param  array   $columns
57
+	 * @return collection
58
+	 */
59
+	public function search($query, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
60
+	{
61
+		$model            = call_user_func_array("{$this->getModel()}::with", array($relations));
62
+		$conditionColumns = $this->model->searchable;
63
+		$sort             = $desc ? 'desc' : 'asc';
64
+
65
+		/**
66
+		 * Construct the select conditions for the model.
67
+		 */
68
+		$model->where(function ($q) use ($query, $conditionColumns, $relations) {
69
+
70
+			if (count($conditionColumns)) {
71
+				$column = 'LOWER('.array_shift($conditionColumns).')';
72
+				if (Str::contains($column, '->')) {
73
+					$column = $this->wrapJsonSelector($column);
74
+				}
75
+
76
+				/**
77
+				 * Use the first element in the model columns to construct the first condition.
78
+				 */
79
+				$q->where(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
80
+			}
81
+
82
+			/**
83
+			 * Loop through the rest of the columns to construct or where conditions.
84
+			 */
85
+			foreach ($conditionColumns as $column) {
86
+				$column = 'LOWER('.$column.')';
87
+				if (Str::contains($column, '->')) {
88
+					$column = $this->wrapJsonSelector($column);
89
+				}
90
+
91
+				$q->orWhere(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
92
+			}
93
+
94
+			/**
95
+			 * Loop through the model relations.
96
+			 */
97
+			foreach ($relations as $relation) {
98
+				/**
99
+				 * Remove the sub relation if exists.
100
+				 */
101
+				$relation = explode('.', $relation)[0];
102
+
103
+				/**
104
+				 * Try to fetch the relation repository from the core.
105
+				 */
106
+				if (\Core::$relation()) {
107
+					/**
108
+					 * Construct the relation condition.
109
+					 */
110
+					$q->orWhereHas($relation, function ($subModel) use ($query, $relation) {
111
+
112
+						$subModel->where(function ($q) use ($query, $relation) {
113
+
114
+							/**
115
+							 * Get columns of the relation.
116
+							 */
117
+							$subConditionColumns = \Core::$relation()->model->searchable;
118
+
119
+							if (count($subConditionColumns)) {
120
+								$column = 'LOWER('.array_shift($subConditionColumns).')';
121
+								if (Str::contains($column, '->')) {
122
+									$column = $this->wrapJsonSelector($column);
123
+								}
124
+
125
+								/**
126
+								 * Use the first element in the relation model columns to construct the first condition.
127
+								 */
128
+								$q->where(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
129
+							}
130
+
131
+							/**
132
+							 * Loop through the rest of the columns to construct or where conditions.
133
+							 */
134
+							foreach ($subConditionColumns as $subConditionColumn) {
135
+								$column = 'LOWER('.$subConditionColumn.')';
136
+								if (Str::contains($column, '->')) {
137
+									$column = $this->wrapJsonSelector($column);
138
+								}
139 139
                                 
140
-                                $q->orWhere(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
141
-                            }
142
-                        });
143
-                    });
144
-                }
145
-            }
146
-        });
140
+								$q->orWhere(\DB::raw($column), 'LIKE', '%'.strtolower($query).'%');
141
+							}
142
+						});
143
+					});
144
+				}
145
+			}
146
+		});
147 147
         
148
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
149
-    }
148
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
149
+	}
150 150
     
151
-    /**
152
-     * Fetch all records with relations from storage in pages.
153
-     *
154
-     * @param  integer $perPage
155
-     * @param  array   $relations
156
-     * @param  string  $sortBy
157
-     * @param  boolean $desc
158
-     * @param  array   $columns
159
-     * @return collection
160
-     */
161
-    public function paginate($perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
162
-    {
163
-        $sort = $desc ? 'desc' : 'asc';
164
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->paginate($perPage, $columns);
165
-    }
166
-
167
-    /**
168
-     * Fetch all records with relations based on
169
-     * the given condition from storage in pages.
170
-     *
171
-     * @param  array   $conditions array of conditions
172
-     * @param  integer $perPage
173
-     * @param  array   $relations
174
-     * @param  string  $sortBy
175
-     * @param  boolean $desc
176
-     * @param  array   $columns
177
-     * @return collection
178
-     */
179
-    public function paginateBy($conditions, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
180
-    {
181
-        unset($conditions['page']);
182
-        $conditions = $this->constructConditions($conditions, $this->model);
183
-        $sort       = $desc ? 'desc' : 'asc';
184
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
185
-    }
151
+	/**
152
+	 * Fetch all records with relations from storage in pages.
153
+	 *
154
+	 * @param  integer $perPage
155
+	 * @param  array   $relations
156
+	 * @param  string  $sortBy
157
+	 * @param  boolean $desc
158
+	 * @param  array   $columns
159
+	 * @return collection
160
+	 */
161
+	public function paginate($perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
162
+	{
163
+		$sort = $desc ? 'desc' : 'asc';
164
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->paginate($perPage, $columns);
165
+	}
166
+
167
+	/**
168
+	 * Fetch all records with relations based on
169
+	 * the given condition from storage in pages.
170
+	 *
171
+	 * @param  array   $conditions array of conditions
172
+	 * @param  integer $perPage
173
+	 * @param  array   $relations
174
+	 * @param  string  $sortBy
175
+	 * @param  boolean $desc
176
+	 * @param  array   $columns
177
+	 * @return collection
178
+	 */
179
+	public function paginateBy($conditions, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
180
+	{
181
+		unset($conditions['page']);
182
+		$conditions = $this->constructConditions($conditions, $this->model);
183
+		$sort       = $desc ? 'desc' : 'asc';
184
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
185
+	}
186 186
     
187
-    /**
188
-     * Save the given model to the storage.
189
-     *
190
-     * @param  array $data
191
-     * @return mixed
192
-     */
193
-    public function save(array $data)
194
-    {
195
-        \Session::put('locale', 'all');
196
-        $model      = false;
197
-        $modelClass = $this->model;
198
-        $relations  = [];
199
-
200
-        \DB::transaction(function () use (&$model, &$relations, $data, $modelClass) {
201
-            /**
202
-             * If the id is present in the data then select the model for updating,
203
-             * else create new model.
204
-             * @var array
205
-             */
206
-            $model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
207
-            if (! $model) {
208
-                \ErrorHandler::notFound(class_basename($modelClass).' with id : '.$data['id']);
209
-            }
210
-
211
-            /**
212
-             * Construct the model object with the given data,
213
-             * and if there is a relation add it to relations array,
214
-             * then save the model.
215
-             */
216
-            foreach ($data as $key => $value) {
217
-                /**
218
-                 * If the attribute is a relation.
219
-                 */
220
-                $relation = camel_case($key);
221
-                if (method_exists($model, $relation) && \Core::$relation()) {
222
-                    /**
223
-                     * Check if the relation is a collection.
224
-                     */
225
-                    if (class_basename($model->$relation) == 'Collection') {
226
-                        /**
227
-                         * If the relation has no value then marke the relation data
228
-                         * related to the model to be deleted.
229
-                         */
230
-                        if (! $value || ! count($value)) {
231
-                            $relations[$relation] = 'delete';
232
-                        }
233
-                    }
234
-                    if (is_array($value)) {
235
-                        /**
236
-                         * Loop through the relation data.
237
-                         */
238
-                        foreach ($value as $attr => $val) {
239
-                            /**
240
-                             * Get the relation model.
241
-                             */
242
-                            $relationBaseModel = \Core::$relation()->model;
243
-
244
-                            /**
245
-                             * Check if the relation is a collection.
246
-                             */
247
-                            if (class_basename($model->$relation) == 'Collection') {
248
-                                /**
249
-                                 * If the id is present in the data then select the relation model for updating,
250
-                                 * else create new model.
251
-                                 */
252
-                                $relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
253
-
254
-                                /**
255
-                                 * If model doesn't exists.
256
-                                 */
257
-                                if (! $relationModel) {
258
-                                    \ErrorHandler::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
259
-                                }
260
-
261
-                                /**
262
-                                 * Loop through the relation attributes.
263
-                                 */
264
-                                foreach ($val as $attr => $val) {
265
-                                    /**
266
-                                     * Prevent the sub relations or attributes not in the fillable.
267
-                                     */
268
-                                    if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false) {
269
-                                        $relationModel->$attr = $val;
270
-                                    }
271
-                                }
272
-
273
-                                $relations[$relation][] = $relationModel;
274
-                            } else {
275
-                                /**
276
-                                 * Prevent the sub relations.
277
-                                 */
278
-                                if (gettype($val) !== 'object' && gettype($val) !== 'array') {
279
-                                    /**
280
-                                     * If the id is present in the data then select the relation model for updating,
281
-                                     * else create new model.
282
-                                     */
283
-                                    $relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
284
-
285
-                                    /**
286
-                                     * If model doesn't exists.
287
-                                     */
288
-                                    if (! $relationModel) {
289
-                                        \ErrorHandler::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
290
-                                    }
291
-
292
-                                    foreach ($value as $relationAttribute => $relationValue) {
293
-                                        /**
294
-                                         * Prevent attributes not in the fillable.
295
-                                         */
296
-                                        if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
297
-                                            $relationModel->$relationAttribute = $relationValue;
298
-                                        }
299
-                                    }
300
-
301
-                                    $relations[$relation] = $relationModel;
302
-                                }
303
-                            }
304
-                        }
305
-                    }
306
-                } elseif (array_search($key, $model->getFillable(), true) !== false) {
307
-                    /**
308
-                     * If the attribute isn't a relation and prevent attributes not in the fillable.
309
-                     */
310
-                    $model->$key = $value;
311
-                }
312
-            }
313
-
314
-            /**
315
-             * Loop through the relations array.
316
-             */
317
-            foreach ($relations as $key => $value) {
318
-                /**
319
-                 * If the relation is marked for delete then delete it.
320
-                 */
321
-                if ($value == 'delete' && $model->$key()->count()) {
322
-                    $model->$key()->delete();
323
-                } elseif (gettype($value) == 'array') {
324
-                    /**
325
-                     * Save the model.
326
-                     */
327
-                    $model->save();
328
-                    $ids = [];
329
-
330
-                    /**
331
-                     * Loop through the relations.
332
-                     */
333
-                    foreach ($value as $val) {
334
-                        switch (class_basename($model->$key())) {
335
-                            /**
336
-                             * If the relation is one to many then update it's foreign key with
337
-                             * the model id and save it then add its id to ids array to delete all
338
-                             * relations who's id isn't in the ids array.
339
-                             */
340
-                            case 'HasMany':
341
-                                $foreignKeyName       = $model->$key()->getForeignKeyName();
342
-                                $val->$foreignKeyName = $model->id;
343
-                                $val->save();
344
-                                $ids[] = $val->id;
345
-                                break;
346
-
347
-                            /**
348
-                             * If the relation is many to many then add it's id to the ids array to
349
-                             * attache these ids to the model.
350
-                             */
351
-                            case 'BelongsToMany':
352
-                                $val->save();
353
-                                $ids[] = $val->id;
354
-                                break;
355
-                        }
356
-                    }
357
-                    switch (class_basename($model->$key())) {
358
-                        /**
359
-                         * If the relation is one to many then delete all
360
-                         * relations who's id isn't in the ids array.
361
-                         */
362
-                        case 'HasMany':
363
-                            $model->$key()->whereNotIn('id', $ids)->delete();
364
-                            break;
365
-
366
-                        /**
367
-                         * If the relation is many to many then
368
-                         * detach the previous data and attach
369
-                         * the ids array to the model.
370
-                         */
371
-                        case 'BelongsToMany':
372
-                            $model->$key()->detach();
373
-                            $model->$key()->attach($ids);
374
-                            break;
375
-                    }
376
-                } else {
377
-                    switch (class_basename($model->$key())) {
378
-                        /**
379
-                         * If the relation is one to one.
380
-                         */
381
-                        case 'HasOne':
382
-                            /**
383
-                             * Save the model.
384
-                             */
385
-                            $model->save();
386
-                            $foreignKeyName         = $model->$key()->getForeignKeyName();
387
-                            $value->$foreignKeyName = $model->id;
388
-                            $value->save();
389
-                            break;
390
-                        case 'BelongsTo':
391
-                            /**
392
-                             * Save the model.
393
-                             */
394
-                            $value->save();
395
-                            $model->$key()->associate($value);
396
-                            break;
397
-                    }
398
-                }
399
-            }
400
-
401
-            /**
402
-             * Save the model.
403
-             */
404
-            $model->save();
405
-        });
187
+	/**
188
+	 * Save the given model to the storage.
189
+	 *
190
+	 * @param  array $data
191
+	 * @return mixed
192
+	 */
193
+	public function save(array $data)
194
+	{
195
+		\Session::put('locale', 'all');
196
+		$model      = false;
197
+		$modelClass = $this->model;
198
+		$relations  = [];
199
+
200
+		\DB::transaction(function () use (&$model, &$relations, $data, $modelClass) {
201
+			/**
202
+			 * If the id is present in the data then select the model for updating,
203
+			 * else create new model.
204
+			 * @var array
205
+			 */
206
+			$model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
207
+			if (! $model) {
208
+				\ErrorHandler::notFound(class_basename($modelClass).' with id : '.$data['id']);
209
+			}
210
+
211
+			/**
212
+			 * Construct the model object with the given data,
213
+			 * and if there is a relation add it to relations array,
214
+			 * then save the model.
215
+			 */
216
+			foreach ($data as $key => $value) {
217
+				/**
218
+				 * If the attribute is a relation.
219
+				 */
220
+				$relation = camel_case($key);
221
+				if (method_exists($model, $relation) && \Core::$relation()) {
222
+					/**
223
+					 * Check if the relation is a collection.
224
+					 */
225
+					if (class_basename($model->$relation) == 'Collection') {
226
+						/**
227
+						 * If the relation has no value then marke the relation data
228
+						 * related to the model to be deleted.
229
+						 */
230
+						if (! $value || ! count($value)) {
231
+							$relations[$relation] = 'delete';
232
+						}
233
+					}
234
+					if (is_array($value)) {
235
+						/**
236
+						 * Loop through the relation data.
237
+						 */
238
+						foreach ($value as $attr => $val) {
239
+							/**
240
+							 * Get the relation model.
241
+							 */
242
+							$relationBaseModel = \Core::$relation()->model;
243
+
244
+							/**
245
+							 * Check if the relation is a collection.
246
+							 */
247
+							if (class_basename($model->$relation) == 'Collection') {
248
+								/**
249
+								 * If the id is present in the data then select the relation model for updating,
250
+								 * else create new model.
251
+								 */
252
+								$relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
253
+
254
+								/**
255
+								 * If model doesn't exists.
256
+								 */
257
+								if (! $relationModel) {
258
+									\ErrorHandler::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
259
+								}
260
+
261
+								/**
262
+								 * Loop through the relation attributes.
263
+								 */
264
+								foreach ($val as $attr => $val) {
265
+									/**
266
+									 * Prevent the sub relations or attributes not in the fillable.
267
+									 */
268
+									if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false) {
269
+										$relationModel->$attr = $val;
270
+									}
271
+								}
272
+
273
+								$relations[$relation][] = $relationModel;
274
+							} else {
275
+								/**
276
+								 * Prevent the sub relations.
277
+								 */
278
+								if (gettype($val) !== 'object' && gettype($val) !== 'array') {
279
+									/**
280
+									 * If the id is present in the data then select the relation model for updating,
281
+									 * else create new model.
282
+									 */
283
+									$relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
284
+
285
+									/**
286
+									 * If model doesn't exists.
287
+									 */
288
+									if (! $relationModel) {
289
+										\ErrorHandler::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
290
+									}
291
+
292
+									foreach ($value as $relationAttribute => $relationValue) {
293
+										/**
294
+										 * Prevent attributes not in the fillable.
295
+										 */
296
+										if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
297
+											$relationModel->$relationAttribute = $relationValue;
298
+										}
299
+									}
300
+
301
+									$relations[$relation] = $relationModel;
302
+								}
303
+							}
304
+						}
305
+					}
306
+				} elseif (array_search($key, $model->getFillable(), true) !== false) {
307
+					/**
308
+					 * If the attribute isn't a relation and prevent attributes not in the fillable.
309
+					 */
310
+					$model->$key = $value;
311
+				}
312
+			}
313
+
314
+			/**
315
+			 * Loop through the relations array.
316
+			 */
317
+			foreach ($relations as $key => $value) {
318
+				/**
319
+				 * If the relation is marked for delete then delete it.
320
+				 */
321
+				if ($value == 'delete' && $model->$key()->count()) {
322
+					$model->$key()->delete();
323
+				} elseif (gettype($value) == 'array') {
324
+					/**
325
+					 * Save the model.
326
+					 */
327
+					$model->save();
328
+					$ids = [];
329
+
330
+					/**
331
+					 * Loop through the relations.
332
+					 */
333
+					foreach ($value as $val) {
334
+						switch (class_basename($model->$key())) {
335
+							/**
336
+							 * If the relation is one to many then update it's foreign key with
337
+							 * the model id and save it then add its id to ids array to delete all
338
+							 * relations who's id isn't in the ids array.
339
+							 */
340
+							case 'HasMany':
341
+								$foreignKeyName       = $model->$key()->getForeignKeyName();
342
+								$val->$foreignKeyName = $model->id;
343
+								$val->save();
344
+								$ids[] = $val->id;
345
+								break;
346
+
347
+							/**
348
+							 * If the relation is many to many then add it's id to the ids array to
349
+							 * attache these ids to the model.
350
+							 */
351
+							case 'BelongsToMany':
352
+								$val->save();
353
+								$ids[] = $val->id;
354
+								break;
355
+						}
356
+					}
357
+					switch (class_basename($model->$key())) {
358
+						/**
359
+						 * If the relation is one to many then delete all
360
+						 * relations who's id isn't in the ids array.
361
+						 */
362
+						case 'HasMany':
363
+							$model->$key()->whereNotIn('id', $ids)->delete();
364
+							break;
365
+
366
+						/**
367
+						 * If the relation is many to many then
368
+						 * detach the previous data and attach
369
+						 * the ids array to the model.
370
+						 */
371
+						case 'BelongsToMany':
372
+							$model->$key()->detach();
373
+							$model->$key()->attach($ids);
374
+							break;
375
+					}
376
+				} else {
377
+					switch (class_basename($model->$key())) {
378
+						/**
379
+						 * If the relation is one to one.
380
+						 */
381
+						case 'HasOne':
382
+							/**
383
+							 * Save the model.
384
+							 */
385
+							$model->save();
386
+							$foreignKeyName         = $model->$key()->getForeignKeyName();
387
+							$value->$foreignKeyName = $model->id;
388
+							$value->save();
389
+							break;
390
+						case 'BelongsTo':
391
+							/**
392
+							 * Save the model.
393
+							 */
394
+							$value->save();
395
+							$model->$key()->associate($value);
396
+							break;
397
+					}
398
+				}
399
+			}
400
+
401
+			/**
402
+			 * Save the model.
403
+			 */
404
+			$model->save();
405
+		});
406 406
             
407
-        return $model;
408
-    }
407
+		return $model;
408
+	}
409 409
     
410
-    /**
411
-     * Update record in the storage based on the given
412
-     * condition.
413
-     *
414
-     * @param  var $value condition value
415
-     * @param  array $data
416
-     * @param  string $attribute condition column name
417
-     * @return void
418
-     */
419
-    public function update($value, array $data, $attribute = 'id')
420
-    {
421
-        if ($attribute == 'id') {
422
-            $model = $this->model->lockForUpdate()->find($value);
423
-            $model ? $model->update($data) : 0;
424
-        } else {
425
-            call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model) use ($data) {
426
-                $model->update($data);
427
-            });
428
-        }
429
-    }
430
-
431
-    /**
432
-     * Delete record from the storage based on the given
433
-     * condition.
434
-     *
435
-     * @param  var $value condition value
436
-     * @param  string $attribute condition column name
437
-     * @return void
438
-     */
439
-    public function delete($value, $attribute = 'id')
440
-    {
441
-        if ($attribute == 'id') {
442
-            \DB::transaction(function () use ($value, $attribute, &$result) {
443
-                $model = $this->model->lockForUpdate()->find($value);
444
-                if (! $model) {
445
-                    \ErrorHandler::notFound(class_basename($this->model).' with id : '.$value);
446
-                }
410
+	/**
411
+	 * Update record in the storage based on the given
412
+	 * condition.
413
+	 *
414
+	 * @param  var $value condition value
415
+	 * @param  array $data
416
+	 * @param  string $attribute condition column name
417
+	 * @return void
418
+	 */
419
+	public function update($value, array $data, $attribute = 'id')
420
+	{
421
+		if ($attribute == 'id') {
422
+			$model = $this->model->lockForUpdate()->find($value);
423
+			$model ? $model->update($data) : 0;
424
+		} else {
425
+			call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model) use ($data) {
426
+				$model->update($data);
427
+			});
428
+		}
429
+	}
430
+
431
+	/**
432
+	 * Delete record from the storage based on the given
433
+	 * condition.
434
+	 *
435
+	 * @param  var $value condition value
436
+	 * @param  string $attribute condition column name
437
+	 * @return void
438
+	 */
439
+	public function delete($value, $attribute = 'id')
440
+	{
441
+		if ($attribute == 'id') {
442
+			\DB::transaction(function () use ($value, $attribute, &$result) {
443
+				$model = $this->model->lockForUpdate()->find($value);
444
+				if (! $model) {
445
+					\ErrorHandler::notFound(class_basename($this->model).' with id : '.$value);
446
+				}
447 447
                 
448
-                $model->delete();
449
-            });
450
-        } else {
451
-            \DB::transaction(function () use ($value, $attribute, &$result) {
452
-                call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model) {
453
-                    $model->delete();
454
-                });
455
-            });
456
-        }
457
-    }
448
+				$model->delete();
449
+			});
450
+		} else {
451
+			\DB::transaction(function () use ($value, $attribute, &$result) {
452
+				call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model) {
453
+					$model->delete();
454
+				});
455
+			});
456
+		}
457
+	}
458 458
     
459
-    /**
460
-     * Fetch records from the storage based on the given
461
-     * id.
462
-     *
463
-     * @param  integer $id
464
-     * @param  string[]   $relations
465
-     * @param  array   $columns
466
-     * @return object
467
-     */
468
-    public function find($id, $relations = [], $columns = ['*'])
469
-    {
470
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->find($id, $columns);
471
-    }
459
+	/**
460
+	 * Fetch records from the storage based on the given
461
+	 * id.
462
+	 *
463
+	 * @param  integer $id
464
+	 * @param  string[]   $relations
465
+	 * @param  array   $columns
466
+	 * @return object
467
+	 */
468
+	public function find($id, $relations = [], $columns = ['*'])
469
+	{
470
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->find($id, $columns);
471
+	}
472 472
     
473
-    /**
474
-     * Fetch records from the storage based on the given
475
-     * condition.
476
-     *
477
-     * @param  array   $conditions array of conditions
478
-     * @param  array   $relations
479
-     * @param  string  $sortBy
480
-     * @param  boolean $desc
481
-     * @param  array   $columns
482
-     * @return collection
483
-     */
484
-    public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
485
-    {
486
-        $conditions = $this->constructConditions($conditions, $this->model);
487
-        $sort       = $desc ? 'desc' : 'asc';
488
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
489
-    }
490
-
491
-    /**
492
-     * Fetch the first record from the storage based on the given
493
-     * condition.
494
-     *
495
-     * @param  array   $conditions array of conditions
496
-     * @param  array   $relations
497
-     * @param  array   $columns
498
-     * @return object
499
-     */
500
-    public function first($conditions, $relations = [], $columns = ['*'])
501
-    {
502
-        $conditions = $this->constructConditions($conditions, $this->model);
503
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
504
-    }
505
-
506
-    /**
507
-     * Return the deleted models in pages based on the given conditions.
508
-     *
509
-     * @param  array   $conditions array of conditions
510
-     * @param  integer $perPage
511
-     * @param  string  $sortBy
512
-     * @param  boolean $desc
513
-     * @param  array   $columns
514
-     * @return collection
515
-     */
516
-    public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = ['*'])
517
-    {
518
-        unset($conditions['page']);
519
-        $conditions = $this->constructConditions($conditions, $this->model);
520
-        $sort       = $desc ? 'desc' : 'asc';
521
-        $model      = $this->model->onlyTrashed();
522
-
523
-        if (count($conditions['conditionValues'])) {
524
-            $model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
525
-        }
526
-
527
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
528
-    }
529
-
530
-    /**
531
-     * Restore the deleted model.
532
-     *
533
-     * @param  integer $id
534
-     * @return void
535
-     */
536
-    public function restore($id)
537
-    {
538
-        $model = $this->model->onlyTrashed()->find($id);
539
-
540
-        if (! $model) {
541
-            \ErrorHandler::notFound(class_basename($this->model).' with id : '.$id);
542
-        }
543
-
544
-        $model->restore();
545
-    }
546
-
547
-    /**
548
-     * Build the conditions recursively for the retrieving methods.
549
-     * @param  array $conditions
550
-     * @return array
551
-     */
552
-    protected function constructConditions($conditions, $model)
553
-    {
554
-        $conditionString = '';
555
-        $conditionValues = [];
556
-        foreach ($conditions as $key => $value) {
557
-            if (Str::contains($key, '->')) {
558
-                $key = $this->wrapJsonSelector($key);
559
-            }
560
-
561
-            if ($key == 'and') {
562
-                $conditions       = $this->constructConditions($value, $model);
563
-                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
564
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
565
-            } elseif ($key == 'or') {
566
-                $conditions       = $this->constructConditions($value, $model);
567
-                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
568
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
569
-            } else {
570
-                if (is_array($value)) {
571
-                    $operator = $value['op'];
572
-                    if (strtolower($operator) == 'between') {
573
-                        $value1 = $value['val1'];
574
-                        $value2 = $value['val2'];
575
-                    } else {
576
-                        $value = Arr::get($value, 'val', '');
577
-                    }
578
-                } else {
579
-                    $operator = '=';
580
-                }
473
+	/**
474
+	 * Fetch records from the storage based on the given
475
+	 * condition.
476
+	 *
477
+	 * @param  array   $conditions array of conditions
478
+	 * @param  array   $relations
479
+	 * @param  string  $sortBy
480
+	 * @param  boolean $desc
481
+	 * @param  array   $columns
482
+	 * @return collection
483
+	 */
484
+	public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
485
+	{
486
+		$conditions = $this->constructConditions($conditions, $this->model);
487
+		$sort       = $desc ? 'desc' : 'asc';
488
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
489
+	}
490
+
491
+	/**
492
+	 * Fetch the first record from the storage based on the given
493
+	 * condition.
494
+	 *
495
+	 * @param  array   $conditions array of conditions
496
+	 * @param  array   $relations
497
+	 * @param  array   $columns
498
+	 * @return object
499
+	 */
500
+	public function first($conditions, $relations = [], $columns = ['*'])
501
+	{
502
+		$conditions = $this->constructConditions($conditions, $this->model);
503
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
504
+	}
505
+
506
+	/**
507
+	 * Return the deleted models in pages based on the given conditions.
508
+	 *
509
+	 * @param  array   $conditions array of conditions
510
+	 * @param  integer $perPage
511
+	 * @param  string  $sortBy
512
+	 * @param  boolean $desc
513
+	 * @param  array   $columns
514
+	 * @return collection
515
+	 */
516
+	public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = ['*'])
517
+	{
518
+		unset($conditions['page']);
519
+		$conditions = $this->constructConditions($conditions, $this->model);
520
+		$sort       = $desc ? 'desc' : 'asc';
521
+		$model      = $this->model->onlyTrashed();
522
+
523
+		if (count($conditions['conditionValues'])) {
524
+			$model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
525
+		}
526
+
527
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
528
+	}
529
+
530
+	/**
531
+	 * Restore the deleted model.
532
+	 *
533
+	 * @param  integer $id
534
+	 * @return void
535
+	 */
536
+	public function restore($id)
537
+	{
538
+		$model = $this->model->onlyTrashed()->find($id);
539
+
540
+		if (! $model) {
541
+			\ErrorHandler::notFound(class_basename($this->model).' with id : '.$id);
542
+		}
543
+
544
+		$model->restore();
545
+	}
546
+
547
+	/**
548
+	 * Build the conditions recursively for the retrieving methods.
549
+	 * @param  array $conditions
550
+	 * @return array
551
+	 */
552
+	protected function constructConditions($conditions, $model)
553
+	{
554
+		$conditionString = '';
555
+		$conditionValues = [];
556
+		foreach ($conditions as $key => $value) {
557
+			if (Str::contains($key, '->')) {
558
+				$key = $this->wrapJsonSelector($key);
559
+			}
560
+
561
+			if ($key == 'and') {
562
+				$conditions       = $this->constructConditions($value, $model);
563
+				$conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
564
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
565
+			} elseif ($key == 'or') {
566
+				$conditions       = $this->constructConditions($value, $model);
567
+				$conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
568
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
569
+			} else {
570
+				if (is_array($value)) {
571
+					$operator = $value['op'];
572
+					if (strtolower($operator) == 'between') {
573
+						$value1 = $value['val1'];
574
+						$value2 = $value['val2'];
575
+					} else {
576
+						$value = Arr::get($value, 'val', '');
577
+					}
578
+				} else {
579
+					$operator = '=';
580
+				}
581 581
                 
582
-                if (strtolower($operator) == 'between') {
583
-                    $conditionString  .= $key.' >= ? and ';
584
-                    $conditionValues[] = $value1;
585
-
586
-                    $conditionString  .= $key.' <= ? {op} ';
587
-                    $conditionValues[] = $value2;
588
-                } elseif (strtolower($operator) == 'in') {
589
-                    $conditionValues  = array_merge($conditionValues, $value);
590
-                    $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
591
-                    $conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
592
-                } elseif (strtolower($operator) == 'null') {
593
-                    $conditionString .= $key.' is null {op} ';
594
-                } elseif (strtolower($operator) == 'not null') {
595
-                    $conditionString .= $key.' is not null {op} ';
596
-                } elseif (strtolower($operator) == 'has') {
597
-                    $sql              = $model->withTrashed()->has($key)->toSql();
598
-                    $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
599
-                    $conditionString .= rtrim(substr($sql, strpos($sql, 'exists')), ')').' and '.$conditions['conditionString'].') {op} ';
600
-                    $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
601
-                } else {
602
-                    $conditionString  .= $key.' '.$operator.' ? {op} ';
603
-                    $conditionValues[] = $value;
604
-                }
605
-            }
606
-        }
607
-        $conditionString = '('.rtrim($conditionString, '{op} ').')';
608
-        return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
609
-    }
610
-
611
-    /**
612
-     * Wrap the given JSON selector.
613
-     *
614
-     * @param  string  $value
615
-     * @return string
616
-     */
617
-    protected function wrapJsonSelector($value)
618
-    {
619
-        $removeLast = strpos($value, ')');
620
-        $value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
621
-        $path       = explode('->', $value);
622
-        $field      = array_shift($path);
623
-        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
624
-            return '"'.$part.'"';
625
-        })->implode('.'));
582
+				if (strtolower($operator) == 'between') {
583
+					$conditionString  .= $key.' >= ? and ';
584
+					$conditionValues[] = $value1;
585
+
586
+					$conditionString  .= $key.' <= ? {op} ';
587
+					$conditionValues[] = $value2;
588
+				} elseif (strtolower($operator) == 'in') {
589
+					$conditionValues  = array_merge($conditionValues, $value);
590
+					$inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
591
+					$conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
592
+				} elseif (strtolower($operator) == 'null') {
593
+					$conditionString .= $key.' is null {op} ';
594
+				} elseif (strtolower($operator) == 'not null') {
595
+					$conditionString .= $key.' is not null {op} ';
596
+				} elseif (strtolower($operator) == 'has') {
597
+					$sql              = $model->withTrashed()->has($key)->toSql();
598
+					$conditions       = $this->constructConditions($value, $model->$key()->getRelated());
599
+					$conditionString .= rtrim(substr($sql, strpos($sql, 'exists')), ')').' and '.$conditions['conditionString'].') {op} ';
600
+					$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
601
+				} else {
602
+					$conditionString  .= $key.' '.$operator.' ? {op} ';
603
+					$conditionValues[] = $value;
604
+				}
605
+			}
606
+		}
607
+		$conditionString = '('.rtrim($conditionString, '{op} ').')';
608
+		return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
609
+	}
610
+
611
+	/**
612
+	 * Wrap the given JSON selector.
613
+	 *
614
+	 * @param  string  $value
615
+	 * @return string
616
+	 */
617
+	protected function wrapJsonSelector($value)
618
+	{
619
+		$removeLast = strpos($value, ')');
620
+		$value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
621
+		$path       = explode('->', $value);
622
+		$field      = array_shift($path);
623
+		$result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
624
+			return '"'.$part.'"';
625
+		})->implode('.'));
626 626
         
627
-        return $removeLast === false ? $result : $result.')';
628
-    }
629
-
630
-    /**
631
-     * Abstract method that return the necessary
632
-     * information (full model namespace)
633
-     * needed to preform the previous actions.
634
-     *
635
-     * @return string
636
-     */
637
-    abstract protected function getModel();
627
+		return $removeLast === false ? $result : $result.')';
628
+	}
629
+
630
+	/**
631
+	 * Abstract method that return the necessary
632
+	 * information (full model namespace)
633
+	 * needed to preform the previous actions.
634
+	 *
635
+	 * @return string
636
+	 */
637
+	abstract protected function getModel();
638 638
 }
Please login to merge, or discard this patch.
src/Modules/Acl/OauthClient.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -6,28 +6,28 @@
 block discarded – undo
6 6
 
7 7
 class OauthClient extends Client
8 8
 {
9
-    protected $dates    = ['created_at', 'updated_at'];
10
-    protected $fillable = ['name', 'redirect', 'user_id', 'personal_access_client', 'password_client', 'revoked'];
11
-    public $searchable  = ['name'];
9
+	protected $dates    = ['created_at', 'updated_at'];
10
+	protected $fillable = ['name', 'redirect', 'user_id', 'personal_access_client', 'password_client', 'revoked'];
11
+	public $searchable  = ['name'];
12 12
     
13
-    public function getCreatedAtAttribute($value)
14
-    {
15
-        return \Carbon\Carbon::parse($value)->tz(\Session::get('time-zone'))->toDateTimeString();
16
-    }
13
+	public function getCreatedAtAttribute($value)
14
+	{
15
+		return \Carbon\Carbon::parse($value)->tz(\Session::get('time-zone'))->toDateTimeString();
16
+	}
17 17
 
18
-    public function getUpdatedAtAttribute($value)
19
-    {
20
-        return \Carbon\Carbon::parse($value)->tz(\Session::get('time-zone'))->toDateTimeString();
21
-    }
18
+	public function getUpdatedAtAttribute($value)
19
+	{
20
+		return \Carbon\Carbon::parse($value)->tz(\Session::get('time-zone'))->toDateTimeString();
21
+	}
22 22
     
23
-    public function user()
24
-    {
25
-        return $this->belongsTo('App\Modules\Acl\AclUser');
26
-    }
23
+	public function user()
24
+	{
25
+		return $this->belongsTo('App\Modules\Acl\AclUser');
26
+	}
27 27
     
28
-    public static function boot()
29
-    {
30
-        parent::boot();
31
-        OauthClient::observe(\App::make('App\Modules\Acl\ModelObservers\OauthClientObserver'));
32
-    }
28
+	public static function boot()
29
+	{
30
+		parent::boot();
31
+		OauthClient::observe(\App::make('App\Modules\Acl\ModelObservers\OauthClientObserver'));
32
+	}
33 33
 }
Please login to merge, or discard this patch.
src/Modules/Acl/Repositories/UserRepository.php 1 patch
Indentation   +379 added lines, -379 removed lines patch added patch discarded remove patch
@@ -6,391 +6,391 @@
 block discarded – undo
6 6
 
7 7
 class UserRepository extends AbstractRepository
8 8
 {
9
-    /**
10
-     * Return the model full namespace.
11
-     *
12
-     * @return string
13
-     */
14
-    protected function getModel()
15
-    {
16
-        return 'App\Modules\Acl\AclUser';
17
-    }
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        = \Core::users()->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
-        });
9
+	/**
10
+	 * Return the model full namespace.
11
+	 *
12
+	 * @return string
13
+	 */
14
+	protected function getModel()
15
+	{
16
+		return 'App\Modules\Acl\AclUser';
17
+	}
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        = \Core::users()->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 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\Acl\Proxy\LoginProxy');
139
-        return $loginProxy->login(['email' => $user->email, 'password' => config('skeleton.social_pass')], 0);
140
-    }
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\Acl\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 array
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 array
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      = call_user_func_array("{$this->getModel()}::with", array($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      = call_user_func_array("{$this->getModel()}::with", array($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 void
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 void
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.
src/Modules/Acl/Http/Resources/AclPermission.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -7,20 +7,20 @@
 block discarded – undo
7 7
 
8 8
 class AclPermission extends JsonResource
9 9
 {
10
-    /**
11
-     * Transform the resource into an array.
12
-     *
13
-     * @param  \Illuminate\Http\Request  $request
14
-     * @return array
15
-     */
16
-    public function toArray($request)
17
-    {
18
-        return [
19
-            'id' => $this->id,
20
-            'name' => $this->name,
21
-            'groups' => GroupResource::collection($this->whenLoaded('groups')),
22
-            'createdAt' => $this->created_at,
23
-            'updatedAt' => $this->updated_at,
24
-        ];
25
-    }
10
+	/**
11
+	 * Transform the resource into an array.
12
+	 *
13
+	 * @param  \Illuminate\Http\Request  $request
14
+	 * @return array
15
+	 */
16
+	public function toArray($request)
17
+	{
18
+		return [
19
+			'id' => $this->id,
20
+			'name' => $this->name,
21
+			'groups' => GroupResource::collection($this->whenLoaded('groups')),
22
+			'createdAt' => $this->created_at,
23
+			'updatedAt' => $this->updated_at,
24
+		];
25
+	}
26 26
 }
Please login to merge, or discard this patch.
src/Modules/Acl/Http/Resources/OauthClient.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -7,24 +7,24 @@
 block discarded – undo
7 7
 
8 8
 class OauthClient extends JsonResource
9 9
 {
10
-    /**
11
-     * Transform the resource into an array.
12
-     *
13
-     * @param  \Illuminate\Http\Request  $request
14
-     * @return array
15
-     */
16
-    public function toArray($request)
17
-    {
18
-        return [
19
-            'id' => $this->id,
20
-            'name' => $this->name,
21
-            'redirect' => $this->redirect,
22
-            'user' => new UserResource($this->whenLoaded('user')),
23
-            'personalAccessClient' => $this->personal_access_client,
24
-            'passwordClient' => $this->password_client,
25
-            'revoked' => $this->revoked,
26
-            'createdAt' => $this->created_at,
27
-            'updatedAt' => $this->updated_at,
28
-        ];
29
-    }
10
+	/**
11
+	 * Transform the resource into an array.
12
+	 *
13
+	 * @param  \Illuminate\Http\Request  $request
14
+	 * @return array
15
+	 */
16
+	public function toArray($request)
17
+	{
18
+		return [
19
+			'id' => $this->id,
20
+			'name' => $this->name,
21
+			'redirect' => $this->redirect,
22
+			'user' => new UserResource($this->whenLoaded('user')),
23
+			'personalAccessClient' => $this->personal_access_client,
24
+			'passwordClient' => $this->password_client,
25
+			'revoked' => $this->revoked,
26
+			'createdAt' => $this->created_at,
27
+			'updatedAt' => $this->updated_at,
28
+		];
29
+	}
30 30
 }
Please login to merge, or discard this patch.
src/Modules/Acl/Http/Resources/AclUser.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -9,28 +9,28 @@
 block discarded – undo
9 9
 
10 10
 class AclUser extends JsonResource
11 11
 {
12
-    /**
13
-     * Transform the resource into an array.
14
-     *
15
-     * @param  \Illuminate\Http\Request  $request
16
-     * @return array
17
-     */
18
-    public function toArray($request)
19
-    {
20
-        return [
21
-            'id' => $this->id,
22
-            'name' => $this->name,
23
-            'email' => $this->email,
24
-            'profilePicture' => $this->profile_picture,
25
-            'notifications' => NotificationResource::collection($this->whenLoaded('notifications')),
26
-            'readNotifications' => NotificationResource::collection($this->whenLoaded('readNotifications')),
27
-            'unreadNotifications' => NotificationResource::collection($this->whenLoaded('unreadNotifications')),
28
-            'groups' => AclGroupResource::collection($this->whenLoaded('groups')),
29
-            'oauthClients' => OauthClientResource::collection($this->whenLoaded('oauthClients')),
30
-            'locale' => $this->locale,
31
-            'timeZone' => $this->time_zone,
32
-            'createdAt' => $this->created_at,
33
-            'updatedAt' => $this->updated_at,
34
-        ];
35
-    }
12
+	/**
13
+	 * Transform the resource into an array.
14
+	 *
15
+	 * @param  \Illuminate\Http\Request  $request
16
+	 * @return array
17
+	 */
18
+	public function toArray($request)
19
+	{
20
+		return [
21
+			'id' => $this->id,
22
+			'name' => $this->name,
23
+			'email' => $this->email,
24
+			'profilePicture' => $this->profile_picture,
25
+			'notifications' => NotificationResource::collection($this->whenLoaded('notifications')),
26
+			'readNotifications' => NotificationResource::collection($this->whenLoaded('readNotifications')),
27
+			'unreadNotifications' => NotificationResource::collection($this->whenLoaded('unreadNotifications')),
28
+			'groups' => AclGroupResource::collection($this->whenLoaded('groups')),
29
+			'oauthClients' => OauthClientResource::collection($this->whenLoaded('oauthClients')),
30
+			'locale' => $this->locale,
31
+			'timeZone' => $this->time_zone,
32
+			'createdAt' => $this->created_at,
33
+			'updatedAt' => $this->updated_at,
34
+		];
35
+	}
36 36
 }
Please login to merge, or discard this patch.