Completed
Push — master ( 84dfb3...7a7a2b )
by Sherif
27s
created
src/Modules/Core/BaseClasses/Contracts/BaseServiceInterface.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
    * @param   bool   $trashed
20 20
    * @return LengthAwarePaginator
21 21
    */
22
-    public function list(array $relations = [], array $conditions = [], int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, bool $trashed = false): LengthAwarePaginator;
22
+	public function list(array $relations = [], array $conditions = [], int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, bool $trashed = false): LengthAwarePaginator;
23 23
 
24 24
   /**
25 25
    * Fetch all records with relations from the storage.
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
    * @param  array   $columns
31 31
    * @return collection
32 32
    */
33
-    public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
33
+	public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
34 34
 
35 35
   /**
36 36
    * Fetch all records with relations from storage in pages.
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
    * @param  array   $columns
43 43
    * @return LengthAwarePaginator
44 44
    */
45
-    public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
45
+	public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
46 46
 
47 47
   /**
48 48
    * Fetch all records with relations based on
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
    * @param  array   $columns
57 57
    * @return collection
58 58
    */
59
-    public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
59
+	public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
60 60
 
61 61
   /**
62 62
    * Save the given model/models to the storage.
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
    * @param  array   $data
65 65
    * @return Model
66 66
    */
67
-    public function save(array $data): Model;
67
+	public function save(array $data): Model;
68 68
 
69 69
   /**
70 70
    * Delete record from the storage based on the given
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
    * @param  string $attribute condition column name
75 75
    * @return bool
76 76
    */
77
-    public function delete(string $value, string $attribute = 'id'): bool;
77
+	public function delete(string $value, string $attribute = 'id'): bool;
78 78
 
79 79
   /**
80 80
    * Fetch records from the storage based on the given
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
    * @param  array $columns
86 86
    * @return object
87 87
    */
88
-    public function find(int $id, array $relations = [], array $columns = ['*']): Model;
88
+	public function find(int $id, array $relations = [], array $columns = ['*']): Model;
89 89
 
90 90
   /**
91 91
    * Fetch records from the storage based on the given
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
    * @param  array   $columns
99 99
    * @return collection
100 100
    */
101
-    public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
101
+	public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
102 102
 
103 103
   /**
104 104
    * Fetch the first record fro the storage based on the given
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
    * @param  array $columns
110 110
    * @return Model
111 111
    */
112
-    public function first(array $conditions, array $relations = [], array $columns = ['*']): Model;
112
+	public function first(array $conditions, array $relations = [], array $columns = ['*']): Model;
113 113
 
114 114
   /**
115 115
    * Return the deleted models in pages based on the given conditions.
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
    * @param  array  $columns
122 122
    * @return LengthAwarePaginator
123 123
    */
124
-    public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
124
+	public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
125 125
 
126 126
   /**
127 127
    * Restore the deleted model.
@@ -129,5 +129,5 @@  discard block
 block discarded – undo
129 129
    * @param  int $id
130 130
    * @return bool
131 131
    */
132
-    public function restore(int $id): bool;
132
+	public function restore(int $id): bool;
133 133
 }
Please login to merge, or discard this patch.
src/Modules/Core/BaseClasses/Contracts/BaseRepositoryInterface.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
    * @param  array  $columns
18 18
    * @return collection
19 19
    */
20
-    public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
20
+	public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
21 21
 
22 22
   /**
23 23
    * Fetch all records with relations from storage in pages.
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
    * @param  array  $columns
30 30
    * @return LengthAwarePaginator
31 31
    */
32
-    public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
32
+	public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
33 33
 
34 34
   /**
35 35
    * Fetch all records with relations based on
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
    * @param  array   $columns
44 44
    * @return collection
45 45
    */
46
-    public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
46
+	public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
47 47
 
48 48
   /**
49 49
    * Count all records based on the given condition from storage.
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
    * @param  array $conditions array of conditions
52 52
    * @return int
53 53
    */
54
-    public function count(array $conditions = []): int;
54
+	public function count(array $conditions = []): int;
55 55
 
56 56
   /**
57 57
    * Pluck column based on the given condition from storage.
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
    * @param  string $column
61 61
    * @return collection
62 62
    */
63
-    public function pluck(array $conditions, string $column): Collection;
63
+	public function pluck(array $conditions, string $column): Collection;
64 64
 
65 65
   /**
66 66
    * Save the given model to the storage.
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
    * @param  array $data
69 69
    * @return Model
70 70
    */
71
-    public function save(array $data): Model;
71
+	public function save(array $data): Model;
72 72
 
73 73
   /**
74 74
    * Insert the given model/models to the storage.
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
    * @param  array $data
77 77
    * @return bool
78 78
    */
79
-    public function insert(array $data): bool;
79
+	public function insert(array $data): bool;
80 80
 
81 81
   /**
82 82
    * Delete record from the storage based on the given
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
    * @param  string $attribute condition column name
87 87
    * @return bool
88 88
    */
89
-    public function delete(string $value, string $attribute = 'id'): bool;
89
+	public function delete(string $value, string $attribute = 'id'): bool;
90 90
 
91 91
   /**
92 92
    * Fetch records from the storage based on the given
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
    * @param  array $columns
98 98
    * @return Model
99 99
    */
100
-    public function find(int $id, array $relations = [], array $columns = ['*']): Model;
100
+	public function find(int $id, array $relations = [], array $columns = ['*']): Model;
101 101
 
102 102
   /**
103 103
    * Fetch records from the storage based on the given
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
    * @param  array   $columns
111 111
    * @return collection
112 112
    */
113
-    public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
113
+	public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection;
114 114
 
115 115
   /**
116 116
    * Fetch the first record fro the storage based on the given
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
    * @param  array $columns
122 122
    * @return Model
123 123
    */
124
-    public function first(array $conditions, array $relations = [], array $columns = ['*']): Model;
124
+	public function first(array $conditions, array $relations = [], array $columns = ['*']): Model;
125 125
 
126 126
   /**
127 127
    * Return the deleted models in pages based on the given conditions.
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
    * @param  array  $columns
134 134
    * @return LengthAwarePaginator
135 135
    */
136
-    public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
136
+	public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator;
137 137
 
138 138
   /**
139 139
    * Restore the deleted model.
@@ -141,5 +141,5 @@  discard block
 block discarded – undo
141 141
    * @param  int $id
142 142
    * @return bool
143 143
    */
144
-    public function restore(int $id): bool;
144
+	public function restore(int $id): bool;
145 145
 }
Please login to merge, or discard this patch.
src/Modules/Core/BaseClasses/BaseRepository.php 2 patches
Indentation   +628 added lines, -628 removed lines patch added patch discarded remove patch
@@ -14,632 +14,632 @@
 block discarded – undo
14 14
 
15 15
 abstract class BaseRepository implements BaseRepositoryInterface
16 16
 {
17
-    /**
18
-     * @var Model
19
-     */
20
-    public $model;
21
-
22
-    /**
23
-     * Init new object.
24
-     *
25
-     * @param   Model$model
26
-     * @return  void
27
-     */
28
-    public function __construct(Model $model)
29
-    {
30
-        $this->model = $model;
31
-    }
32
-
33
-    /**
34
-     * Fetch all records with relations from the storage.
35
-     *
36
-     * @param  array  $relations
37
-     * @param  string $sortBy
38
-     * @param  bool   $desc
39
-     * @param  array  $columns
40
-     * @return collection
41
-     */
42
-    public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
43
-    {
44
-        $sort = $desc ? 'desc' : 'asc';
45
-        return $this->model->with($relations)->orderBy($sortBy, $sort)->get($columns);
46
-    }
47
-
48
-    /**
49
-     * Fetch all records with relations from storage in pages.
50
-     *
51
-     * @param  int    $perPage
52
-     * @param  array  $relations
53
-     * @param  string $sortBy
54
-     * @param  bool   $desc
55
-     * @param  array  $columns
56
-     * @return LengthAwarePaginator
57
-     */
58
-    public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
59
-    {
60
-        $sort = $desc ? 'desc' : 'asc';
61
-        return $this->model->with($relations)->orderBy($sortBy, $sort)->paginate($perPage, $columns);
62
-    }
63
-
64
-    /**
65
-     * Fetch all records with relations based on
66
-     * the given condition from storage in pages.
67
-     *
68
-     * @param  array  $conditions array of conditions
69
-     * @param  int    $perPage
70
-     * @param  array  $relations
71
-     * @param  string $sortBy
72
-     * @param  bool   $desc
73
-     * @param  array  $columns
74
-     * @return LengthAwarePaginator
75
-     */
76
-    public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
77
-    {
78
-        $conditions = $this->constructConditions($conditions, $this->model);
79
-        $sort       = $desc ? 'desc' : 'asc';
80
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
81
-    }
82
-
83
-    /**
84
-     * Count all records based on the given condition from storage.
85
-     *
86
-     * @param  array $conditions array of conditions
87
-     * @return int
88
-     */
89
-    public function count(array $conditions = []): int
90
-    {
91
-        if ($conditions) {
92
-            $conditions = $this->constructConditions($conditions, $this->model);
93
-            return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->count();
94
-        }
95
-
96
-        return $this->model->count();
97
-    }
98
-
99
-    /**
100
-     * Pluck column based on the given condition from storage.
101
-     *
102
-     * @param  array  $conditions array of conditions
103
-     * @param  string $column
104
-     * @return collection
105
-     */
106
-    public function pluck(array $conditions, string $column): Collection
107
-    {
108
-        $conditions = $this->constructConditions($conditions, $this->model);
109
-        return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->pluck($column);
110
-    }
111
-
112
-    /**
113
-     * Save the given model to the storage.
114
-     *
115
-     * @param  array $data
116
-     * @return Model
117
-     */
118
-    public function save(array $data): Model
119
-    {
120
-        $model      = new Model();
121
-        $relations  = [];
122
-
123
-        DB::transaction(function () use (&$model, &$relations, $data) {
124
-
125
-            $model     = $this->prepareModel($data);
126
-            $relations = $this->prepareRelations($data, $model);
127
-            $model     = $this->saveModel($model, $relations);
128
-        });
129
-
130
-        if (count($relations)) {
131
-            $model->load(...array_keys($relations));
132
-        }
133
-
134
-        return $model;
135
-    }
136
-
137
-    /**
138
-     * Insert the given model/models to the storage.
139
-     *
140
-     * @param  array $data
141
-     * @return bool
142
-     */
143
-    public function insert(array $data): bool
144
-    {
145
-        return $this->model->insert($data);
146
-    }
147
-
148
-    /**
149
-     * Delete record from the storage based on the given
150
-     * condition.
151
-     *
152
-     * @param  string $value condition value
153
-     * @param  string $attribute condition column name
154
-     * @return bool
155
-     */
156
-    public function delete(string $value, string $attribute = 'id'): bool
157
-    {
158
-        DB::transaction(function () use ($value, $attribute) {
159
-            $this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
160
-                $model->delete();
161
-            });
162
-        });
163
-
164
-        return true;
165
-    }
166
-
167
-    /**
168
-     * Fetch records from the storage based on the given
169
-     * id.
170
-     *
171
-     * @param  int   $id
172
-     * @param  array $relations
173
-     * @param  array $columns
174
-     * @return Model
175
-     */
176
-    public function find(int $id, array $relations = [], array $columns = ['*']): Model
177
-    {
178
-        return $this->model->with($relations)->find($id, $columns);
179
-    }
180
-
181
-    /**
182
-     * Fetch records from the storage based on the given
183
-     * condition.
184
-     *
185
-     * @param  array   $conditions array of conditions
186
-     * @param  array   $relations
187
-     * @param  string  $sortBy
188
-     * @param  bool    $desc
189
-     * @param  array   $columns
190
-     * @return collection
191
-     */
192
-    public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
193
-    {
194
-        $conditions = $this->constructConditions($conditions, $this->model);
195
-        $sort       = $desc ? 'desc' : 'asc';
196
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
197
-    }
198
-
199
-    /**
200
-     * Fetch the first record from the storage based on the given
201
-     * condition.
202
-     *
203
-     * @param  array $conditions array of conditions
204
-     * @param  array $relations
205
-     * @param  array $columns
206
-     * @return Model
207
-     */
208
-    public function first(array $conditions, array $relations = [], array $columns = ['*']): Model
209
-    {
210
-        $conditions = $this->constructConditions($conditions, $this->model);
211
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
212
-    }
213
-
214
-    /**
215
-     * Return the deleted models in pages based on the given conditions.
216
-     *
217
-     * @param  array  $conditions array of conditions
218
-     * @param  int    $perPage
219
-     * @param  string $sortBy
220
-     * @param  bool   $desc
221
-     * @param  array  $columns
222
-     * @return LengthAwarePaginator
223
-     */
224
-    public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
225
-    {
226
-        unset($conditions['page']);
227
-        unset($conditions['perPage']);
228
-        unset($conditions['sortBy']);
229
-        unset($conditions['sort']);
230
-        $conditions = $this->constructConditions($conditions, $this->model);
231
-        $sort       = $desc ? 'desc' : 'asc';
232
-        $model      = $this->model->onlyTrashed();
233
-
234
-        if (count($conditions['conditionValues'])) {
235
-            $model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
236
-        }
237
-
238
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
239
-    }
240
-
241
-    /**
242
-     * Restore the deleted model.
243
-     *
244
-     * @param  int $id
245
-     * @return bool
246
-     */
247
-    public function restore(int $id): bool
248
-    {
249
-        $model = $this->model->onlyTrashed()->find($id);
250
-
251
-        if (!$model) {
252
-            Errors::notFound(class_basename($this->model) . ' with id : ' . $id);
253
-        }
254
-
255
-        $model->restore();
256
-
257
-        return true;
258
-    }
259
-
260
-    /**
261
-     * Fill the model with the given data.
262
-     *
263
-     * @param   array  $data
264
-     * @return  Model
265
-     */
266
-    protected function prepareModel(array $data): Model
267
-    {
268
-        $modelClass = $this->model;
269
-
270
-        /**
271
-         * If the id is present in the data then select the model for updating,
272
-         * else create new model.
273
-         *
274
-         * @var object
275
-         */
276
-        $model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
277
-        if (!$model) {
278
-            Errors::notFound(class_basename($modelClass) . ' with id : ' . $data['id']);
279
-        }
280
-
281
-        /**
282
-         * Construct the model object with the given data,
283
-         * and if there is a relation add it to relations array,
284
-         * then save the model.
285
-         */
286
-        foreach ($data as $key => $value) {
287
-            if (array_search($key, $model->getFillable(), true) !== false) {
288
-                /**
289
-                 * If the attribute isn't a relation and prevent attributes not in the fillable.
290
-                 */
291
-                $model->$key = $value;
292
-            }
293
-        }
294
-
295
-        return $model;
296
-    }
297
-
298
-    /**
299
-     * Prepare related models based on the given data for the given model.
300
-     *
301
-     * @param   array $data
302
-     * @param   Model $model
303
-     *
304
-     * @return  array
305
-     */
306
-    protected function prepareRelations(array $data, Model $model): array
307
-    {
308
-        /**
309
-         * Init the relation array
310
-         *
311
-         * @var array
312
-         */
313
-        $relations = [];
314
-
315
-        /**
316
-         * Construct the model object with the given data,
317
-         * and if there is a relation add it to relations array,
318
-         * then save the model.
319
-         */
320
-        foreach ($data as $key => $value) {
321
-            /**
322
-             * If the attribute is a relation.
323
-             */
324
-            $relation = Str::camel($key);
325
-            if (method_exists($model, $relation) && Core::$relation()) {
326
-                /**
327
-                 * Check if the relation is a collection.
328
-                 */
329
-                if (class_basename($model->$relation) == 'Collection') {
330
-                    /**
331
-                     * If the relation has no value then marke the relation data
332
-                     * related to the model to be deleted.
333
-                     */
334
-                    if (!$value || !count($value)) {
335
-                        $relations[$relation] = 'delete';
336
-                    }
337
-                }
338
-                if (is_array($value)) {
339
-                    /**
340
-                     * Loop through the relation data.
341
-                     */
342
-                    foreach ($value as $attr => $val) {
343
-                        /**
344
-                         * Get the relation model.
345
-                         */
346
-                        $relationBaseModel = Core::$relation()->model;
347
-
348
-                        /**
349
-                         * Check if the relation is a collection.
350
-                         */
351
-                        if (class_basename($model->$relation) == 'Collection') {
352
-                            if (!is_array($val)) {
353
-                                $relationModel = $relationBaseModel->lockForUpdate()->find($val);
354
-                            } else {
355
-                                /**
356
-                                 * If the id is present in the data then select the relation model for updating,
357
-                                 * else create new model.
358
-                                 */
359
-                                $relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
360
-                            }
361
-
362
-                            /**
363
-                             * If model doesn't exists.
364
-                             */
365
-                            if (!$relationModel) {
366
-                                Errors::notFound(class_basename($relationBaseModel) . ' with id : ' . $val['id']);
367
-                            }
368
-
369
-                            if (is_array($val)) {
370
-                                /**
371
-                                 * Loop through the relation attributes.
372
-                                 */
373
-                                foreach ($val as $attr => $val) {
374
-                                    /**
375
-                                     * Prevent the sub relations or attributes not in the fillable.
376
-                                     */
377
-                                    if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false && class_basename($model->$key()) !== 'BelongsToMany') {
378
-                                        $relationModel->$attr = $val;
379
-                                    } elseif (gettype($val) !== 'object' && gettype($val) !== 'array' && $attr !== 'id') {
380
-                                        $extra[$attr] = $val;
381
-                                    }
382
-                                }
383
-                            }
384
-
385
-                            if (isset($extra)) {
386
-                                $relationModel->extra = $extra;
387
-                            }
388
-                            $relations[$relation][] = $relationModel;
389
-                        } else {
390
-                            /**
391
-                             * Prevent the sub relations.
392
-                             */
393
-                            if (gettype($val) !== 'object' && gettype($val) !== 'array') {
394
-                                /**
395
-                                 * If the id is present in the data then select the relation model for updating,
396
-                                 * else create new model.
397
-                                 */
398
-                                $relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
399
-
400
-                                /**
401
-                                 * If model doesn't exists.
402
-                                 */
403
-                                if (!$relationModel) {
404
-                                    Errors::notFound(class_basename($relationBaseModel) . ' with id : ' . $value['id']);
405
-                                }
406
-
407
-                                foreach ($value as $relationAttribute => $relationValue) {
408
-                                    /**
409
-                                     * Prevent attributes not in the fillable.
410
-                                     */
411
-                                    if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
412
-                                        $relationModel->$relationAttribute = $relationValue;
413
-                                    }
414
-                                }
415
-
416
-                                $relations[$relation] = $relationModel;
417
-                            }
418
-                        }
419
-                    }
420
-                }
421
-            }
422
-        }
423
-
424
-        return $relations;
425
-    }
426
-
427
-    /**
428
-     * Save the model with related models.
429
-     *
430
-     * @param   Model $model
431
-     * @param   array $relations
432
-     *
433
-     * @return  Model
434
-     */
435
-    protected function saveModel(Model $model, array $relations): Model
436
-    {
437
-
438
-        /**
439
-         * Loop through the relations array.
440
-         */
441
-        foreach ($relations as $key => $value) {
442
-            /**
443
-             * If the relation is marked for delete then delete it.
444
-             */
445
-            if ($value == 'delete' && $model->$key()->count()) {
446
-                switch (class_basename($model->$key())) {
447
-                        /**
448
-                     * If the relation is one to many then delete all
449
-                     * relations who's id isn't in the ids array.
450
-                     */
451
-                    case 'HasMany':
452
-                        $model->$key()->delete();
453
-                        break;
454
-
455
-                        /**
456
-                         * If the relation is many to many then
457
-                         * detach the previous data and attach
458
-                         * the ids array to the model.
459
-                         */
460
-                    case 'BelongsToMany':
461
-                        $model->$key()->detach();
462
-                        break;
463
-                }
464
-            } elseif (gettype($value) == 'array') {
465
-                /**
466
-                 * Save the model.
467
-                 */
468
-                $model->save();
469
-                $ids = [];
470
-
471
-                /**
472
-                 * Loop through the relations.
473
-                 */
474
-                foreach ($value as $val) {
475
-                    switch (class_basename($model->$key())) {
476
-                            /**
477
-                         * If the relation is one to many then update it's foreign key with
478
-                         * the model id and save it then add its id to ids array to delete all
479
-                         * relations who's id isn't in the ids array.
480
-                         */
481
-                        case 'HasMany':
482
-                            $foreignKeyName       = $model->$key()->getForeignKeyName();
483
-                            $val->$foreignKeyName = $model->id;
484
-                            $val->save();
485
-                            $ids[] = $val->id;
486
-                            break;
487
-
488
-                            /**
489
-                             * If the relation is many to many then add it's id to the ids array to
490
-                             * attache these ids to the model.
491
-                             */
492
-                        case 'BelongsToMany':
493
-                        case 'MorphToMany':
494
-                            $extra = $val->extra;
495
-                            unset($val->extra);
496
-                            $val->save();
497
-                            $ids[$val->id] = $extra ?? [];
498
-                            break;
499
-                    }
500
-                }
501
-                switch (class_basename($model->$key())) {
502
-                        /**
503
-                     * If the relation is one to many then delete all
504
-                     * relations who's id isn't in the ids array.
505
-                     */
506
-                    case 'HasMany':
507
-                        $model->$key()->whereNotIn('id', $ids)->delete();
508
-                        break;
509
-
510
-                        /**
511
-                         * If the relation is many to many then
512
-                         * detach the previous data and attach
513
-                         * the ids array to the model.
514
-                         */
515
-                    case 'BelongsToMany':
516
-                    case 'MorphToMany':
517
-                        $model->$key()->detach();
518
-                        $model->$key()->attach($ids);
519
-                        break;
520
-                }
521
-            } else {
522
-                switch (class_basename($model->$key())) {
523
-                        /**
524
-                     * If the relation is one to one.
525
-                     */
526
-                    case 'HasOne':
527
-                        /**
528
-                         * Save the model.
529
-                         */
530
-                        $model->save();
531
-                        $foreignKeyName         = $model->$key()->getForeignKeyName();
532
-                        $value->$foreignKeyName = $model->id;
533
-                        $value->save();
534
-                        break;
535
-                    case 'BelongsTo':
536
-                        /**
537
-                         * Save the model.
538
-                         */
539
-                        $value->save();
540
-                        $model->$key()->associate($value);
541
-                        break;
542
-                }
543
-            }
544
-        }
545
-
546
-        /**
547
-         * Save the model.
548
-         */
549
-        $model->save();
550
-
551
-        return $model;
552
-    }
553
-
554
-    /**
555
-     * Build the conditions recursively for the retrieving methods.
556
-     *
557
-     * @param  array $conditions
558
-     * @param  Model $model
559
-     * @return array
560
-     */
561
-    protected function constructConditions(array $conditions, Model $model): array
562
-    {
563
-        $conditionString = '';
564
-        $conditionValues = [];
565
-        foreach ($conditions as $key => $value) {
566
-            if (Str::contains($key, '->')) {
567
-                $key = $this->wrapJsonSelector($key);
568
-            }
569
-
570
-            if ($key == 'and') {
571
-                $conditions       = $this->constructConditions($value, $model);
572
-                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']) . ' {op} ';
573
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
574
-            } elseif ($key == 'or') {
575
-                $conditions       = $this->constructConditions($value, $model);
576
-                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']) . ' {op} ';
577
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
578
-            } else {
579
-                if (is_array($value)) {
580
-                    $operator = $value['op'];
581
-                    if (strtolower($operator) == 'between') {
582
-                        $value1 = $value['val1'];
583
-                        $value2 = $value['val2'];
584
-                    } else {
585
-                        $value = Arr::get($value, 'val', '');
586
-                    }
587
-                } else {
588
-                    $operator = '=';
589
-                }
590
-
591
-                if (strtolower($operator) == 'between') {
592
-                    $conditionString  .= $key . ' >= ? and ';
593
-                    $conditionValues[] = $value1;
594
-
595
-                    $conditionString  .= $key . ' <= ? {op} ';
596
-                    $conditionValues[] = $value2;
597
-                } elseif (strtolower($operator) == 'in') {
598
-                    $conditionValues  = array_merge($conditionValues, $value);
599
-                    $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
600
-                    $conditionString .= $key . ' in (' . rtrim($inBindingsString, ',') . ') {op} ';
601
-                } elseif (strtolower($operator) == 'null') {
602
-                    $conditionString .= $key . ' is null {op} ';
603
-                } elseif (strtolower($operator) == 'not null') {
604
-                    $conditionString .= $key . ' is not null {op} ';
605
-                } elseif (strtolower($operator) == 'has') {
606
-                    $sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
607
-                    $bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
608
-                    if ($value) {
609
-                        $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
610
-                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1) . ' and ' . $conditions['conditionString'] . ') {op} ';
611
-                        $conditionValues  = array_merge($conditionValues, $bindings);
612
-                        $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
613
-                    } else {
614
-                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1) . ') {op} ';
615
-                        $conditionValues  = array_merge($conditionValues, $bindings);
616
-                    }
617
-                } else {
618
-                    $conditionString  .= $key . ' ' . $operator . ' ? {op} ';
619
-                    $conditionValues[] = $value;
620
-                }
621
-            }
622
-        }
623
-        $conditionString = '(' . rtrim($conditionString, '{op} ') . ')';
624
-        return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
625
-    }
626
-
627
-    /**
628
-     * Wrap the given JSON selector.
629
-     *
630
-     * @param  string  $value
631
-     * @return string
632
-     */
633
-    protected function wrapJsonSelector(string $value): string
634
-    {
635
-        $removeLast = strpos($value, ')');
636
-        $value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
637
-        $path       = explode('->', $value);
638
-        $field      = array_shift($path);
639
-        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
640
-            return '"' . $part . '"';
641
-        })->implode('.'));
642
-
643
-        return $removeLast === false ? $result : $result . ')';
644
-    }
17
+	/**
18
+	 * @var Model
19
+	 */
20
+	public $model;
21
+
22
+	/**
23
+	 * Init new object.
24
+	 *
25
+	 * @param   Model$model
26
+	 * @return  void
27
+	 */
28
+	public function __construct(Model $model)
29
+	{
30
+		$this->model = $model;
31
+	}
32
+
33
+	/**
34
+	 * Fetch all records with relations from the storage.
35
+	 *
36
+	 * @param  array  $relations
37
+	 * @param  string $sortBy
38
+	 * @param  bool   $desc
39
+	 * @param  array  $columns
40
+	 * @return collection
41
+	 */
42
+	public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
43
+	{
44
+		$sort = $desc ? 'desc' : 'asc';
45
+		return $this->model->with($relations)->orderBy($sortBy, $sort)->get($columns);
46
+	}
47
+
48
+	/**
49
+	 * Fetch all records with relations from storage in pages.
50
+	 *
51
+	 * @param  int    $perPage
52
+	 * @param  array  $relations
53
+	 * @param  string $sortBy
54
+	 * @param  bool   $desc
55
+	 * @param  array  $columns
56
+	 * @return LengthAwarePaginator
57
+	 */
58
+	public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
59
+	{
60
+		$sort = $desc ? 'desc' : 'asc';
61
+		return $this->model->with($relations)->orderBy($sortBy, $sort)->paginate($perPage, $columns);
62
+	}
63
+
64
+	/**
65
+	 * Fetch all records with relations based on
66
+	 * the given condition from storage in pages.
67
+	 *
68
+	 * @param  array  $conditions array of conditions
69
+	 * @param  int    $perPage
70
+	 * @param  array  $relations
71
+	 * @param  string $sortBy
72
+	 * @param  bool   $desc
73
+	 * @param  array  $columns
74
+	 * @return LengthAwarePaginator
75
+	 */
76
+	public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
77
+	{
78
+		$conditions = $this->constructConditions($conditions, $this->model);
79
+		$sort       = $desc ? 'desc' : 'asc';
80
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
81
+	}
82
+
83
+	/**
84
+	 * Count all records based on the given condition from storage.
85
+	 *
86
+	 * @param  array $conditions array of conditions
87
+	 * @return int
88
+	 */
89
+	public function count(array $conditions = []): int
90
+	{
91
+		if ($conditions) {
92
+			$conditions = $this->constructConditions($conditions, $this->model);
93
+			return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->count();
94
+		}
95
+
96
+		return $this->model->count();
97
+	}
98
+
99
+	/**
100
+	 * Pluck column based on the given condition from storage.
101
+	 *
102
+	 * @param  array  $conditions array of conditions
103
+	 * @param  string $column
104
+	 * @return collection
105
+	 */
106
+	public function pluck(array $conditions, string $column): Collection
107
+	{
108
+		$conditions = $this->constructConditions($conditions, $this->model);
109
+		return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->pluck($column);
110
+	}
111
+
112
+	/**
113
+	 * Save the given model to the storage.
114
+	 *
115
+	 * @param  array $data
116
+	 * @return Model
117
+	 */
118
+	public function save(array $data): Model
119
+	{
120
+		$model      = new Model();
121
+		$relations  = [];
122
+
123
+		DB::transaction(function () use (&$model, &$relations, $data) {
124
+
125
+			$model     = $this->prepareModel($data);
126
+			$relations = $this->prepareRelations($data, $model);
127
+			$model     = $this->saveModel($model, $relations);
128
+		});
129
+
130
+		if (count($relations)) {
131
+			$model->load(...array_keys($relations));
132
+		}
133
+
134
+		return $model;
135
+	}
136
+
137
+	/**
138
+	 * Insert the given model/models to the storage.
139
+	 *
140
+	 * @param  array $data
141
+	 * @return bool
142
+	 */
143
+	public function insert(array $data): bool
144
+	{
145
+		return $this->model->insert($data);
146
+	}
147
+
148
+	/**
149
+	 * Delete record from the storage based on the given
150
+	 * condition.
151
+	 *
152
+	 * @param  string $value condition value
153
+	 * @param  string $attribute condition column name
154
+	 * @return bool
155
+	 */
156
+	public function delete(string $value, string $attribute = 'id'): bool
157
+	{
158
+		DB::transaction(function () use ($value, $attribute) {
159
+			$this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
160
+				$model->delete();
161
+			});
162
+		});
163
+
164
+		return true;
165
+	}
166
+
167
+	/**
168
+	 * Fetch records from the storage based on the given
169
+	 * id.
170
+	 *
171
+	 * @param  int   $id
172
+	 * @param  array $relations
173
+	 * @param  array $columns
174
+	 * @return Model
175
+	 */
176
+	public function find(int $id, array $relations = [], array $columns = ['*']): Model
177
+	{
178
+		return $this->model->with($relations)->find($id, $columns);
179
+	}
180
+
181
+	/**
182
+	 * Fetch records from the storage based on the given
183
+	 * condition.
184
+	 *
185
+	 * @param  array   $conditions array of conditions
186
+	 * @param  array   $relations
187
+	 * @param  string  $sortBy
188
+	 * @param  bool    $desc
189
+	 * @param  array   $columns
190
+	 * @return collection
191
+	 */
192
+	public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
193
+	{
194
+		$conditions = $this->constructConditions($conditions, $this->model);
195
+		$sort       = $desc ? 'desc' : 'asc';
196
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
197
+	}
198
+
199
+	/**
200
+	 * Fetch the first record from the storage based on the given
201
+	 * condition.
202
+	 *
203
+	 * @param  array $conditions array of conditions
204
+	 * @param  array $relations
205
+	 * @param  array $columns
206
+	 * @return Model
207
+	 */
208
+	public function first(array $conditions, array $relations = [], array $columns = ['*']): Model
209
+	{
210
+		$conditions = $this->constructConditions($conditions, $this->model);
211
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
212
+	}
213
+
214
+	/**
215
+	 * Return the deleted models in pages based on the given conditions.
216
+	 *
217
+	 * @param  array  $conditions array of conditions
218
+	 * @param  int    $perPage
219
+	 * @param  string $sortBy
220
+	 * @param  bool   $desc
221
+	 * @param  array  $columns
222
+	 * @return LengthAwarePaginator
223
+	 */
224
+	public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
225
+	{
226
+		unset($conditions['page']);
227
+		unset($conditions['perPage']);
228
+		unset($conditions['sortBy']);
229
+		unset($conditions['sort']);
230
+		$conditions = $this->constructConditions($conditions, $this->model);
231
+		$sort       = $desc ? 'desc' : 'asc';
232
+		$model      = $this->model->onlyTrashed();
233
+
234
+		if (count($conditions['conditionValues'])) {
235
+			$model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
236
+		}
237
+
238
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
239
+	}
240
+
241
+	/**
242
+	 * Restore the deleted model.
243
+	 *
244
+	 * @param  int $id
245
+	 * @return bool
246
+	 */
247
+	public function restore(int $id): bool
248
+	{
249
+		$model = $this->model->onlyTrashed()->find($id);
250
+
251
+		if (!$model) {
252
+			Errors::notFound(class_basename($this->model) . ' with id : ' . $id);
253
+		}
254
+
255
+		$model->restore();
256
+
257
+		return true;
258
+	}
259
+
260
+	/**
261
+	 * Fill the model with the given data.
262
+	 *
263
+	 * @param   array  $data
264
+	 * @return  Model
265
+	 */
266
+	protected function prepareModel(array $data): Model
267
+	{
268
+		$modelClass = $this->model;
269
+
270
+		/**
271
+		 * If the id is present in the data then select the model for updating,
272
+		 * else create new model.
273
+		 *
274
+		 * @var object
275
+		 */
276
+		$model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
277
+		if (!$model) {
278
+			Errors::notFound(class_basename($modelClass) . ' with id : ' . $data['id']);
279
+		}
280
+
281
+		/**
282
+		 * Construct the model object with the given data,
283
+		 * and if there is a relation add it to relations array,
284
+		 * then save the model.
285
+		 */
286
+		foreach ($data as $key => $value) {
287
+			if (array_search($key, $model->getFillable(), true) !== false) {
288
+				/**
289
+				 * If the attribute isn't a relation and prevent attributes not in the fillable.
290
+				 */
291
+				$model->$key = $value;
292
+			}
293
+		}
294
+
295
+		return $model;
296
+	}
297
+
298
+	/**
299
+	 * Prepare related models based on the given data for the given model.
300
+	 *
301
+	 * @param   array $data
302
+	 * @param   Model $model
303
+	 *
304
+	 * @return  array
305
+	 */
306
+	protected function prepareRelations(array $data, Model $model): array
307
+	{
308
+		/**
309
+		 * Init the relation array
310
+		 *
311
+		 * @var array
312
+		 */
313
+		$relations = [];
314
+
315
+		/**
316
+		 * Construct the model object with the given data,
317
+		 * and if there is a relation add it to relations array,
318
+		 * then save the model.
319
+		 */
320
+		foreach ($data as $key => $value) {
321
+			/**
322
+			 * If the attribute is a relation.
323
+			 */
324
+			$relation = Str::camel($key);
325
+			if (method_exists($model, $relation) && Core::$relation()) {
326
+				/**
327
+				 * Check if the relation is a collection.
328
+				 */
329
+				if (class_basename($model->$relation) == 'Collection') {
330
+					/**
331
+					 * If the relation has no value then marke the relation data
332
+					 * related to the model to be deleted.
333
+					 */
334
+					if (!$value || !count($value)) {
335
+						$relations[$relation] = 'delete';
336
+					}
337
+				}
338
+				if (is_array($value)) {
339
+					/**
340
+					 * Loop through the relation data.
341
+					 */
342
+					foreach ($value as $attr => $val) {
343
+						/**
344
+						 * Get the relation model.
345
+						 */
346
+						$relationBaseModel = Core::$relation()->model;
347
+
348
+						/**
349
+						 * Check if the relation is a collection.
350
+						 */
351
+						if (class_basename($model->$relation) == 'Collection') {
352
+							if (!is_array($val)) {
353
+								$relationModel = $relationBaseModel->lockForUpdate()->find($val);
354
+							} else {
355
+								/**
356
+								 * If the id is present in the data then select the relation model for updating,
357
+								 * else create new model.
358
+								 */
359
+								$relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
360
+							}
361
+
362
+							/**
363
+							 * If model doesn't exists.
364
+							 */
365
+							if (!$relationModel) {
366
+								Errors::notFound(class_basename($relationBaseModel) . ' with id : ' . $val['id']);
367
+							}
368
+
369
+							if (is_array($val)) {
370
+								/**
371
+								 * Loop through the relation attributes.
372
+								 */
373
+								foreach ($val as $attr => $val) {
374
+									/**
375
+									 * Prevent the sub relations or attributes not in the fillable.
376
+									 */
377
+									if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false && class_basename($model->$key()) !== 'BelongsToMany') {
378
+										$relationModel->$attr = $val;
379
+									} elseif (gettype($val) !== 'object' && gettype($val) !== 'array' && $attr !== 'id') {
380
+										$extra[$attr] = $val;
381
+									}
382
+								}
383
+							}
384
+
385
+							if (isset($extra)) {
386
+								$relationModel->extra = $extra;
387
+							}
388
+							$relations[$relation][] = $relationModel;
389
+						} else {
390
+							/**
391
+							 * Prevent the sub relations.
392
+							 */
393
+							if (gettype($val) !== 'object' && gettype($val) !== 'array') {
394
+								/**
395
+								 * If the id is present in the data then select the relation model for updating,
396
+								 * else create new model.
397
+								 */
398
+								$relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
399
+
400
+								/**
401
+								 * If model doesn't exists.
402
+								 */
403
+								if (!$relationModel) {
404
+									Errors::notFound(class_basename($relationBaseModel) . ' with id : ' . $value['id']);
405
+								}
406
+
407
+								foreach ($value as $relationAttribute => $relationValue) {
408
+									/**
409
+									 * Prevent attributes not in the fillable.
410
+									 */
411
+									if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
412
+										$relationModel->$relationAttribute = $relationValue;
413
+									}
414
+								}
415
+
416
+								$relations[$relation] = $relationModel;
417
+							}
418
+						}
419
+					}
420
+				}
421
+			}
422
+		}
423
+
424
+		return $relations;
425
+	}
426
+
427
+	/**
428
+	 * Save the model with related models.
429
+	 *
430
+	 * @param   Model $model
431
+	 * @param   array $relations
432
+	 *
433
+	 * @return  Model
434
+	 */
435
+	protected function saveModel(Model $model, array $relations): Model
436
+	{
437
+
438
+		/**
439
+		 * Loop through the relations array.
440
+		 */
441
+		foreach ($relations as $key => $value) {
442
+			/**
443
+			 * If the relation is marked for delete then delete it.
444
+			 */
445
+			if ($value == 'delete' && $model->$key()->count()) {
446
+				switch (class_basename($model->$key())) {
447
+						/**
448
+						 * If the relation is one to many then delete all
449
+						 * relations who's id isn't in the ids array.
450
+						 */
451
+					case 'HasMany':
452
+						$model->$key()->delete();
453
+						break;
454
+
455
+						/**
456
+						 * If the relation is many to many then
457
+						 * detach the previous data and attach
458
+						 * the ids array to the model.
459
+						 */
460
+					case 'BelongsToMany':
461
+						$model->$key()->detach();
462
+						break;
463
+				}
464
+			} elseif (gettype($value) == 'array') {
465
+				/**
466
+				 * Save the model.
467
+				 */
468
+				$model->save();
469
+				$ids = [];
470
+
471
+				/**
472
+				 * Loop through the relations.
473
+				 */
474
+				foreach ($value as $val) {
475
+					switch (class_basename($model->$key())) {
476
+							/**
477
+							 * If the relation is one to many then update it's foreign key with
478
+							 * the model id and save it then add its id to ids array to delete all
479
+							 * relations who's id isn't in the ids array.
480
+							 */
481
+						case 'HasMany':
482
+							$foreignKeyName       = $model->$key()->getForeignKeyName();
483
+							$val->$foreignKeyName = $model->id;
484
+							$val->save();
485
+							$ids[] = $val->id;
486
+							break;
487
+
488
+							/**
489
+							 * If the relation is many to many then add it's id to the ids array to
490
+							 * attache these ids to the model.
491
+							 */
492
+						case 'BelongsToMany':
493
+						case 'MorphToMany':
494
+							$extra = $val->extra;
495
+							unset($val->extra);
496
+							$val->save();
497
+							$ids[$val->id] = $extra ?? [];
498
+							break;
499
+					}
500
+				}
501
+				switch (class_basename($model->$key())) {
502
+						/**
503
+						 * If the relation is one to many then delete all
504
+						 * relations who's id isn't in the ids array.
505
+						 */
506
+					case 'HasMany':
507
+						$model->$key()->whereNotIn('id', $ids)->delete();
508
+						break;
509
+
510
+						/**
511
+						 * If the relation is many to many then
512
+						 * detach the previous data and attach
513
+						 * the ids array to the model.
514
+						 */
515
+					case 'BelongsToMany':
516
+					case 'MorphToMany':
517
+						$model->$key()->detach();
518
+						$model->$key()->attach($ids);
519
+						break;
520
+				}
521
+			} else {
522
+				switch (class_basename($model->$key())) {
523
+						/**
524
+						 * If the relation is one to one.
525
+						 */
526
+					case 'HasOne':
527
+						/**
528
+						 * Save the model.
529
+						 */
530
+						$model->save();
531
+						$foreignKeyName         = $model->$key()->getForeignKeyName();
532
+						$value->$foreignKeyName = $model->id;
533
+						$value->save();
534
+						break;
535
+					case 'BelongsTo':
536
+						/**
537
+						 * Save the model.
538
+						 */
539
+						$value->save();
540
+						$model->$key()->associate($value);
541
+						break;
542
+				}
543
+			}
544
+		}
545
+
546
+		/**
547
+		 * Save the model.
548
+		 */
549
+		$model->save();
550
+
551
+		return $model;
552
+	}
553
+
554
+	/**
555
+	 * Build the conditions recursively for the retrieving methods.
556
+	 *
557
+	 * @param  array $conditions
558
+	 * @param  Model $model
559
+	 * @return array
560
+	 */
561
+	protected function constructConditions(array $conditions, Model $model): array
562
+	{
563
+		$conditionString = '';
564
+		$conditionValues = [];
565
+		foreach ($conditions as $key => $value) {
566
+			if (Str::contains($key, '->')) {
567
+				$key = $this->wrapJsonSelector($key);
568
+			}
569
+
570
+			if ($key == 'and') {
571
+				$conditions       = $this->constructConditions($value, $model);
572
+				$conditionString .= str_replace('{op}', 'and', $conditions['conditionString']) . ' {op} ';
573
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
574
+			} elseif ($key == 'or') {
575
+				$conditions       = $this->constructConditions($value, $model);
576
+				$conditionString .= str_replace('{op}', 'or', $conditions['conditionString']) . ' {op} ';
577
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
578
+			} else {
579
+				if (is_array($value)) {
580
+					$operator = $value['op'];
581
+					if (strtolower($operator) == 'between') {
582
+						$value1 = $value['val1'];
583
+						$value2 = $value['val2'];
584
+					} else {
585
+						$value = Arr::get($value, 'val', '');
586
+					}
587
+				} else {
588
+					$operator = '=';
589
+				}
590
+
591
+				if (strtolower($operator) == 'between') {
592
+					$conditionString  .= $key . ' >= ? and ';
593
+					$conditionValues[] = $value1;
594
+
595
+					$conditionString  .= $key . ' <= ? {op} ';
596
+					$conditionValues[] = $value2;
597
+				} elseif (strtolower($operator) == 'in') {
598
+					$conditionValues  = array_merge($conditionValues, $value);
599
+					$inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
600
+					$conditionString .= $key . ' in (' . rtrim($inBindingsString, ',') . ') {op} ';
601
+				} elseif (strtolower($operator) == 'null') {
602
+					$conditionString .= $key . ' is null {op} ';
603
+				} elseif (strtolower($operator) == 'not null') {
604
+					$conditionString .= $key . ' is not null {op} ';
605
+				} elseif (strtolower($operator) == 'has') {
606
+					$sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
607
+					$bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
608
+					if ($value) {
609
+						$conditions       = $this->constructConditions($value, $model->$key()->getRelated());
610
+						$conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1) . ' and ' . $conditions['conditionString'] . ') {op} ';
611
+						$conditionValues  = array_merge($conditionValues, $bindings);
612
+						$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
613
+					} else {
614
+						$conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1) . ') {op} ';
615
+						$conditionValues  = array_merge($conditionValues, $bindings);
616
+					}
617
+				} else {
618
+					$conditionString  .= $key . ' ' . $operator . ' ? {op} ';
619
+					$conditionValues[] = $value;
620
+				}
621
+			}
622
+		}
623
+		$conditionString = '(' . rtrim($conditionString, '{op} ') . ')';
624
+		return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
625
+	}
626
+
627
+	/**
628
+	 * Wrap the given JSON selector.
629
+	 *
630
+	 * @param  string  $value
631
+	 * @return string
632
+	 */
633
+	protected function wrapJsonSelector(string $value): string
634
+	{
635
+		$removeLast = strpos($value, ')');
636
+		$value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
637
+		$path       = explode('->', $value);
638
+		$field      = array_shift($path);
639
+		$result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
640
+			return '"' . $part . '"';
641
+		})->implode('.'));
642
+
643
+		return $removeLast === false ? $result : $result . ')';
644
+	}
645 645
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
         $model      = new Model();
121 121
         $relations  = [];
122 122
 
123
-        DB::transaction(function () use (&$model, &$relations, $data) {
123
+        DB::transaction(function() use (&$model, &$relations, $data) {
124 124
 
125 125
             $model     = $this->prepareModel($data);
126 126
             $relations = $this->prepareRelations($data, $model);
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
      */
156 156
     public function delete(string $value, string $attribute = 'id'): bool
157 157
     {
158
-        DB::transaction(function () use ($value, $attribute) {
159
-            $this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
158
+        DB::transaction(function() use ($value, $attribute) {
159
+            $this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function($model) {
160 160
                 $model->delete();
161 161
             });
162 162
         });
@@ -248,8 +248,8 @@  discard block
 block discarded – undo
248 248
     {
249 249
         $model = $this->model->onlyTrashed()->find($id);
250 250
 
251
-        if (!$model) {
252
-            Errors::notFound(class_basename($this->model) . ' with id : ' . $id);
251
+        if ( ! $model) {
252
+            Errors::notFound(class_basename($this->model).' with id : '.$id);
253 253
         }
254 254
 
255 255
         $model->restore();
@@ -274,8 +274,8 @@  discard block
 block discarded – undo
274 274
          * @var object
275 275
          */
276 276
         $model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
277
-        if (!$model) {
278
-            Errors::notFound(class_basename($modelClass) . ' with id : ' . $data['id']);
277
+        if ( ! $model) {
278
+            Errors::notFound(class_basename($modelClass).' with id : '.$data['id']);
279 279
         }
280 280
 
281 281
         /**
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
                      * If the relation has no value then marke the relation data
332 332
                      * related to the model to be deleted.
333 333
                      */
334
-                    if (!$value || !count($value)) {
334
+                    if ( ! $value || ! count($value)) {
335 335
                         $relations[$relation] = 'delete';
336 336
                     }
337 337
                 }
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
                          * Check if the relation is a collection.
350 350
                          */
351 351
                         if (class_basename($model->$relation) == 'Collection') {
352
-                            if (!is_array($val)) {
352
+                            if ( ! is_array($val)) {
353 353
                                 $relationModel = $relationBaseModel->lockForUpdate()->find($val);
354 354
                             } else {
355 355
                                 /**
@@ -362,8 +362,8 @@  discard block
 block discarded – undo
362 362
                             /**
363 363
                              * If model doesn't exists.
364 364
                              */
365
-                            if (!$relationModel) {
366
-                                Errors::notFound(class_basename($relationBaseModel) . ' with id : ' . $val['id']);
365
+                            if ( ! $relationModel) {
366
+                                Errors::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
367 367
                             }
368 368
 
369 369
                             if (is_array($val)) {
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
                                 /**
401 401
                                  * If model doesn't exists.
402 402
                                  */
403
-                                if (!$relationModel) {
404
-                                    Errors::notFound(class_basename($relationBaseModel) . ' with id : ' . $value['id']);
403
+                                if ( ! $relationModel) {
404
+                                    Errors::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
405 405
                                 }
406 406
 
407 407
                                 foreach ($value as $relationAttribute => $relationValue) {
@@ -569,11 +569,11 @@  discard block
 block discarded – undo
569 569
 
570 570
             if ($key == 'and') {
571 571
                 $conditions       = $this->constructConditions($value, $model);
572
-                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']) . ' {op} ';
572
+                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
573 573
                 $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
574 574
             } elseif ($key == 'or') {
575 575
                 $conditions       = $this->constructConditions($value, $model);
576
-                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']) . ' {op} ';
576
+                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
577 577
                 $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
578 578
             } else {
579 579
                 if (is_array($value)) {
@@ -589,38 +589,38 @@  discard block
 block discarded – undo
589 589
                 }
590 590
 
591 591
                 if (strtolower($operator) == 'between') {
592
-                    $conditionString  .= $key . ' >= ? and ';
592
+                    $conditionString  .= $key.' >= ? and ';
593 593
                     $conditionValues[] = $value1;
594 594
 
595
-                    $conditionString  .= $key . ' <= ? {op} ';
595
+                    $conditionString  .= $key.' <= ? {op} ';
596 596
                     $conditionValues[] = $value2;
597 597
                 } elseif (strtolower($operator) == 'in') {
598 598
                     $conditionValues  = array_merge($conditionValues, $value);
599 599
                     $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
600
-                    $conditionString .= $key . ' in (' . rtrim($inBindingsString, ',') . ') {op} ';
600
+                    $conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
601 601
                 } elseif (strtolower($operator) == 'null') {
602
-                    $conditionString .= $key . ' is null {op} ';
602
+                    $conditionString .= $key.' is null {op} ';
603 603
                 } elseif (strtolower($operator) == 'not null') {
604
-                    $conditionString .= $key . ' is not null {op} ';
604
+                    $conditionString .= $key.' is not null {op} ';
605 605
                 } elseif (strtolower($operator) == 'has') {
606 606
                     $sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
607 607
                     $bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
608 608
                     if ($value) {
609 609
                         $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
610
-                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1) . ' and ' . $conditions['conditionString'] . ') {op} ';
610
+                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
611 611
                         $conditionValues  = array_merge($conditionValues, $bindings);
612 612
                         $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
613 613
                     } else {
614
-                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1) . ') {op} ';
614
+                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).') {op} ';
615 615
                         $conditionValues  = array_merge($conditionValues, $bindings);
616 616
                     }
617 617
                 } else {
618
-                    $conditionString  .= $key . ' ' . $operator . ' ? {op} ';
618
+                    $conditionString  .= $key.' '.$operator.' ? {op} ';
619 619
                     $conditionValues[] = $value;
620 620
                 }
621 621
             }
622 622
         }
623
-        $conditionString = '(' . rtrim($conditionString, '{op} ') . ')';
623
+        $conditionString = '('.rtrim($conditionString, '{op} ').')';
624 624
         return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
625 625
     }
626 626
 
@@ -636,10 +636,10 @@  discard block
 block discarded – undo
636 636
         $value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
637 637
         $path       = explode('->', $value);
638 638
         $field      = array_shift($path);
639
-        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
640
-            return '"' . $part . '"';
639
+        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function($part) {
640
+            return '"'.$part.'"';
641 641
         })->implode('.'));
642 642
 
643
-        return $removeLast === false ? $result : $result . ')';
643
+        return $removeLast === false ? $result : $result.')';
644 644
     }
645 645
 }
Please login to merge, or discard this patch.
src/Modules/Core/BaseClasses/BaseService.php 2 patches
Indentation   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -11,257 +11,257 @@
 block discarded – undo
11 11
 
12 12
 abstract class BaseService implements BaseServiceInterface
13 13
 {
14
-    /**
15
-     * @var BaseRepositoryInterface
16
-     */
17
-    public $repo;
14
+	/**
15
+	 * @var BaseRepositoryInterface
16
+	 */
17
+	public $repo;
18 18
 
19
-    /**
20
-     * @var Session
21
-     */
22
-    public $session;
19
+	/**
20
+	 * @var Session
21
+	 */
22
+	public $session;
23 23
 
24
-    /**
25
-     * Init new object.
26
-     *
27
-     * @param   BaseRepositoryInterface $repo
28
-     * @param   Session $session
29
-     * @return  void
30
-     */
31
-    public function __construct(BaseRepositoryInterface $repo, Session $session)
32
-    {
33
-        $this->repo = $repo;
34
-        $this->session = $session;
35
-    }
24
+	/**
25
+	 * Init new object.
26
+	 *
27
+	 * @param   BaseRepositoryInterface $repo
28
+	 * @param   Session $session
29
+	 * @return  void
30
+	 */
31
+	public function __construct(BaseRepositoryInterface $repo, Session $session)
32
+	{
33
+		$this->repo = $repo;
34
+		$this->session = $session;
35
+	}
36 36
 
37
-    /**
38
-     * Fetch records with relations based on the given params.
39
-     *
40
-     * @param   array  $relations
41
-     * @param   array  $conditions
42
-     * @param   int    $perPage
43
-     * @param   string $sortBy
44
-     * @param   bool   $desc
45
-     * @param   bool   $trashed
46
-     * @return LengthAwarePaginator
47
-     */
48
-    public function list(array $relations = [], array $conditions = [], int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, bool $trashed = false): LengthAwarePaginator
49
-    {
50
-        $translatable = $this->repo->model->translatable ?? [];
51
-        $filters = $this->constructFilters($conditions);
52
-        $sortBy = in_array($sortBy, $translatable) ? $sortBy . '->' . $this->session->get('locale') : $sortBy;
37
+	/**
38
+	 * Fetch records with relations based on the given params.
39
+	 *
40
+	 * @param   array  $relations
41
+	 * @param   array  $conditions
42
+	 * @param   int    $perPage
43
+	 * @param   string $sortBy
44
+	 * @param   bool   $desc
45
+	 * @param   bool   $trashed
46
+	 * @return LengthAwarePaginator
47
+	 */
48
+	public function list(array $relations = [], array $conditions = [], int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, bool $trashed = false): LengthAwarePaginator
49
+	{
50
+		$translatable = $this->repo->model->translatable ?? [];
51
+		$filters = $this->constructFilters($conditions);
52
+		$sortBy = in_array($sortBy, $translatable) ? $sortBy . '->' . $this->session->get('locale') : $sortBy;
53 53
 
54
-        if ($trashed) {
55
-            return $this->deleted(['and' => $filters], $perPage ?? 15, $sortBy ?? 'created_at', $desc ?? true);
56
-        }
54
+		if ($trashed) {
55
+			return $this->deleted(['and' => $filters], $perPage ?? 15, $sortBy ?? 'created_at', $desc ?? true);
56
+		}
57 57
 
58
-        if (count($filters)) {
59
-            return $this->paginateBy(['and' => $filters], $perPage ?? 15, $relations, $sortBy ?? 'created_at', $desc ?? true);
60
-        }
58
+		if (count($filters)) {
59
+			return $this->paginateBy(['and' => $filters], $perPage ?? 15, $relations, $sortBy ?? 'created_at', $desc ?? true);
60
+		}
61 61
 
62
-        return $this->paginate($perPage ?? 15, $relations, $sortBy ?? 'created_at', $desc ?? true);
63
-    }
62
+		return $this->paginate($perPage ?? 15, $relations, $sortBy ?? 'created_at', $desc ?? true);
63
+	}
64 64
 
65
-    /**
66
-     * Fetch all records with relations from the storage.
67
-     *
68
-     * @param  array   $relations
69
-     * @param  string  $sortBy
70
-     * @param  boolean $desc
71
-     * @param  array   $columns
72
-     * @return collection
73
-     */
74
-    public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
75
-    {
76
-        return $this->repo->all($relations, $sortBy, $desc, $columns);
77
-    }
65
+	/**
66
+	 * Fetch all records with relations from the storage.
67
+	 *
68
+	 * @param  array   $relations
69
+	 * @param  string  $sortBy
70
+	 * @param  boolean $desc
71
+	 * @param  array   $columns
72
+	 * @return collection
73
+	 */
74
+	public function all(array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
75
+	{
76
+		return $this->repo->all($relations, $sortBy, $desc, $columns);
77
+	}
78 78
 
79
-    /**
80
-     * Fetch all records with relations from storage in pages.
81
-     *
82
-     * @param  integer $perPage
83
-     * @param  array   $relations
84
-     * @param  string  $sortBy
85
-     * @param  boolean $desc
86
-     * @param  array   $columns
87
-     * @return LengthAwarePaginator
88
-     */
89
-    public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
90
-    {
91
-        return $this->repo->paginate($perPage, $relations, $sortBy, $desc, $columns);
92
-    }
79
+	/**
80
+	 * Fetch all records with relations from storage in pages.
81
+	 *
82
+	 * @param  integer $perPage
83
+	 * @param  array   $relations
84
+	 * @param  string  $sortBy
85
+	 * @param  boolean $desc
86
+	 * @param  array   $columns
87
+	 * @return LengthAwarePaginator
88
+	 */
89
+	public function paginate(int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
90
+	{
91
+		return $this->repo->paginate($perPage, $relations, $sortBy, $desc, $columns);
92
+	}
93 93
 
94
-    /**
95
-     * Fetch all records with relations based on
96
-     * the given condition from storage in pages.
97
-     *
98
-     * @param  array   $conditions array of conditions
99
-     * @param  integer $perPage
100
-     * @param  array   $relations
101
-     * @param  string  $sortBy
102
-     * @param  boolean $desc
103
-     * @param  array   $columns
104
-     * @return LengthAwarePaginator
105
-     */
106
-    public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
107
-    {
108
-        return $this->repo->paginateBy($conditions, $perPage, $relations, $sortBy, $desc, $columns);
109
-    }
94
+	/**
95
+	 * Fetch all records with relations based on
96
+	 * the given condition from storage in pages.
97
+	 *
98
+	 * @param  array   $conditions array of conditions
99
+	 * @param  integer $perPage
100
+	 * @param  array   $relations
101
+	 * @param  string  $sortBy
102
+	 * @param  boolean $desc
103
+	 * @param  array   $columns
104
+	 * @return LengthAwarePaginator
105
+	 */
106
+	public function paginateBy(array $conditions, int $perPage = 15, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
107
+	{
108
+		return $this->repo->paginateBy($conditions, $perPage, $relations, $sortBy, $desc, $columns);
109
+	}
110 110
 
111
-    /**
112
-     * Save the given model to the storage.
113
-     *
114
-     * @param  array $data
115
-     * @return Model
116
-     */
117
-    public function save(array $data): Model
118
-    {
119
-        return $this->repo->save($data);
120
-    }
111
+	/**
112
+	 * Save the given model to the storage.
113
+	 *
114
+	 * @param  array $data
115
+	 * @return Model
116
+	 */
117
+	public function save(array $data): Model
118
+	{
119
+		return $this->repo->save($data);
120
+	}
121 121
 
122
-    /**
123
-     * Delete record from the storage based on the given
124
-     * condition.
125
-     *
126
-     * @param  string $value condition value
127
-     * @param  string $attribute condition column name
128
-     * @return bool
129
-     */
130
-    public function delete(string $value, string $attribute = 'id'): bool
131
-    {
132
-        return $this->repo->delete($value, $attribute);
133
-    }
122
+	/**
123
+	 * Delete record from the storage based on the given
124
+	 * condition.
125
+	 *
126
+	 * @param  string $value condition value
127
+	 * @param  string $attribute condition column name
128
+	 * @return bool
129
+	 */
130
+	public function delete(string $value, string $attribute = 'id'): bool
131
+	{
132
+		return $this->repo->delete($value, $attribute);
133
+	}
134 134
 
135
-    /**
136
-     * Fetch records from the storage based on the given
137
-     * id.
138
-     *
139
-     * @param  int   $id
140
-     * @param  array $relations
141
-     * @param  array $columns
142
-     * @return object
143
-     */
144
-    public function find(int $id, array $relations = [], array $columns = ['*']): Model
145
-    {
146
-        return $this->repo->find($id, $relations, $columns);
147
-    }
135
+	/**
136
+	 * Fetch records from the storage based on the given
137
+	 * id.
138
+	 *
139
+	 * @param  int   $id
140
+	 * @param  array $relations
141
+	 * @param  array $columns
142
+	 * @return object
143
+	 */
144
+	public function find(int $id, array $relations = [], array $columns = ['*']): Model
145
+	{
146
+		return $this->repo->find($id, $relations, $columns);
147
+	}
148 148
 
149
-    /**
150
-     * Fetch records from the storage based on the given
151
-     * condition.
152
-     *
153
-     * @param  array  $conditions array of conditions
154
-     * @param  array  $relations
155
-     * @param  string $sortBy
156
-     * @param  bool   $desc
157
-     * @param  array  $columns
158
-     * @return collection
159
-     */
160
-    public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
161
-    {
162
-        return $this->repo->findBy($conditions, $relations, $sortBy, $desc, $columns);
163
-    }
149
+	/**
150
+	 * Fetch records from the storage based on the given
151
+	 * condition.
152
+	 *
153
+	 * @param  array  $conditions array of conditions
154
+	 * @param  array  $relations
155
+	 * @param  string $sortBy
156
+	 * @param  bool   $desc
157
+	 * @param  array  $columns
158
+	 * @return collection
159
+	 */
160
+	public function findBy(array $conditions, array $relations = [], string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): Collection
161
+	{
162
+		return $this->repo->findBy($conditions, $relations, $sortBy, $desc, $columns);
163
+	}
164 164
 
165
-    /**
166
-     * Fetch the first record from the storage based on the given
167
-     * condition.
168
-     *
169
-     * @param  array $conditions array of conditions
170
-     * @param  array $relations
171
-     * @param  array $columns
172
-     * @return Model
173
-     */
174
-    public function first(array $conditions, array $relations = [], array $columns = ['*']): Model
175
-    {
176
-        return $this->repo->first($conditions, $relations, $columns);
177
-    }
165
+	/**
166
+	 * Fetch the first record from the storage based on the given
167
+	 * condition.
168
+	 *
169
+	 * @param  array $conditions array of conditions
170
+	 * @param  array $relations
171
+	 * @param  array $columns
172
+	 * @return Model
173
+	 */
174
+	public function first(array $conditions, array $relations = [], array $columns = ['*']): Model
175
+	{
176
+		return $this->repo->first($conditions, $relations, $columns);
177
+	}
178 178
 
179
-    /**
180
-     * Return the deleted models in pages based on the given conditions.
181
-     *
182
-     * @param  array  $conditions array of conditions
183
-     * @param  int    $perPage
184
-     * @param  string $sortBy
185
-     * @param  bool   $desc
186
-     * @param  array  $columns
187
-     * @return LengthAwarePaginator
188
-     */
189
-    public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
190
-    {
191
-        return $this->repo->deleted($conditions, $perPage, $sortBy, $desc, $columns);
192
-    }
179
+	/**
180
+	 * Return the deleted models in pages based on the given conditions.
181
+	 *
182
+	 * @param  array  $conditions array of conditions
183
+	 * @param  int    $perPage
184
+	 * @param  string $sortBy
185
+	 * @param  bool   $desc
186
+	 * @param  array  $columns
187
+	 * @return LengthAwarePaginator
188
+	 */
189
+	public function deleted(array $conditions, int $perPage = 15, string $sortBy = 'created_at', bool $desc = true, array $columns = ['*']): LengthAwarePaginator
190
+	{
191
+		return $this->repo->deleted($conditions, $perPage, $sortBy, $desc, $columns);
192
+	}
193 193
 
194
-    /**
195
-     * Restore the deleted model.
196
-     *
197
-     * @param  int $id
198
-     * @return bool
199
-     */
200
-    public function restore(int $id): bool
201
-    {
202
-        return $this->repo->restore($id);
203
-    }
194
+	/**
195
+	 * Restore the deleted model.
196
+	 *
197
+	 * @param  int $id
198
+	 * @return bool
199
+	 */
200
+	public function restore(int $id): bool
201
+	{
202
+		return $this->repo->restore($id);
203
+	}
204 204
 
205
-    /**
206
-     * Prepare filters for repo.
207
-     *
208
-     * @param  array $conditions
209
-     * @return array
210
-     */
211
-    protected function constructFilters(array $conditions): array
212
-    {
213
-        $filters = [];
214
-        $translatable = $this->repo->model->translatable ?? [];
215
-        foreach ($conditions as $key => $value) {
216
-            if ((in_array($key, $this->repo->model->fillable ?? []) || method_exists($this->repo->model, $key) || in_array($key, ['or', 'and'])) && $key !== 'trashed') {
217
-                /**
218
-                 * Prepare key based on the the requested lang if it was translatable.
219
-                 */
220
-                $key = in_array($key, $translatable) ? $key . '->' . ($this->session->get('locale') == 'all' ? 'en' : $this->session->get('locale')) : $key;
205
+	/**
206
+	 * Prepare filters for repo.
207
+	 *
208
+	 * @param  array $conditions
209
+	 * @return array
210
+	 */
211
+	protected function constructFilters(array $conditions): array
212
+	{
213
+		$filters = [];
214
+		$translatable = $this->repo->model->translatable ?? [];
215
+		foreach ($conditions as $key => $value) {
216
+			if ((in_array($key, $this->repo->model->fillable ?? []) || method_exists($this->repo->model, $key) || in_array($key, ['or', 'and'])) && $key !== 'trashed') {
217
+				/**
218
+				 * Prepare key based on the the requested lang if it was translatable.
219
+				 */
220
+				$key = in_array($key, $translatable) ? $key . '->' . ($this->session->get('locale') == 'all' ? 'en' : $this->session->get('locale')) : $key;
221 221
 
222
-                /**
223
-                 * Convert 0/1 or true/false to boolean in case of not foreign key.
224
-                 */
225
-                if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null && strpos($key, '_id') === false && !is_null($value)) {
226
-                    $filters[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
222
+				/**
223
+				 * Convert 0/1 or true/false to boolean in case of not foreign key.
224
+				 */
225
+				if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null && strpos($key, '_id') === false && !is_null($value)) {
226
+					$filters[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
227 227
 
228
-                    /**
229
-                     * Use in operator in case of foreign and comma seperated values.
230
-                     */
231
-                } elseif (!is_array($value) && strpos($key, '_id') && $value) {
232
-                    $filters[$key] = [
233
-                        'op' => 'in',
234
-                        'val' => explode(',', $value)
235
-                    ];
228
+					/**
229
+					 * Use in operator in case of foreign and comma seperated values.
230
+					 */
231
+				} elseif (!is_array($value) && strpos($key, '_id') && $value) {
232
+					$filters[$key] = [
233
+						'op' => 'in',
234
+						'val' => explode(',', $value)
235
+					];
236 236
 
237
-                    /**
238
-                     * Use null operator in case of 0 value and foreign.
239
-                     */
240
-                } elseif (strpos($key, '_id') && $value == 0) {
241
-                    $filters[$key] = [
242
-                        'op' => 'null'
243
-                    ];
237
+					/**
238
+					 * Use null operator in case of 0 value and foreign.
239
+					 */
240
+				} elseif (strpos($key, '_id') && $value == 0) {
241
+					$filters[$key] = [
242
+						'op' => 'null'
243
+					];
244 244
 
245
-                    /**
246
-                     * Consider values as a sub conditions if it is array.
247
-                     */
248
-                } elseif (is_array($value)) {
249
-                    $filters[$key] = $value;
245
+					/**
246
+					 * Consider values as a sub conditions if it is array.
247
+					 */
248
+				} elseif (is_array($value)) {
249
+					$filters[$key] = $value;
250 250
 
251
-                    /**
252
-                     * Default string filteration.
253
-                     */
254
-                } elseif ($value) {
255
-                    $key = 'LOWER(' . $key . ')';
256
-                    $value = strtolower($value);
257
-                    $filters[$key] = [
258
-                        'op' => 'like',
259
-                        'val' => '%' . $value . '%'
260
-                    ];
261
-                }
262
-            }
263
-        }
251
+					/**
252
+					 * Default string filteration.
253
+					 */
254
+				} elseif ($value) {
255
+					$key = 'LOWER(' . $key . ')';
256
+					$value = strtolower($value);
257
+					$filters[$key] = [
258
+						'op' => 'like',
259
+						'val' => '%' . $value . '%'
260
+					];
261
+				}
262
+			}
263
+		}
264 264
 
265
-        return $filters;
266
-    }
265
+		return $filters;
266
+	}
267 267
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
     {
50 50
         $translatable = $this->repo->model->translatable ?? [];
51 51
         $filters = $this->constructFilters($conditions);
52
-        $sortBy = in_array($sortBy, $translatable) ? $sortBy . '->' . $this->session->get('locale') : $sortBy;
52
+        $sortBy = in_array($sortBy, $translatable) ? $sortBy.'->'.$this->session->get('locale') : $sortBy;
53 53
 
54 54
         if ($trashed) {
55 55
             return $this->deleted(['and' => $filters], $perPage ?? 15, $sortBy ?? 'created_at', $desc ?? true);
@@ -217,18 +217,18 @@  discard block
 block discarded – undo
217 217
                 /**
218 218
                  * Prepare key based on the the requested lang if it was translatable.
219 219
                  */
220
-                $key = in_array($key, $translatable) ? $key . '->' . ($this->session->get('locale') == 'all' ? 'en' : $this->session->get('locale')) : $key;
220
+                $key = in_array($key, $translatable) ? $key.'->'.($this->session->get('locale') == 'all' ? 'en' : $this->session->get('locale')) : $key;
221 221
 
222 222
                 /**
223 223
                  * Convert 0/1 or true/false to boolean in case of not foreign key.
224 224
                  */
225
-                if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null && strpos($key, '_id') === false && !is_null($value)) {
225
+                if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null && strpos($key, '_id') === false && ! is_null($value)) {
226 226
                     $filters[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
227 227
 
228 228
                     /**
229 229
                      * Use in operator in case of foreign and comma seperated values.
230 230
                      */
231
-                } elseif (!is_array($value) && strpos($key, '_id') && $value) {
231
+                } elseif ( ! is_array($value) && strpos($key, '_id') && $value) {
232 232
                     $filters[$key] = [
233 233
                         'op' => 'in',
234 234
                         'val' => explode(',', $value)
@@ -252,11 +252,11 @@  discard block
 block discarded – undo
252 252
                      * Default string filteration.
253 253
                      */
254 254
                 } elseif ($value) {
255
-                    $key = 'LOWER(' . $key . ')';
255
+                    $key = 'LOWER('.$key.')';
256 256
                     $value = strtolower($value);
257 257
                     $filters[$key] = [
258 258
                         'op' => 'like',
259
-                        'val' => '%' . $value . '%'
259
+                        'val' => '%'.$value.'%'
260 260
                     ];
261 261
                 }
262 262
             }
Please login to merge, or discard this patch.
src/Modules/Notifications/Services/NotificationService.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -9,79 +9,79 @@
 block discarded – undo
9 9
 
10 10
 class NotificationService extends BaseService
11 11
 {
12
-    /**
13
-     * @var UserRepository
14
-     */
15
-    protected $userRepository;
12
+	/**
13
+	 * @var UserRepository
14
+	 */
15
+	protected $userRepository;
16 16
 
17
-    /**
18
-     * Init new object.
19
-     *
20
-     * @param   NotificationRepository $repo
21
-     * @param   Session $session
22
-     * @return  void
23
-     */
24
-    public function __construct(NotificationRepository $repo, UserRepository $userRepository, Session $session)
25
-    {
26
-        $this->userRepository = $userRepository;
27
-        parent::__construct($repo, $session);
28
-    }
17
+	/**
18
+	 * Init new object.
19
+	 *
20
+	 * @param   NotificationRepository $repo
21
+	 * @param   Session $session
22
+	 * @return  void
23
+	 */
24
+	public function __construct(NotificationRepository $repo, UserRepository $userRepository, Session $session)
25
+	{
26
+		$this->userRepository = $userRepository;
27
+		parent::__construct($repo, $session);
28
+	}
29 29
 
30
-    /**
31
-     * Retrieve all notifications of the logged in user.
32
-     *
33
-     * @param  integer $perPage
34
-     * @return Collection
35
-     */
36
-    public function my($perPage)
37
-    {
38
-        return $this->repo->my($perPage);
39
-    }
30
+	/**
31
+	 * Retrieve all notifications of the logged in user.
32
+	 *
33
+	 * @param  integer $perPage
34
+	 * @return Collection
35
+	 */
36
+	public function my($perPage)
37
+	{
38
+		return $this->repo->my($perPage);
39
+	}
40 40
 
41
-    /**
42
-     * Retrieve unread notifications of the logged in user.
43
-     *
44
-     * @param  integer $perPage
45
-     * @return Collection
46
-     */
47
-    public function unread($perPage)
48
-    {
49
-        return $this->repo->unread($perPage);
50
-    }
41
+	/**
42
+	 * Retrieve unread notifications of the logged in user.
43
+	 *
44
+	 * @param  integer $perPage
45
+	 * @return Collection
46
+	 */
47
+	public function unread($perPage)
48
+	{
49
+		return $this->repo->unread($perPage);
50
+	}
51 51
 
52
-    /**
53
-     * Mark the notification as read.
54
-     *
55
-     * @param  integer  $id
56
-     * @return object
57
-     */
58
-    public function markAsRead($id)
59
-    {
60
-        return $this->repo->markAsRead($id);
61
-    }
52
+	/**
53
+	 * Mark the notification as read.
54
+	 *
55
+	 * @param  integer  $id
56
+	 * @return object
57
+	 */
58
+	public function markAsRead($id)
59
+	{
60
+		return $this->repo->markAsRead($id);
61
+	}
62 62
 
63
-    /**
64
-     * Mark all notifications as read.
65
-     *
66
-     * @return void
67
-     */
68
-    public function markAllAsRead()
69
-    {
70
-        return $this->repo->markAllAsRead();
71
-    }
63
+	/**
64
+	 * Mark all notifications as read.
65
+	 *
66
+	 * @return void
67
+	 */
68
+	public function markAllAsRead()
69
+	{
70
+		return $this->repo->markAllAsRead();
71
+	}
72 72
 
73
-    /**
74
-     * Notify th given user with the given notification.
75
-     *
76
-     * @param  collection $users
77
-     * @param  string     $notification
78
-     * @param  Variadic   $notificationData
79
-     * @return void
80
-     */
81
-    public function notify($users, $notification, ...$notificationData)
82
-    {
83
-        $users = is_array($users) ? $this->userRepository->findBy(['id' => ['op' => 'in', 'val' => $users]]) : $users;
84
-        $notification = 'App\Modules\Notifications\Notifications\\'.$notification;
85
-        \Notification::send($users, new $notification(...$notificationData));
86
-    }
73
+	/**
74
+	 * Notify th given user with the given notification.
75
+	 *
76
+	 * @param  collection $users
77
+	 * @param  string     $notification
78
+	 * @param  Variadic   $notificationData
79
+	 * @return void
80
+	 */
81
+	public function notify($users, $notification, ...$notificationData)
82
+	{
83
+		$users = is_array($users) ? $this->userRepository->findBy(['id' => ['op' => 'in', 'val' => $users]]) : $users;
84
+		$notification = 'App\Modules\Notifications\Notifications\\'.$notification;
85
+		\Notification::send($users, new $notification(...$notificationData));
86
+	}
87 87
 }
Please login to merge, or discard this patch.
src/Modules/Roles/Services/RoleService.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -8,34 +8,34 @@
 block discarded – undo
8 8
 
9 9
 class RoleService extends BaseService
10 10
 {
11
-    /**
12
-     * Init new object.
13
-     *
14
-     * @param   RoleRepository $repo
15
-     * @param   Session $session
16
-     * @return  void
17
-     */
18
-    public function __construct(RoleRepository $repo, Session $session)
19
-    {
20
-        parent::__construct($repo, $session);
21
-    }
11
+	/**
12
+	 * Init new object.
13
+	 *
14
+	 * @param   RoleRepository $repo
15
+	 * @param   Session $session
16
+	 * @return  void
17
+	 */
18
+	public function __construct(RoleRepository $repo, Session $session)
19
+	{
20
+		parent::__construct($repo, $session);
21
+	}
22 22
 
23
-    /**
24
-     * Assign the given permission ids to the given role.
25
-     *
26
-     * @param  integer $roleId
27
-     * @param  array   $permissionIds
28
-     * @return object
29
-     */
30
-    public function assignPermissions($roleId, $permissionIds)
31
-    {
32
-        $role = false;
33
-        \DB::transaction(function () use ($roleId, $permissionIds, &$role) {
34
-            $role = $this->repo->find($roleId);
35
-            $this->repo->detachPermissions($role);
36
-            $this->repo->attachPermissions($role, $permissionIds);
37
-        });
23
+	/**
24
+	 * Assign the given permission ids to the given role.
25
+	 *
26
+	 * @param  integer $roleId
27
+	 * @param  array   $permissionIds
28
+	 * @return object
29
+	 */
30
+	public function assignPermissions($roleId, $permissionIds)
31
+	{
32
+		$role = false;
33
+		\DB::transaction(function () use ($roleId, $permissionIds, &$role) {
34
+			$role = $this->repo->find($roleId);
35
+			$this->repo->detachPermissions($role);
36
+			$this->repo->attachPermissions($role, $permissionIds);
37
+		});
38 38
 
39
-        return $role;
40
-    }
39
+		return $role;
40
+	}
41 41
 }
Please login to merge, or discard this patch.
src/Modules/Users/Services/UserService.php 2 patches
Indentation   +358 added lines, -358 removed lines patch added patch discarded remove patch
@@ -13,362 +13,362 @@
 block discarded – undo
13 13
 
14 14
 class UserService extends BaseService
15 15
 {
16
-    /**
17
-     * @var PermissionService
18
-     */
19
-    protected $permissionService;
20
-
21
-    /**
22
-     * @var LoginProxy
23
-     */
24
-    protected $loginProxy;
25
-
26
-    /**
27
-     * @var NotificationService
28
-     */
29
-    protected $notificationService;
30
-
31
-    /**
32
-     * @var OauthClientService
33
-     */
34
-    protected $oauthClientService;
35
-
36
-    /**
37
-     * Init new object.
38
-     *
39
-     * @param   UserRepository       $repo
40
-     * @param   PermissionService    $permissionService
41
-     * @param   LoginProxy           $loginProxy
42
-     * @param   NotificationService  $notificationService
43
-     * @param   OauthClientService   $oauthClientService
44
-     * @param   Session $session
45
-     * @return  void
46
-     */
47
-    public function __construct(
48
-        UserRepository $repo,
49
-        PermissionService $permissionService,
50
-        LoginProxy $loginProxy,
51
-        NotificationService $notificationService,
52
-        OauthClientService $oauthClientService,
53
-        Session $session
54
-    ) {
55
-        $this->permissionService   = $permissionService;
56
-        $this->loginProxy          = $loginProxy;
57
-        $this->notificationService = $notificationService;
58
-        $this->oauthClientService  = $oauthClientService;
59
-        parent::__construct($repo, $session);
60
-    }
61
-
62
-    /**
63
-     * Return the logged in user account.
64
-     *
65
-     * @param  array   $relations
66
-     * @return boolean
67
-     */
68
-    public function account($relations = ['roles.permissions'])
69
-    {
70
-        $permissions = [];
71
-        $user        = $this->repo->find(\Auth::id(), $relations);
72
-        foreach ($user->roles as $role) {
73
-            $role->permissions->each(function ($permission) use (&$permissions) {
74
-                $permissions[] = $permission;
75
-            });
76
-        }
77
-        $user->permissions = $permissions;
78
-
79
-        return $user;
80
-    }
81
-
82
-    /**
83
-     * Check if the logged in user or the given user
84
-     * has the given permissions on the given model.
85
-     *
86
-     * @param  string $permissionName
87
-     * @param  string $model
88
-     * @param  mixed  $userId
89
-     * @return boolean
90
-     */
91
-    public function can($permissionName, $model, $userId = false)
92
-    {
93
-        $permission = $this->permissionService->first([
94
-            'and' => [
95
-                'model' => $model,
96
-                'name'  => $permissionName,
97
-                'roles' => [
98
-                    'op' => 'has',
99
-                    'val' => [
100
-                        'users' => [
101
-                            'op' => 'has',
102
-                            'val' => [
103
-                                'users.id' => $userId ?: \Auth::id()
104
-                            ]
105
-                        ]
106
-                    ]
107
-                ]
108
-            ]
109
-        ]);
110
-
111
-        return $permission ? true : false;
112
-    }
113
-
114
-    /**
115
-     * Check if the logged in or the given user has the given role.
116
-     *
117
-     * @param  string[] $roles
118
-     * @param  mixed    $user
119
-     * @return boolean
120
-     */
121
-    public function hasRoles($roles, $user = false)
122
-    {
123
-        return $this->repo->countRoles($user ?: \Auth::id(), $roles) ? true : false;
124
-    }
125
-
126
-    /**
127
-     * Assign the given role ids to the given user.
128
-     *
129
-     * @param  integer $userId
130
-     * @param  array   $roleIds
131
-     * @return object
132
-     */
133
-    public function assignRoles($userId, $roleIds)
134
-    {
135
-        $user = false;
136
-        \DB::transaction(function () use ($userId, $roleIds, &$user) {
137
-            $user = $this->repo->find($userId);
138
-            $this->repo->detachRoles($user);
139
-            $this->repo->attachRoles($user, $roleIds);
140
-        });
141
-
142
-        return $user;
143
-    }
144
-
145
-    /**
146
-     * Handle the login request to the application.
147
-     *
148
-     * @param  string  $email
149
-     * @param  string  $password
150
-     * @return object
151
-     */
152
-    public function login($email, $password)
153
-    {
154
-        if (!$user = $this->repo->first(['email' => $email])) {
155
-            \Errors::loginFailed();
156
-        } elseif ($user->blocked) {
157
-            \Errors::userIsBlocked();
158
-        } elseif (!config('user.disable_confirm_email') && !$user->confirmed) {
159
-            \Errors::emailNotConfirmed();
160
-        }
161
-
162
-        return ['user' => $user, 'tokens' => $this->loginProxy->login($user->email, $password)];
163
-    }
164
-
165
-    /**
166
-     * Handle the social login request to the application.
167
-     *
168
-     * @param  string $authCode
169
-     * @param  string $accessToken
170
-     * @return array
171
-     */
172
-    public function loginSocial($authCode, $accessToken, $type)
173
-    {
174
-        $accessToken = $authCode ? Arr::get(\Socialite::driver($type)->getAccessTokenResponse($authCode), 'access_token') : $accessToken;
175
-        $user        = \Socialite::driver($type)->userFromToken($accessToken)->user;
176
-
177
-        if (!Arr::has($user, 'email')) {
178
-            \Errors::noSocialEmail();
179
-        }
180
-
181
-        if (!$this->repo->first(['email' => $user['email']]) && !$this->repo->deleted(['email' => $user['email']])->count()) {
182
-            $this->register(Arr::get($user, 'name'), $user['email'], '', true);
183
-        }
184
-
185
-        return $this->login($user['email'], config('user.social_pass'));
186
-    }
187
-    /**
188
-     * Handle the registration request.
189
-     *
190
-     * @param  array   $data
191
-     * @param  boolean $skipConfirmEmail
192
-     * @param  integer $roleId
193
-     * @return object
194
-     */
195
-    public function register($data, $skipConfirmEmail = false, $roleId = false)
196
-    {
197
-        $data['confirmed'] = $skipConfirmEmail;
198
-
199
-        if ($roleId) {
200
-            $data['roles'] = [['id' => $roleId]];
201
-        }
202
-
203
-        $user = $this->repo->save($data);
204
-
205
-        if (!$skipConfirmEmail && !config('user.disable_confirm_email')) {
206
-            $this->sendConfirmationEmail($user->email);
207
-        }
208
-
209
-        return $user;
210
-    }
211
-
212
-    /**
213
-     * Block the user.
214
-     *
215
-     * @param  integer $userId
216
-     * @return object
217
-     */
218
-    public function block($userId)
219
-    {
220
-        if (\Auth::id() == $userId) {
221
-            \Errors::noPermissions();
222
-        }
223
-
224
-        return $this->repo->save(['id' => $userId, 'blocked' => 1]);
225
-    }
226
-
227
-    /**
228
-     * Unblock the user.
229
-     *
230
-     * @param  integer $userId
231
-     * @return object
232
-     */
233
-    public function unblock($userId)
234
-    {
235
-        return $this->repo->save(['id' => $userId, 'blocked' => 0]);
236
-    }
237
-
238
-    /**
239
-     * Send a reset link to the given user.
240
-     *
241
-     * @param  string  $email
242
-     * @return void
243
-     */
244
-    public function sendReset($email)
245
-    {
246
-        if (!$user = $this->repo->first(['email' => $email])) {
247
-            \Errors::notFound('email');
248
-        }
249
-
250
-        $token = \Password::createToken($user);
251
-        $this->notificationService->notify($user, 'ResetPassword', $token);
252
-    }
253
-
254
-    /**
255
-     * Reset the given user's password.
256
-     *
257
-     * @param   string  $email
258
-     * @param   string  $password
259
-     * @param   string  $passwordConfirmation
260
-     * @param   string  $token
261
-     * @return string|void
262
-     */
263
-    public function resetPassword($email, $password, $passwordConfirmation, $token)
264
-    {
265
-        $response = \Password::reset([
266
-            'email'                 => $email,
267
-            'password'              => $password,
268
-            'password_confirmation' => $passwordConfirmation,
269
-            'token'                 => $token
270
-        ], function ($user, $password) {
271
-            $this->repo->save(['id' => $user->id, 'password' => $password]);
272
-        });
273
-
274
-        switch ($response) {
275
-            case \Password::PASSWORD_RESET:
276
-                return 'success';
277
-                break;
278
-
279
-            case \Password::INVALID_TOKEN:
280
-                \Errors::invalidResetToken();
281
-                break;
282
-
283
-            case \Password::INVALID_PASSWORD:
284
-                \Errors::invalidResetPassword();
285
-                break;
286
-
287
-            case \Password::INVALID_USER:
288
-                \Errors::notFound('user');
289
-                break;
290
-        }
291
-    }
292
-
293
-    /**
294
-     * Change the logged in user password.
295
-     *
296
-     * @param  string  $password
297
-     * @param  string  $oldPassword
298
-     * @return void
299
-     */
300
-    public function changePassword($password, $oldPassword)
301
-    {
302
-        $user = \Auth::user();
303
-        if (!\Hash::check($oldPassword, $user->password)) {
304
-            \Errors::invalidOldPassword();
305
-        }
306
-
307
-        $this->repo->save(['id' => $user->id, 'password' => $password]);
308
-    }
309
-
310
-    /**
311
-     * Confirm email using the confirmation code.
312
-     *
313
-     * @param  string $confirmationCode
314
-     * @return void
315
-     */
316
-    public function confirmEmail($confirmationCode)
317
-    {
318
-        if (!$user = $this->repo->first(['confirmation_code' => $confirmationCode])) {
319
-            \Errors::invalidConfirmationCode();
320
-        }
321
-
322
-        $this->repo->save(['id' => $user->id, 'confirmed' => 1, 'confirmation_code' => null]);
323
-    }
324
-
325
-    /**
326
-     * Send the confirmation mail.
327
-     *
328
-     * @param  string $email
329
-     * @return void
330
-     */
331
-    public function sendConfirmationEmail($email)
332
-    {
333
-        $user = $this->repo->first(['email' => $email]);
334
-        if ($user->confirmed) {
335
-            \Errors::emailAlreadyConfirmed();
336
-        }
337
-
338
-        $this->repo->save(['id' => $user->id, 'confirmation_code' => sha1(microtime())]);
339
-        $this->notificationService->notify($user, 'ConfirmEmail');
340
-    }
341
-
342
-    /**
343
-     * Save the given data to the logged in user.
344
-     *
345
-     * @param  array $data
346
-     * @return void
347
-     */
348
-    public function saveProfile($data)
349
-    {
350
-        $data['id'] = \Auth::id();
351
-        return $this->repo->save($data);
352
-    }
353
-
354
-    /**
355
-     * Logs out the user, revoke access token and refresh token.
356
-     *
357
-     * @return void
358
-     */
359
-    public function logout()
360
-    {
361
-        $this->oauthClientService->revokeAccessToken(\Auth::user()->token());
362
-    }
363
-
364
-    /**
365
-     * Attempt to refresh the access token using the given refresh token.
366
-     *
367
-     * @param  string $refreshToken
368
-     * @return array
369
-     */
370
-    public function refreshToken($refreshToken)
371
-    {
372
-        return $this->loginProxy->refreshToken($refreshToken);
373
-    }
16
+	/**
17
+	 * @var PermissionService
18
+	 */
19
+	protected $permissionService;
20
+
21
+	/**
22
+	 * @var LoginProxy
23
+	 */
24
+	protected $loginProxy;
25
+
26
+	/**
27
+	 * @var NotificationService
28
+	 */
29
+	protected $notificationService;
30
+
31
+	/**
32
+	 * @var OauthClientService
33
+	 */
34
+	protected $oauthClientService;
35
+
36
+	/**
37
+	 * Init new object.
38
+	 *
39
+	 * @param   UserRepository       $repo
40
+	 * @param   PermissionService    $permissionService
41
+	 * @param   LoginProxy           $loginProxy
42
+	 * @param   NotificationService  $notificationService
43
+	 * @param   OauthClientService   $oauthClientService
44
+	 * @param   Session $session
45
+	 * @return  void
46
+	 */
47
+	public function __construct(
48
+		UserRepository $repo,
49
+		PermissionService $permissionService,
50
+		LoginProxy $loginProxy,
51
+		NotificationService $notificationService,
52
+		OauthClientService $oauthClientService,
53
+		Session $session
54
+	) {
55
+		$this->permissionService   = $permissionService;
56
+		$this->loginProxy          = $loginProxy;
57
+		$this->notificationService = $notificationService;
58
+		$this->oauthClientService  = $oauthClientService;
59
+		parent::__construct($repo, $session);
60
+	}
61
+
62
+	/**
63
+	 * Return the logged in user account.
64
+	 *
65
+	 * @param  array   $relations
66
+	 * @return boolean
67
+	 */
68
+	public function account($relations = ['roles.permissions'])
69
+	{
70
+		$permissions = [];
71
+		$user        = $this->repo->find(\Auth::id(), $relations);
72
+		foreach ($user->roles as $role) {
73
+			$role->permissions->each(function ($permission) use (&$permissions) {
74
+				$permissions[] = $permission;
75
+			});
76
+		}
77
+		$user->permissions = $permissions;
78
+
79
+		return $user;
80
+	}
81
+
82
+	/**
83
+	 * Check if the logged in user or the given user
84
+	 * has the given permissions on the given model.
85
+	 *
86
+	 * @param  string $permissionName
87
+	 * @param  string $model
88
+	 * @param  mixed  $userId
89
+	 * @return boolean
90
+	 */
91
+	public function can($permissionName, $model, $userId = false)
92
+	{
93
+		$permission = $this->permissionService->first([
94
+			'and' => [
95
+				'model' => $model,
96
+				'name'  => $permissionName,
97
+				'roles' => [
98
+					'op' => 'has',
99
+					'val' => [
100
+						'users' => [
101
+							'op' => 'has',
102
+							'val' => [
103
+								'users.id' => $userId ?: \Auth::id()
104
+							]
105
+						]
106
+					]
107
+				]
108
+			]
109
+		]);
110
+
111
+		return $permission ? true : false;
112
+	}
113
+
114
+	/**
115
+	 * Check if the logged in or the given user has the given role.
116
+	 *
117
+	 * @param  string[] $roles
118
+	 * @param  mixed    $user
119
+	 * @return boolean
120
+	 */
121
+	public function hasRoles($roles, $user = false)
122
+	{
123
+		return $this->repo->countRoles($user ?: \Auth::id(), $roles) ? true : false;
124
+	}
125
+
126
+	/**
127
+	 * Assign the given role ids to the given user.
128
+	 *
129
+	 * @param  integer $userId
130
+	 * @param  array   $roleIds
131
+	 * @return object
132
+	 */
133
+	public function assignRoles($userId, $roleIds)
134
+	{
135
+		$user = false;
136
+		\DB::transaction(function () use ($userId, $roleIds, &$user) {
137
+			$user = $this->repo->find($userId);
138
+			$this->repo->detachRoles($user);
139
+			$this->repo->attachRoles($user, $roleIds);
140
+		});
141
+
142
+		return $user;
143
+	}
144
+
145
+	/**
146
+	 * Handle the login request to the application.
147
+	 *
148
+	 * @param  string  $email
149
+	 * @param  string  $password
150
+	 * @return object
151
+	 */
152
+	public function login($email, $password)
153
+	{
154
+		if (!$user = $this->repo->first(['email' => $email])) {
155
+			\Errors::loginFailed();
156
+		} elseif ($user->blocked) {
157
+			\Errors::userIsBlocked();
158
+		} elseif (!config('user.disable_confirm_email') && !$user->confirmed) {
159
+			\Errors::emailNotConfirmed();
160
+		}
161
+
162
+		return ['user' => $user, 'tokens' => $this->loginProxy->login($user->email, $password)];
163
+	}
164
+
165
+	/**
166
+	 * Handle the social login request to the application.
167
+	 *
168
+	 * @param  string $authCode
169
+	 * @param  string $accessToken
170
+	 * @return array
171
+	 */
172
+	public function loginSocial($authCode, $accessToken, $type)
173
+	{
174
+		$accessToken = $authCode ? Arr::get(\Socialite::driver($type)->getAccessTokenResponse($authCode), 'access_token') : $accessToken;
175
+		$user        = \Socialite::driver($type)->userFromToken($accessToken)->user;
176
+
177
+		if (!Arr::has($user, 'email')) {
178
+			\Errors::noSocialEmail();
179
+		}
180
+
181
+		if (!$this->repo->first(['email' => $user['email']]) && !$this->repo->deleted(['email' => $user['email']])->count()) {
182
+			$this->register(Arr::get($user, 'name'), $user['email'], '', true);
183
+		}
184
+
185
+		return $this->login($user['email'], config('user.social_pass'));
186
+	}
187
+	/**
188
+	 * Handle the registration request.
189
+	 *
190
+	 * @param  array   $data
191
+	 * @param  boolean $skipConfirmEmail
192
+	 * @param  integer $roleId
193
+	 * @return object
194
+	 */
195
+	public function register($data, $skipConfirmEmail = false, $roleId = false)
196
+	{
197
+		$data['confirmed'] = $skipConfirmEmail;
198
+
199
+		if ($roleId) {
200
+			$data['roles'] = [['id' => $roleId]];
201
+		}
202
+
203
+		$user = $this->repo->save($data);
204
+
205
+		if (!$skipConfirmEmail && !config('user.disable_confirm_email')) {
206
+			$this->sendConfirmationEmail($user->email);
207
+		}
208
+
209
+		return $user;
210
+	}
211
+
212
+	/**
213
+	 * Block the user.
214
+	 *
215
+	 * @param  integer $userId
216
+	 * @return object
217
+	 */
218
+	public function block($userId)
219
+	{
220
+		if (\Auth::id() == $userId) {
221
+			\Errors::noPermissions();
222
+		}
223
+
224
+		return $this->repo->save(['id' => $userId, 'blocked' => 1]);
225
+	}
226
+
227
+	/**
228
+	 * Unblock the user.
229
+	 *
230
+	 * @param  integer $userId
231
+	 * @return object
232
+	 */
233
+	public function unblock($userId)
234
+	{
235
+		return $this->repo->save(['id' => $userId, 'blocked' => 0]);
236
+	}
237
+
238
+	/**
239
+	 * Send a reset link to the given user.
240
+	 *
241
+	 * @param  string  $email
242
+	 * @return void
243
+	 */
244
+	public function sendReset($email)
245
+	{
246
+		if (!$user = $this->repo->first(['email' => $email])) {
247
+			\Errors::notFound('email');
248
+		}
249
+
250
+		$token = \Password::createToken($user);
251
+		$this->notificationService->notify($user, 'ResetPassword', $token);
252
+	}
253
+
254
+	/**
255
+	 * Reset the given user's password.
256
+	 *
257
+	 * @param   string  $email
258
+	 * @param   string  $password
259
+	 * @param   string  $passwordConfirmation
260
+	 * @param   string  $token
261
+	 * @return string|void
262
+	 */
263
+	public function resetPassword($email, $password, $passwordConfirmation, $token)
264
+	{
265
+		$response = \Password::reset([
266
+			'email'                 => $email,
267
+			'password'              => $password,
268
+			'password_confirmation' => $passwordConfirmation,
269
+			'token'                 => $token
270
+		], function ($user, $password) {
271
+			$this->repo->save(['id' => $user->id, 'password' => $password]);
272
+		});
273
+
274
+		switch ($response) {
275
+			case \Password::PASSWORD_RESET:
276
+				return 'success';
277
+				break;
278
+
279
+			case \Password::INVALID_TOKEN:
280
+				\Errors::invalidResetToken();
281
+				break;
282
+
283
+			case \Password::INVALID_PASSWORD:
284
+				\Errors::invalidResetPassword();
285
+				break;
286
+
287
+			case \Password::INVALID_USER:
288
+				\Errors::notFound('user');
289
+				break;
290
+		}
291
+	}
292
+
293
+	/**
294
+	 * Change the logged in user password.
295
+	 *
296
+	 * @param  string  $password
297
+	 * @param  string  $oldPassword
298
+	 * @return void
299
+	 */
300
+	public function changePassword($password, $oldPassword)
301
+	{
302
+		$user = \Auth::user();
303
+		if (!\Hash::check($oldPassword, $user->password)) {
304
+			\Errors::invalidOldPassword();
305
+		}
306
+
307
+		$this->repo->save(['id' => $user->id, 'password' => $password]);
308
+	}
309
+
310
+	/**
311
+	 * Confirm email using the confirmation code.
312
+	 *
313
+	 * @param  string $confirmationCode
314
+	 * @return void
315
+	 */
316
+	public function confirmEmail($confirmationCode)
317
+	{
318
+		if (!$user = $this->repo->first(['confirmation_code' => $confirmationCode])) {
319
+			\Errors::invalidConfirmationCode();
320
+		}
321
+
322
+		$this->repo->save(['id' => $user->id, 'confirmed' => 1, 'confirmation_code' => null]);
323
+	}
324
+
325
+	/**
326
+	 * Send the confirmation mail.
327
+	 *
328
+	 * @param  string $email
329
+	 * @return void
330
+	 */
331
+	public function sendConfirmationEmail($email)
332
+	{
333
+		$user = $this->repo->first(['email' => $email]);
334
+		if ($user->confirmed) {
335
+			\Errors::emailAlreadyConfirmed();
336
+		}
337
+
338
+		$this->repo->save(['id' => $user->id, 'confirmation_code' => sha1(microtime())]);
339
+		$this->notificationService->notify($user, 'ConfirmEmail');
340
+	}
341
+
342
+	/**
343
+	 * Save the given data to the logged in user.
344
+	 *
345
+	 * @param  array $data
346
+	 * @return void
347
+	 */
348
+	public function saveProfile($data)
349
+	{
350
+		$data['id'] = \Auth::id();
351
+		return $this->repo->save($data);
352
+	}
353
+
354
+	/**
355
+	 * Logs out the user, revoke access token and refresh token.
356
+	 *
357
+	 * @return void
358
+	 */
359
+	public function logout()
360
+	{
361
+		$this->oauthClientService->revokeAccessToken(\Auth::user()->token());
362
+	}
363
+
364
+	/**
365
+	 * Attempt to refresh the access token using the given refresh token.
366
+	 *
367
+	 * @param  string $refreshToken
368
+	 * @return array
369
+	 */
370
+	public function refreshToken($refreshToken)
371
+	{
372
+		return $this->loginProxy->refreshToken($refreshToken);
373
+	}
374 374
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
         $permissions = [];
71 71
         $user        = $this->repo->find(\Auth::id(), $relations);
72 72
         foreach ($user->roles as $role) {
73
-            $role->permissions->each(function ($permission) use (&$permissions) {
73
+            $role->permissions->each(function($permission) use (&$permissions) {
74 74
                 $permissions[] = $permission;
75 75
             });
76 76
         }
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
     public function assignRoles($userId, $roleIds)
134 134
     {
135 135
         $user = false;
136
-        \DB::transaction(function () use ($userId, $roleIds, &$user) {
136
+        \DB::transaction(function() use ($userId, $roleIds, &$user) {
137 137
             $user = $this->repo->find($userId);
138 138
             $this->repo->detachRoles($user);
139 139
             $this->repo->attachRoles($user, $roleIds);
@@ -151,11 +151,11 @@  discard block
 block discarded – undo
151 151
      */
152 152
     public function login($email, $password)
153 153
     {
154
-        if (!$user = $this->repo->first(['email' => $email])) {
154
+        if ( ! $user = $this->repo->first(['email' => $email])) {
155 155
             \Errors::loginFailed();
156 156
         } elseif ($user->blocked) {
157 157
             \Errors::userIsBlocked();
158
-        } elseif (!config('user.disable_confirm_email') && !$user->confirmed) {
158
+        } elseif ( ! config('user.disable_confirm_email') && ! $user->confirmed) {
159 159
             \Errors::emailNotConfirmed();
160 160
         }
161 161
 
@@ -174,11 +174,11 @@  discard block
 block discarded – undo
174 174
         $accessToken = $authCode ? Arr::get(\Socialite::driver($type)->getAccessTokenResponse($authCode), 'access_token') : $accessToken;
175 175
         $user        = \Socialite::driver($type)->userFromToken($accessToken)->user;
176 176
 
177
-        if (!Arr::has($user, 'email')) {
177
+        if ( ! Arr::has($user, 'email')) {
178 178
             \Errors::noSocialEmail();
179 179
         }
180 180
 
181
-        if (!$this->repo->first(['email' => $user['email']]) && !$this->repo->deleted(['email' => $user['email']])->count()) {
181
+        if ( ! $this->repo->first(['email' => $user['email']]) && ! $this->repo->deleted(['email' => $user['email']])->count()) {
182 182
             $this->register(Arr::get($user, 'name'), $user['email'], '', true);
183 183
         }
184 184
 
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 
203 203
         $user = $this->repo->save($data);
204 204
 
205
-        if (!$skipConfirmEmail && !config('user.disable_confirm_email')) {
205
+        if ( ! $skipConfirmEmail && ! config('user.disable_confirm_email')) {
206 206
             $this->sendConfirmationEmail($user->email);
207 207
         }
208 208
 
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
      */
244 244
     public function sendReset($email)
245 245
     {
246
-        if (!$user = $this->repo->first(['email' => $email])) {
246
+        if ( ! $user = $this->repo->first(['email' => $email])) {
247 247
             \Errors::notFound('email');
248 248
         }
249 249
 
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
             'password'              => $password,
268 268
             'password_confirmation' => $passwordConfirmation,
269 269
             'token'                 => $token
270
-        ], function ($user, $password) {
270
+        ], function($user, $password) {
271 271
             $this->repo->save(['id' => $user->id, 'password' => $password]);
272 272
         });
273 273
 
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
     public function changePassword($password, $oldPassword)
301 301
     {
302 302
         $user = \Auth::user();
303
-        if (!\Hash::check($oldPassword, $user->password)) {
303
+        if ( ! \Hash::check($oldPassword, $user->password)) {
304 304
             \Errors::invalidOldPassword();
305 305
         }
306 306
 
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
      */
316 316
     public function confirmEmail($confirmationCode)
317 317
     {
318
-        if (!$user = $this->repo->first(['confirmation_code' => $confirmationCode])) {
318
+        if ( ! $user = $this->repo->first(['confirmation_code' => $confirmationCode])) {
319 319
             \Errors::invalidConfirmationCode();
320 320
         }
321 321
 
Please login to merge, or discard this patch.