Completed
Push — master ( 60eb24...8a761d )
by Sherif
01:58
created
src/Modules/Core/BaseClasses/BaseRepository.php 1 patch
Indentation   +563 added lines, -563 removed lines patch added patch discarded remove patch
@@ -8,577 +8,577 @@
 block discarded – undo
8 8
 
9 9
 abstract class BaseRepository implements BaseRepositoryInterface
10 10
 {
11
-    /**
12
-     * @var object
13
-     */
14
-    public $model;
11
+	/**
12
+	 * @var object
13
+	 */
14
+	public $model;
15 15
     
16
-    /**
17
-     * Init new object.
18
-     *
19
-     * @var mixed model
20
-     * @return  void
21
-     */
22
-    public function __construct($model)
23
-    {
24
-        $this->model  = $model;
25
-    }
26
-
27
-    /**
28
-     * Fetch all records with relations from the storage.
29
-     *
30
-     * @param  array   $relations
31
-     * @param  string  $sortBy
32
-     * @param  boolean $desc
33
-     * @param  array   $columns
34
-     * @return collection
35
-     */
36
-    public function all($relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
37
-    {
38
-        $sort = $desc ? 'desc' : 'asc';
39
-        return $this->model->with($relations)->orderBy($sortBy, $sort)->get($columns);
40
-    }
16
+	/**
17
+	 * Init new object.
18
+	 *
19
+	 * @var mixed model
20
+	 * @return  void
21
+	 */
22
+	public function __construct($model)
23
+	{
24
+		$this->model  = $model;
25
+	}
26
+
27
+	/**
28
+	 * Fetch all records with relations from the storage.
29
+	 *
30
+	 * @param  array   $relations
31
+	 * @param  string  $sortBy
32
+	 * @param  boolean $desc
33
+	 * @param  array   $columns
34
+	 * @return collection
35
+	 */
36
+	public function all($relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
37
+	{
38
+		$sort = $desc ? 'desc' : 'asc';
39
+		return $this->model->with($relations)->orderBy($sortBy, $sort)->get($columns);
40
+	}
41 41
     
42
-    /**
43
-     * Fetch all records with relations from storage in pages.
44
-     *
45
-     * @param  integer $perPage
46
-     * @param  array   $relations
47
-     * @param  string  $sortBy
48
-     * @param  boolean $desc
49
-     * @param  array   $columns
50
-     * @return collection
51
-     */
52
-    public function paginate($perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
53
-    {
54
-        $sort = $desc ? 'desc' : 'asc';
55
-        return $this->model->with($relations)->orderBy($sortBy, $sort)->paginate($perPage, $columns);
56
-    }
57
-
58
-    /**
59
-     * Fetch all records with relations based on
60
-     * the given condition from storage in pages.
61
-     *
62
-     * @param  array   $conditions array of conditions
63
-     * @param  integer $perPage
64
-     * @param  array   $relations
65
-     * @param  string  $sortBy
66
-     * @param  boolean $desc
67
-     * @param  array   $columns
68
-     * @return collection
69
-     */
70
-    public function paginateBy($conditions, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
71
-    {
72
-        $conditions = $this->constructConditions($conditions, $this->model);
73
-        $sort       = $desc ? 'desc' : 'asc';
74
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
75
-    }
76
-
77
-    /**
78
-     * Count all records based on the given condition from storage.
79
-     *
80
-     * @param  array   $conditions array of conditions
81
-     * @return collection
82
-     */
83
-    public function count($conditions)
84
-    {
85
-        $conditions = $this->constructConditions($conditions, $this->model);
86
-        return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->count();
87
-    }
42
+	/**
43
+	 * Fetch all records with relations from storage in pages.
44
+	 *
45
+	 * @param  integer $perPage
46
+	 * @param  array   $relations
47
+	 * @param  string  $sortBy
48
+	 * @param  boolean $desc
49
+	 * @param  array   $columns
50
+	 * @return collection
51
+	 */
52
+	public function paginate($perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
53
+	{
54
+		$sort = $desc ? 'desc' : 'asc';
55
+		return $this->model->with($relations)->orderBy($sortBy, $sort)->paginate($perPage, $columns);
56
+	}
57
+
58
+	/**
59
+	 * Fetch all records with relations based on
60
+	 * the given condition from storage in pages.
61
+	 *
62
+	 * @param  array   $conditions array of conditions
63
+	 * @param  integer $perPage
64
+	 * @param  array   $relations
65
+	 * @param  string  $sortBy
66
+	 * @param  boolean $desc
67
+	 * @param  array   $columns
68
+	 * @return collection
69
+	 */
70
+	public function paginateBy($conditions, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
71
+	{
72
+		$conditions = $this->constructConditions($conditions, $this->model);
73
+		$sort       = $desc ? 'desc' : 'asc';
74
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
75
+	}
76
+
77
+	/**
78
+	 * Count all records based on the given condition from storage.
79
+	 *
80
+	 * @param  array   $conditions array of conditions
81
+	 * @return collection
82
+	 */
83
+	public function count($conditions)
84
+	{
85
+		$conditions = $this->constructConditions($conditions, $this->model);
86
+		return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->count();
87
+	}
88 88
     
89
-    /**
90
-     * Save the given model to the storage.
91
-     *
92
-     * @param  array $data
93
-     * @return mixed
94
-     */
95
-    public function save(array $data)
96
-    {
97
-        $local = \Session::get('locale');
98
-        \Session::put('locale', 'all');
99
-        $model      = false;
100
-        $relations  = [];
101
-
102
-        \DB::transaction(function () use (&$model, &$relations, $data) {
89
+	/**
90
+	 * Save the given model to the storage.
91
+	 *
92
+	 * @param  array $data
93
+	 * @return mixed
94
+	 */
95
+	public function save(array $data)
96
+	{
97
+		$local = \Session::get('locale');
98
+		\Session::put('locale', 'all');
99
+		$model      = false;
100
+		$relations  = [];
101
+
102
+		\DB::transaction(function () use (&$model, &$relations, $data) {
103 103
             
104
-            $model     = $this->prepareModel($data);
105
-            $relations = $this->prepareRelations($data, $model);
106
-            $model     = $this->saveModel($model, $relations);
107
-        });
108
-        \Session::put('locale', $local);
104
+			$model     = $this->prepareModel($data);
105
+			$relations = $this->prepareRelations($data, $model);
106
+			$model     = $this->saveModel($model, $relations);
107
+		});
108
+		\Session::put('locale', $local);
109 109
         
110
-        if (count($relations)) {
111
-            $model->load(...array_keys($relations));
112
-        }
113
-
114
-        return $model;
115
-    }
116
-
117
-    /**
118
-     * Delete record from the storage based on the given
119
-     * condition.
120
-     *
121
-     * @param  var $value condition value
122
-     * @param  string $attribute condition column name
123
-     * @return void
124
-     */
125
-    public function delete($value, $attribute = 'id')
126
-    {
127
-        \DB::transaction(function () use ($value, $attribute) {
128
-            $this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
129
-                $model->delete();
130
-            });
131
-        });
132
-    }
110
+		if (count($relations)) {
111
+			$model->load(...array_keys($relations));
112
+		}
113
+
114
+		return $model;
115
+	}
116
+
117
+	/**
118
+	 * Delete record from the storage based on the given
119
+	 * condition.
120
+	 *
121
+	 * @param  var $value condition value
122
+	 * @param  string $attribute condition column name
123
+	 * @return void
124
+	 */
125
+	public function delete($value, $attribute = 'id')
126
+	{
127
+		\DB::transaction(function () use ($value, $attribute) {
128
+			$this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
129
+				$model->delete();
130
+			});
131
+		});
132
+	}
133 133
     
134
-    /**
135
-     * Fetch records from the storage based on the given
136
-     * id.
137
-     *
138
-     * @param  integer $id
139
-     * @param  string[]   $relations
140
-     * @param  array   $columns
141
-     * @return object
142
-     */
143
-    public function find($id, $relations = [], $columns = ['*'])
144
-    {
145
-        return $this->model->with($relations)->find($id, $columns);
146
-    }
134
+	/**
135
+	 * Fetch records from the storage based on the given
136
+	 * id.
137
+	 *
138
+	 * @param  integer $id
139
+	 * @param  string[]   $relations
140
+	 * @param  array   $columns
141
+	 * @return object
142
+	 */
143
+	public function find($id, $relations = [], $columns = ['*'])
144
+	{
145
+		return $this->model->with($relations)->find($id, $columns);
146
+	}
147 147
     
148
-    /**
149
-     * Fetch records from the storage based on the given
150
-     * condition.
151
-     *
152
-     * @param  array   $conditions array of conditions
153
-     * @param  array   $relations
154
-     * @param  string  $sortBy
155
-     * @param  boolean $desc
156
-     * @param  array   $columns
157
-     * @return collection
158
-     */
159
-    public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
160
-    {
161
-        $conditions = $this->constructConditions($conditions, $this->model);
162
-        $sort       = $desc ? 'desc' : 'asc';
163
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
164
-    }
165
-
166
-    /**
167
-     * Fetch the first record from the storage based on the given
168
-     * condition.
169
-     *
170
-     * @param  array   $conditions array of conditions
171
-     * @param  array   $relations
172
-     * @param  array   $columns
173
-     * @return object
174
-     */
175
-    public function first($conditions, $relations = [], $columns = ['*'])
176
-    {
177
-        $conditions = $this->constructConditions($conditions, $this->model);
178
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
179
-    }
180
-
181
-    /**
182
-     * Return the deleted models in pages based on the given conditions.
183
-     *
184
-     * @param  array   $conditions array of conditions
185
-     * @param  integer $perPage
186
-     * @param  string  $sortBy
187
-     * @param  boolean $desc
188
-     * @param  array   $columns
189
-     * @return collection
190
-     */
191
-    public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = ['*'])
192
-    {
193
-        unset($conditions['page']);
194
-        unset($conditions['perPage']);
195
-        unset($conditions['sortBy']);
196
-        unset($conditions['sort']);
197
-        $conditions = $this->constructConditions($conditions, $this->model);
198
-        $sort       = $desc ? 'desc' : 'asc';
199
-        $model      = $this->model->onlyTrashed();
200
-
201
-        if (count($conditions['conditionValues'])) {
202
-            $model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
203
-        }
204
-
205
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
206
-    }
207
-
208
-    /**
209
-     * Restore the deleted model.
210
-     *
211
-     * @param  integer $id
212
-     * @return void
213
-     */
214
-    public function restore($id)
215
-    {
216
-        $model = $this->model->onlyTrashed()->find($id);
217
-
218
-        if (! $model) {
219
-            \Errors::notFound(class_basename($this->model).' with id : '.$id);
220
-        }
221
-
222
-        $model->restore();
223
-    }
224
-
225
-    /**
226
-     * Fill the model with the given data.
227
-     *
228
-     * @param   array  $data
229
-     *
230
-     * @return  object
231
-     */
232
-    public function prepareModel($data)
233
-    {
234
-        $modelClass = $this->model;
235
-
236
-        /**
237
-         * If the id is present in the data then select the model for updating,
238
-         * else create new model.
239
-         * @var array
240
-         */
241
-        $model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
242
-        if (! $model) {
243
-            \Errors::notFound(class_basename($modelClass).' with id : '.$data['id']);
244
-        }
245
-
246
-        /**
247
-         * Construct the model object with the given data,
248
-         * and if there is a relation add it to relations array,
249
-         * then save the model.
250
-         */
251
-        foreach ($data as $key => $value) {
252
-            if (array_search($key, $model->getFillable(), true) !== false) {
253
-                /**
254
-                 * If the attribute isn't a relation and prevent attributes not in the fillable.
255
-                 */
256
-                $model->$key = $value;
257
-            }
258
-        }
259
-
260
-        return $model;
261
-    }
148
+	/**
149
+	 * Fetch records from the storage based on the given
150
+	 * condition.
151
+	 *
152
+	 * @param  array   $conditions array of conditions
153
+	 * @param  array   $relations
154
+	 * @param  string  $sortBy
155
+	 * @param  boolean $desc
156
+	 * @param  array   $columns
157
+	 * @return collection
158
+	 */
159
+	public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
160
+	{
161
+		$conditions = $this->constructConditions($conditions, $this->model);
162
+		$sort       = $desc ? 'desc' : 'asc';
163
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
164
+	}
165
+
166
+	/**
167
+	 * Fetch the first record from the storage based on the given
168
+	 * condition.
169
+	 *
170
+	 * @param  array   $conditions array of conditions
171
+	 * @param  array   $relations
172
+	 * @param  array   $columns
173
+	 * @return object
174
+	 */
175
+	public function first($conditions, $relations = [], $columns = ['*'])
176
+	{
177
+		$conditions = $this->constructConditions($conditions, $this->model);
178
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
179
+	}
180
+
181
+	/**
182
+	 * Return the deleted models in pages based on the given conditions.
183
+	 *
184
+	 * @param  array   $conditions array of conditions
185
+	 * @param  integer $perPage
186
+	 * @param  string  $sortBy
187
+	 * @param  boolean $desc
188
+	 * @param  array   $columns
189
+	 * @return collection
190
+	 */
191
+	public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = ['*'])
192
+	{
193
+		unset($conditions['page']);
194
+		unset($conditions['perPage']);
195
+		unset($conditions['sortBy']);
196
+		unset($conditions['sort']);
197
+		$conditions = $this->constructConditions($conditions, $this->model);
198
+		$sort       = $desc ? 'desc' : 'asc';
199
+		$model      = $this->model->onlyTrashed();
200
+
201
+		if (count($conditions['conditionValues'])) {
202
+			$model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
203
+		}
204
+
205
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
206
+	}
207
+
208
+	/**
209
+	 * Restore the deleted model.
210
+	 *
211
+	 * @param  integer $id
212
+	 * @return void
213
+	 */
214
+	public function restore($id)
215
+	{
216
+		$model = $this->model->onlyTrashed()->find($id);
217
+
218
+		if (! $model) {
219
+			\Errors::notFound(class_basename($this->model).' with id : '.$id);
220
+		}
221
+
222
+		$model->restore();
223
+	}
224
+
225
+	/**
226
+	 * Fill the model with the given data.
227
+	 *
228
+	 * @param   array  $data
229
+	 *
230
+	 * @return  object
231
+	 */
232
+	public function prepareModel($data)
233
+	{
234
+		$modelClass = $this->model;
235
+
236
+		/**
237
+		 * If the id is present in the data then select the model for updating,
238
+		 * else create new model.
239
+		 * @var array
240
+		 */
241
+		$model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
242
+		if (! $model) {
243
+			\Errors::notFound(class_basename($modelClass).' with id : '.$data['id']);
244
+		}
245
+
246
+		/**
247
+		 * Construct the model object with the given data,
248
+		 * and if there is a relation add it to relations array,
249
+		 * then save the model.
250
+		 */
251
+		foreach ($data as $key => $value) {
252
+			if (array_search($key, $model->getFillable(), true) !== false) {
253
+				/**
254
+				 * If the attribute isn't a relation and prevent attributes not in the fillable.
255
+				 */
256
+				$model->$key = $value;
257
+			}
258
+		}
259
+
260
+		return $model;
261
+	}
262 262
     
263
-    /**
264
-     * Prepare related models based on the given data for the given model.
265
-     *
266
-     * @param   array  $data
267
-     * @param   object $model
268
-     *
269
-     * @return  array
270
-     */
271
-    public function prepareRelations($data, $model)
272
-    {
273
-        /**
274
-         * Init the relation array
275
-         *
276
-         * @var array
277
-         */
278
-        $relations = [];
279
-
280
-        /**
281
-         * Construct the model object with the given data,
282
-         * and if there is a relation add it to relations array,
283
-         * then save the model.
284
-         */
285
-        foreach ($data as $key => $value) {
286
-            /**
287
-             * If the attribute is a relation.
288
-             */
289
-            $relation = \Str::camel($key);
290
-            if (method_exists($model, $relation) && \Core::$relation()) {
291
-                /**
292
-                 * Check if the relation is a collection.
293
-                 */
294
-                if (class_basename($model->$relation) == 'Collection') {
295
-                    /**
296
-                     * If the relation has no value then marke the relation data
297
-                     * related to the model to be deleted.
298
-                     */
299
-                    if (! $value || ! count($value)) {
300
-                        $relations[$relation] = 'delete';
301
-                    }
302
-                }
303
-                if (is_array($value)) {
304
-                    /**
305
-                     * Loop through the relation data.
306
-                     */
307
-                    foreach ($value as $attr => $val) {
308
-                        /**
309
-                         * Get the relation model.
310
-                         */
311
-                        $relationBaseModel = \Core::$relation()->model;
312
-
313
-                        /**
314
-                         * Check if the relation is a collection.
315
-                         */
316
-                        if (class_basename($model->$relation) == 'Collection') {
317
-                            if (! is_array($val)) {
318
-                                $relationModel = $relationBaseModel->lockForUpdate()->find($val);
319
-                            } else {
320
-                                /**
321
-                                 * If the id is present in the data then select the relation model for updating,
322
-                                 * else create new model.
323
-                                 */
324
-                                $relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
325
-                            }
326
-
327
-                            /**
328
-                             * If model doesn't exists.
329
-                             */
330
-                            if (! $relationModel) {
331
-                                \Errors::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
332
-                            }
333
-
334
-                            if (is_array($val)) {
335
-                                /**
336
-                                 * Loop through the relation attributes.
337
-                                 */
338
-                                foreach ($val as $attr => $val) {
339
-                                    /**
340
-                                     * Prevent the sub relations or attributes not in the fillable.
341
-                                     */
342
-                                    if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false) {
343
-                                        $relationModel->$attr = $val;
344
-                                    } elseif (gettype($val) !== 'object' && gettype($val) !== 'array' && $attr !== 'id') {
345
-                                        $extra[$attr] = $val;
346
-                                    }
347
-                                }
348
-                            }
349
-
350
-                            if (isset($extra)) {
351
-                                $relationModel->extra = $extra;
352
-                            }
353
-                            $relations[$relation][] = $relationModel;
354
-                        } else {
355
-                            /**
356
-                             * Prevent the sub relations.
357
-                             */
358
-                            if (gettype($val) !== 'object' && gettype($val) !== 'array') {
359
-                                /**
360
-                                 * If the id is present in the data then select the relation model for updating,
361
-                                 * else create new model.
362
-                                 */
363
-                                $relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
364
-
365
-                                /**
366
-                                 * If model doesn't exists.
367
-                                 */
368
-                                if (! $relationModel) {
369
-                                    \Errors::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
370
-                                }
371
-
372
-                                foreach ($value as $relationAttribute => $relationValue) {
373
-                                    /**
374
-                                     * Prevent attributes not in the fillable.
375
-                                     */
376
-                                    if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
377
-                                        $relationModel->$relationAttribute = $relationValue;
378
-                                    }
379
-                                }
380
-
381
-                                $relations[$relation] = $relationModel;
382
-                            }
383
-                        }
384
-                    }
385
-                }
386
-            }
387
-        }
388
-
389
-        return $relations;
390
-    }
391
-
392
-    /**
393
-     * Save the model with related models.
394
-     *
395
-     * @param   object  $model
396
-     * @param   array   $relations
397
-     *
398
-     * @return  object
399
-     */
400
-    public function saveModel($model, $relations)
401
-    {
402
-
403
-        /**
404
-         * Loop through the relations array.
405
-         */
406
-        foreach ($relations as $key => $value) {
407
-            /**
408
-             * If the relation is marked for delete then delete it.
409
-             */
410
-            if ($value == 'delete' && $model->$key()->count()) {
411
-                $model->$key()->delete();
412
-            } elseif (gettype($value) == 'array') {
413
-                /**
414
-                 * Save the model.
415
-                 */
416
-                $model->save();
417
-                $ids = [];
418
-
419
-                /**
420
-                 * Loop through the relations.
421
-                 */
422
-                foreach ($value as $val) {
423
-                    switch (class_basename($model->$key())) {
424
-                        /**
425
-                         * If the relation is one to many then update it's foreign key with
426
-                         * the model id and save it then add its id to ids array to delete all
427
-                         * relations who's id isn't in the ids array.
428
-                         */
429
-                        case 'HasMany':
430
-                            $foreignKeyName       = $model->$key()->getForeignKeyName();
431
-                            $val->$foreignKeyName = $model->id;
432
-                            $val->save();
433
-                            $ids[] = $val->id;
434
-                            break;
435
-
436
-                        /**
437
-                         * If the relation is many to many then add it's id to the ids array to
438
-                         * attache these ids to the model.
439
-                         */
440
-                        case 'BelongsToMany':
441
-                            $extra = $val->extra;
442
-                            unset($val->extra);
443
-                            $val->save();
444
-                            $ids[$val->id] = $extra ?? [];
445
-                            break;
446
-                    }
447
-                }
448
-                switch (class_basename($model->$key())) {
449
-                    /**
450
-                     * If the relation is one to many then delete all
451
-                     * relations who's id isn't in the ids array.
452
-                     */
453
-                    case 'HasMany':
454
-                        $model->$key()->whereNotIn('id', $ids)->delete();
455
-                        break;
456
-
457
-                    /**
458
-                     * If the relation is many to many then
459
-                     * detach the previous data and attach
460
-                     * the ids array to the model.
461
-                     */
462
-                    case 'BelongsToMany':
463
-                        $model->$key()->detach();
464
-                        $model->$key()->attach($ids);
465
-                        break;
466
-                }
467
-            } else {
468
-                switch (class_basename($model->$key())) {
469
-                    /**
470
-                     * If the relation is one to one.
471
-                     */
472
-                    case 'HasOne':
473
-                        /**
474
-                         * Save the model.
475
-                         */
476
-                        $model->save();
477
-                        $foreignKeyName         = $model->$key()->getForeignKeyName();
478
-                        $value->$foreignKeyName = $model->id;
479
-                        $value->save();
480
-                        break;
481
-                    case 'BelongsTo':
482
-                        /**
483
-                         * Save the model.
484
-                         */
485
-                        $value->save();
486
-                        $model->$key()->associate($value);
487
-                        break;
488
-                }
489
-            }
490
-        }
491
-
492
-        /**
493
-         * Save the model.
494
-         */
495
-        $model->save();
496
-
497
-        return $model;
498
-    }
499
-
500
-    /**
501
-     * Build the conditions recursively for the retrieving methods.
502
-     * @param  array $conditions
503
-     * @return array
504
-     */
505
-    protected function constructConditions($conditions, $model)
506
-    {
507
-        $conditionString = '';
508
-        $conditionValues = [];
509
-        foreach ($conditions as $key => $value) {
510
-            if (Str::contains($key, '->')) {
511
-                $key = $this->wrapJsonSelector($key);
512
-            }
513
-
514
-            if ($key == 'and') {
515
-                $conditions       = $this->constructConditions($value, $model);
516
-                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
517
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
518
-            } elseif ($key == 'or') {
519
-                $conditions       = $this->constructConditions($value, $model);
520
-                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
521
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
522
-            } else {
523
-                if (is_array($value)) {
524
-                    $operator = $value['op'];
525
-                    if (strtolower($operator) == 'between') {
526
-                        $value1 = $value['val1'];
527
-                        $value2 = $value['val2'];
528
-                    } else {
529
-                        $value = Arr::get($value, 'val', '');
530
-                    }
531
-                } else {
532
-                    $operator = '=';
533
-                }
263
+	/**
264
+	 * Prepare related models based on the given data for the given model.
265
+	 *
266
+	 * @param   array  $data
267
+	 * @param   object $model
268
+	 *
269
+	 * @return  array
270
+	 */
271
+	public function prepareRelations($data, $model)
272
+	{
273
+		/**
274
+		 * Init the relation array
275
+		 *
276
+		 * @var array
277
+		 */
278
+		$relations = [];
279
+
280
+		/**
281
+		 * Construct the model object with the given data,
282
+		 * and if there is a relation add it to relations array,
283
+		 * then save the model.
284
+		 */
285
+		foreach ($data as $key => $value) {
286
+			/**
287
+			 * If the attribute is a relation.
288
+			 */
289
+			$relation = \Str::camel($key);
290
+			if (method_exists($model, $relation) && \Core::$relation()) {
291
+				/**
292
+				 * Check if the relation is a collection.
293
+				 */
294
+				if (class_basename($model->$relation) == 'Collection') {
295
+					/**
296
+					 * If the relation has no value then marke the relation data
297
+					 * related to the model to be deleted.
298
+					 */
299
+					if (! $value || ! count($value)) {
300
+						$relations[$relation] = 'delete';
301
+					}
302
+				}
303
+				if (is_array($value)) {
304
+					/**
305
+					 * Loop through the relation data.
306
+					 */
307
+					foreach ($value as $attr => $val) {
308
+						/**
309
+						 * Get the relation model.
310
+						 */
311
+						$relationBaseModel = \Core::$relation()->model;
312
+
313
+						/**
314
+						 * Check if the relation is a collection.
315
+						 */
316
+						if (class_basename($model->$relation) == 'Collection') {
317
+							if (! is_array($val)) {
318
+								$relationModel = $relationBaseModel->lockForUpdate()->find($val);
319
+							} else {
320
+								/**
321
+								 * If the id is present in the data then select the relation model for updating,
322
+								 * else create new model.
323
+								 */
324
+								$relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
325
+							}
326
+
327
+							/**
328
+							 * If model doesn't exists.
329
+							 */
330
+							if (! $relationModel) {
331
+								\Errors::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
332
+							}
333
+
334
+							if (is_array($val)) {
335
+								/**
336
+								 * Loop through the relation attributes.
337
+								 */
338
+								foreach ($val as $attr => $val) {
339
+									/**
340
+									 * Prevent the sub relations or attributes not in the fillable.
341
+									 */
342
+									if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false) {
343
+										$relationModel->$attr = $val;
344
+									} elseif (gettype($val) !== 'object' && gettype($val) !== 'array' && $attr !== 'id') {
345
+										$extra[$attr] = $val;
346
+									}
347
+								}
348
+							}
349
+
350
+							if (isset($extra)) {
351
+								$relationModel->extra = $extra;
352
+							}
353
+							$relations[$relation][] = $relationModel;
354
+						} else {
355
+							/**
356
+							 * Prevent the sub relations.
357
+							 */
358
+							if (gettype($val) !== 'object' && gettype($val) !== 'array') {
359
+								/**
360
+								 * If the id is present in the data then select the relation model for updating,
361
+								 * else create new model.
362
+								 */
363
+								$relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
364
+
365
+								/**
366
+								 * If model doesn't exists.
367
+								 */
368
+								if (! $relationModel) {
369
+									\Errors::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
370
+								}
371
+
372
+								foreach ($value as $relationAttribute => $relationValue) {
373
+									/**
374
+									 * Prevent attributes not in the fillable.
375
+									 */
376
+									if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
377
+										$relationModel->$relationAttribute = $relationValue;
378
+									}
379
+								}
380
+
381
+								$relations[$relation] = $relationModel;
382
+							}
383
+						}
384
+					}
385
+				}
386
+			}
387
+		}
388
+
389
+		return $relations;
390
+	}
391
+
392
+	/**
393
+	 * Save the model with related models.
394
+	 *
395
+	 * @param   object  $model
396
+	 * @param   array   $relations
397
+	 *
398
+	 * @return  object
399
+	 */
400
+	public function saveModel($model, $relations)
401
+	{
402
+
403
+		/**
404
+		 * Loop through the relations array.
405
+		 */
406
+		foreach ($relations as $key => $value) {
407
+			/**
408
+			 * If the relation is marked for delete then delete it.
409
+			 */
410
+			if ($value == 'delete' && $model->$key()->count()) {
411
+				$model->$key()->delete();
412
+			} elseif (gettype($value) == 'array') {
413
+				/**
414
+				 * Save the model.
415
+				 */
416
+				$model->save();
417
+				$ids = [];
418
+
419
+				/**
420
+				 * Loop through the relations.
421
+				 */
422
+				foreach ($value as $val) {
423
+					switch (class_basename($model->$key())) {
424
+						/**
425
+						 * If the relation is one to many then update it's foreign key with
426
+						 * the model id and save it then add its id to ids array to delete all
427
+						 * relations who's id isn't in the ids array.
428
+						 */
429
+						case 'HasMany':
430
+							$foreignKeyName       = $model->$key()->getForeignKeyName();
431
+							$val->$foreignKeyName = $model->id;
432
+							$val->save();
433
+							$ids[] = $val->id;
434
+							break;
435
+
436
+						/**
437
+						 * If the relation is many to many then add it's id to the ids array to
438
+						 * attache these ids to the model.
439
+						 */
440
+						case 'BelongsToMany':
441
+							$extra = $val->extra;
442
+							unset($val->extra);
443
+							$val->save();
444
+							$ids[$val->id] = $extra ?? [];
445
+							break;
446
+					}
447
+				}
448
+				switch (class_basename($model->$key())) {
449
+					/**
450
+					 * If the relation is one to many then delete all
451
+					 * relations who's id isn't in the ids array.
452
+					 */
453
+					case 'HasMany':
454
+						$model->$key()->whereNotIn('id', $ids)->delete();
455
+						break;
456
+
457
+					/**
458
+					 * If the relation is many to many then
459
+					 * detach the previous data and attach
460
+					 * the ids array to the model.
461
+					 */
462
+					case 'BelongsToMany':
463
+						$model->$key()->detach();
464
+						$model->$key()->attach($ids);
465
+						break;
466
+				}
467
+			} else {
468
+				switch (class_basename($model->$key())) {
469
+					/**
470
+					 * If the relation is one to one.
471
+					 */
472
+					case 'HasOne':
473
+						/**
474
+						 * Save the model.
475
+						 */
476
+						$model->save();
477
+						$foreignKeyName         = $model->$key()->getForeignKeyName();
478
+						$value->$foreignKeyName = $model->id;
479
+						$value->save();
480
+						break;
481
+					case 'BelongsTo':
482
+						/**
483
+						 * Save the model.
484
+						 */
485
+						$value->save();
486
+						$model->$key()->associate($value);
487
+						break;
488
+				}
489
+			}
490
+		}
491
+
492
+		/**
493
+		 * Save the model.
494
+		 */
495
+		$model->save();
496
+
497
+		return $model;
498
+	}
499
+
500
+	/**
501
+	 * Build the conditions recursively for the retrieving methods.
502
+	 * @param  array $conditions
503
+	 * @return array
504
+	 */
505
+	protected function constructConditions($conditions, $model)
506
+	{
507
+		$conditionString = '';
508
+		$conditionValues = [];
509
+		foreach ($conditions as $key => $value) {
510
+			if (Str::contains($key, '->')) {
511
+				$key = $this->wrapJsonSelector($key);
512
+			}
513
+
514
+			if ($key == 'and') {
515
+				$conditions       = $this->constructConditions($value, $model);
516
+				$conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
517
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
518
+			} elseif ($key == 'or') {
519
+				$conditions       = $this->constructConditions($value, $model);
520
+				$conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
521
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
522
+			} else {
523
+				if (is_array($value)) {
524
+					$operator = $value['op'];
525
+					if (strtolower($operator) == 'between') {
526
+						$value1 = $value['val1'];
527
+						$value2 = $value['val2'];
528
+					} else {
529
+						$value = Arr::get($value, 'val', '');
530
+					}
531
+				} else {
532
+					$operator = '=';
533
+				}
534 534
                 
535
-                if (strtolower($operator) == 'between') {
536
-                    $conditionString  .= $key.' >= ? and ';
537
-                    $conditionValues[] = $value1;
538
-
539
-                    $conditionString  .= $key.' <= ? {op} ';
540
-                    $conditionValues[] = $value2;
541
-                } elseif (strtolower($operator) == 'in') {
542
-                    $conditionValues  = array_merge($conditionValues, $value);
543
-                    $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
544
-                    $conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
545
-                } elseif (strtolower($operator) == 'null') {
546
-                    $conditionString .= $key.' is null {op} ';
547
-                } elseif (strtolower($operator) == 'not null') {
548
-                    $conditionString .= $key.' is not null {op} ';
549
-                } elseif (strtolower($operator) == 'has') {
550
-                    $sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
551
-                    $bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
552
-                    $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
553
-                    $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
554
-                    $conditionValues  = array_merge($conditionValues, $bindings);
555
-                    $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
556
-                } else {
557
-                    $conditionString  .= $key.' '.$operator.' ? {op} ';
558
-                    $conditionValues[] = $value;
559
-                }
560
-            }
561
-        }
562
-        $conditionString = '('.rtrim($conditionString, '{op} ').')';
563
-        return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
564
-    }
565
-
566
-    /**
567
-     * Wrap the given JSON selector.
568
-     *
569
-     * @param  string  $value
570
-     * @return string
571
-     */
572
-    protected function wrapJsonSelector($value)
573
-    {
574
-        $removeLast = strpos($value, ')');
575
-        $value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
576
-        $path       = explode('->', $value);
577
-        $field      = array_shift($path);
578
-        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
579
-            return '"'.$part.'"';
580
-        })->implode('.'));
535
+				if (strtolower($operator) == 'between') {
536
+					$conditionString  .= $key.' >= ? and ';
537
+					$conditionValues[] = $value1;
538
+
539
+					$conditionString  .= $key.' <= ? {op} ';
540
+					$conditionValues[] = $value2;
541
+				} elseif (strtolower($operator) == 'in') {
542
+					$conditionValues  = array_merge($conditionValues, $value);
543
+					$inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
544
+					$conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
545
+				} elseif (strtolower($operator) == 'null') {
546
+					$conditionString .= $key.' is null {op} ';
547
+				} elseif (strtolower($operator) == 'not null') {
548
+					$conditionString .= $key.' is not null {op} ';
549
+				} elseif (strtolower($operator) == 'has') {
550
+					$sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
551
+					$bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
552
+					$conditions       = $this->constructConditions($value, $model->$key()->getRelated());
553
+					$conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
554
+					$conditionValues  = array_merge($conditionValues, $bindings);
555
+					$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
556
+				} else {
557
+					$conditionString  .= $key.' '.$operator.' ? {op} ';
558
+					$conditionValues[] = $value;
559
+				}
560
+			}
561
+		}
562
+		$conditionString = '('.rtrim($conditionString, '{op} ').')';
563
+		return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
564
+	}
565
+
566
+	/**
567
+	 * Wrap the given JSON selector.
568
+	 *
569
+	 * @param  string  $value
570
+	 * @return string
571
+	 */
572
+	protected function wrapJsonSelector($value)
573
+	{
574
+		$removeLast = strpos($value, ')');
575
+		$value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
576
+		$path       = explode('->', $value);
577
+		$field      = array_shift($path);
578
+		$result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
579
+			return '"'.$part.'"';
580
+		})->implode('.'));
581 581
         
582
-        return $removeLast === false ? $result : $result.')';
583
-    }
582
+		return $removeLast === false ? $result : $result.')';
583
+	}
584 584
 }
Please login to merge, or discard this patch.
src/Modules/Core/Console/Commands/Stubs/Module/Resources/Lang/ar/errors.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -2,8 +2,8 @@
 block discarded – undo
2 2
 
3 3
 return [
4 4
     
5
-    /**
6
-     * Here goes your error messages.
7
-     */
5
+	/**
6
+	 * Here goes your error messages.
7
+	 */
8 8
 
9 9
 ];
Please login to merge, or discard this patch.
src/Modules/Core/Console/Commands/Stubs/Module/Resources/Lang/en/errors.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -2,8 +2,8 @@
 block discarded – undo
2 2
 
3 3
 return [
4 4
     
5
-    /**
6
-     * Here goes your error messages.
7
-     */
5
+	/**
6
+	 * Here goes your error messages.
7
+	 */
8 8
 
9 9
 ];
Please login to merge, or discard this patch.
src/Modules/Core/Console/Commands/MakeModuleCommand.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -10,244 +10,244 @@
 block discarded – undo
10 10
 
11 11
 class MakeModuleCommand extends Command
12 12
 {
13
-    /**
14
-     * The name and signature of the console command.
15
-     *
16
-     * @var string
17
-     */
18
-    protected $signature = 'generate:module
13
+	/**
14
+	 * The name and signature of the console command.
15
+	 *
16
+	 * @var string
17
+	 */
18
+	protected $signature = 'generate:module
19 19
         {slug : The slug of the module}';
20 20
 
21
-    /**
22
-     * The console command description.
23
-     *
24
-     * @var string
25
-     */
26
-    protected $description = 'Create a new module';
27
-
28
-    /**
29
-     * The modules instance.
30
-     *
31
-     * @var RepositoryManager
32
-     */
33
-    protected $module;
34
-
35
-    /**
36
-     * The filesystem instance.
37
-     *
38
-     * @var Filesystem
39
-     */
40
-    protected $files;
41
-
42
-    /**
43
-     * Array to store the configuration details.
44
-     *
45
-     * @var array
46
-     */
47
-    protected $container;
48
-
49
-    /**
50
-     * Array of folder mappings.
51
-     *
52
-     * @var Array
53
-     */
54
-    protected $mapping = [
55
-        'Database/Factories'  => 'Database/Factories',
56
-        'Database/Migrations' => 'Database/Migrations',
57
-        'Database/Seeds'      => 'Database/Seeds',
58
-        'Http/Controllers'    => 'Http/Controllers',
59
-        'Http/Requests'       => 'Http/Requests',
60
-        'Http/Resources'      => 'Http/Resources',
61
-        'ModelObservers'      => 'ModelObservers',
62
-        'Providers'           => 'Providers',
63
-        'Repositories'        => 'Repositories',
64
-        'Services'            => 'Services',
65
-        'Routes'              => 'Routes',
66
-        'Errors'              => 'Errors',
67
-        'Resources'           => 'Resources',
68
-    ];
69
-
70
-    /**
71
-     * Create a new command instance.
72
-     *
73
-     * @param Filesystem $files
74
-     * @param RepositoryManager $module
75
-     */
76
-    public function __construct(Filesystem $files, RepositoryManager $module)
77
-    {
78
-        parent::__construct();
79
-
80
-        $this->files = $files;
81
-        $this->module = $module;
82
-    }
83
-
84
-    /**
85
-     * Execute the console command.
86
-     *
87
-     * @return mixed
88
-     */
89
-    public function handle()
90
-    {
91
-        $this->container['slug']        = Str::slug($this->argument('slug'));
92
-        $this->container['name']        = Str::studly($this->container['slug']);
93
-        $this->container['version']     = '1.0';
94
-        $this->container['description'] = 'This is the description for the ' . $this->container['name'] . ' module.';
95
-        $this->container['location']    = config('modules.default_location');
96
-        $this->container['provider']    = config("modules.locations.{$this->container['location']}.provider");
97
-        $this->container['basename']    = Str::studly($this->container['slug']);
98
-        $this->container['namespace']   = config("modules.locations.{$this->container['location']}.namespace").$this->container['basename'];
99
-
100
-        return $this->generate();
101
-    }
102
-
103
-    /**
104
-     * Generate the module.
105
-     */
106
-    protected function generate()
107
-    {
108
-        $steps = [
109
-            'Generating module...' => 'generateModule',
110
-            'Optimizing module cache...' => 'optimizeModules',
111
-            'Generating migrations...' => 'generateMigration',
112
-        ];
113
-
114
-        $progress = new ProgressBar($this->output, count($steps));
115
-        $progress->start();
116
-
117
-        foreach ($steps as $message => $function) {
118
-            $progress->setMessage($message);
119
-
120
-            $this->$function();
121
-
122
-            $progress->advance();
123
-        }
124
-
125
-        $progress->finish();
126
-
127
-        event($this->container['slug'] . '.module.made');
128
-
129
-        $this->info("\nModule generated successfully.");
130
-    }
131
-
132
-    /**
133
-     * Generate defined module folders.
134
-     */
135
-    protected function generateModule()
136
-    {
137
-        $location = $this->container['location'];
138
-        $root     = module_path(null, '', $location);
139
-        $manifest = config("modules.locations.$location.manifest") ?: 'module.json';
140
-        $provider = config("modules.locations.$location.provider") ?: 'ModuleServiceProvider';
141
-
142
-        if (!$this->files->isDirectory($root)) {
143
-            $this->files->makeDirectory($root);
144
-        }
145
-
146
-        $directory = module_path(null, $this->container['basename'], $location);
147
-        $source    = __DIR__ . '/Stubs/Module';
148
-
149
-        $this->files->makeDirectory($directory);
150
-
151
-        $sourceFiles = $this->files->allFiles($source, true);
152
-
153
-        if (!empty($this->mapping)) {
154
-            $search = array_keys($this->mapping);
155
-            $replace = array_values($this->mapping);
156
-        }
157
-
158
-        foreach ($sourceFiles as $file) {
159
-            $contents = $this->replacePlaceholders($file->getContents());
160
-            $subPath = $file->getRelativePathname();
161
-
162
-            if (!empty($this->mapping)) {
163
-                $subPath = str_replace($search, $replace, $subPath);
164
-            }
165
-
166
-            $filePath = $directory . '/' . $subPath;
21
+	/**
22
+	 * The console command description.
23
+	 *
24
+	 * @var string
25
+	 */
26
+	protected $description = 'Create a new module';
27
+
28
+	/**
29
+	 * The modules instance.
30
+	 *
31
+	 * @var RepositoryManager
32
+	 */
33
+	protected $module;
34
+
35
+	/**
36
+	 * The filesystem instance.
37
+	 *
38
+	 * @var Filesystem
39
+	 */
40
+	protected $files;
41
+
42
+	/**
43
+	 * Array to store the configuration details.
44
+	 *
45
+	 * @var array
46
+	 */
47
+	protected $container;
48
+
49
+	/**
50
+	 * Array of folder mappings.
51
+	 *
52
+	 * @var Array
53
+	 */
54
+	protected $mapping = [
55
+		'Database/Factories'  => 'Database/Factories',
56
+		'Database/Migrations' => 'Database/Migrations',
57
+		'Database/Seeds'      => 'Database/Seeds',
58
+		'Http/Controllers'    => 'Http/Controllers',
59
+		'Http/Requests'       => 'Http/Requests',
60
+		'Http/Resources'      => 'Http/Resources',
61
+		'ModelObservers'      => 'ModelObservers',
62
+		'Providers'           => 'Providers',
63
+		'Repositories'        => 'Repositories',
64
+		'Services'            => 'Services',
65
+		'Routes'              => 'Routes',
66
+		'Errors'              => 'Errors',
67
+		'Resources'           => 'Resources',
68
+	];
69
+
70
+	/**
71
+	 * Create a new command instance.
72
+	 *
73
+	 * @param Filesystem $files
74
+	 * @param RepositoryManager $module
75
+	 */
76
+	public function __construct(Filesystem $files, RepositoryManager $module)
77
+	{
78
+		parent::__construct();
79
+
80
+		$this->files = $files;
81
+		$this->module = $module;
82
+	}
83
+
84
+	/**
85
+	 * Execute the console command.
86
+	 *
87
+	 * @return mixed
88
+	 */
89
+	public function handle()
90
+	{
91
+		$this->container['slug']        = Str::slug($this->argument('slug'));
92
+		$this->container['name']        = Str::studly($this->container['slug']);
93
+		$this->container['version']     = '1.0';
94
+		$this->container['description'] = 'This is the description for the ' . $this->container['name'] . ' module.';
95
+		$this->container['location']    = config('modules.default_location');
96
+		$this->container['provider']    = config("modules.locations.{$this->container['location']}.provider");
97
+		$this->container['basename']    = Str::studly($this->container['slug']);
98
+		$this->container['namespace']   = config("modules.locations.{$this->container['location']}.namespace").$this->container['basename'];
99
+
100
+		return $this->generate();
101
+	}
102
+
103
+	/**
104
+	 * Generate the module.
105
+	 */
106
+	protected function generate()
107
+	{
108
+		$steps = [
109
+			'Generating module...' => 'generateModule',
110
+			'Optimizing module cache...' => 'optimizeModules',
111
+			'Generating migrations...' => 'generateMigration',
112
+		];
113
+
114
+		$progress = new ProgressBar($this->output, count($steps));
115
+		$progress->start();
116
+
117
+		foreach ($steps as $message => $function) {
118
+			$progress->setMessage($message);
119
+
120
+			$this->$function();
121
+
122
+			$progress->advance();
123
+		}
124
+
125
+		$progress->finish();
126
+
127
+		event($this->container['slug'] . '.module.made');
128
+
129
+		$this->info("\nModule generated successfully.");
130
+	}
131
+
132
+	/**
133
+	 * Generate defined module folders.
134
+	 */
135
+	protected function generateModule()
136
+	{
137
+		$location = $this->container['location'];
138
+		$root     = module_path(null, '', $location);
139
+		$manifest = config("modules.locations.$location.manifest") ?: 'module.json';
140
+		$provider = config("modules.locations.$location.provider") ?: 'ModuleServiceProvider';
141
+
142
+		if (!$this->files->isDirectory($root)) {
143
+			$this->files->makeDirectory($root);
144
+		}
145
+
146
+		$directory = module_path(null, $this->container['basename'], $location);
147
+		$source    = __DIR__ . '/Stubs/Module';
148
+
149
+		$this->files->makeDirectory($directory);
150
+
151
+		$sourceFiles = $this->files->allFiles($source, true);
152
+
153
+		if (!empty($this->mapping)) {
154
+			$search = array_keys($this->mapping);
155
+			$replace = array_values($this->mapping);
156
+		}
157
+
158
+		foreach ($sourceFiles as $file) {
159
+			$contents = $this->replacePlaceholders($file->getContents());
160
+			$subPath = $file->getRelativePathname();
161
+
162
+			if (!empty($this->mapping)) {
163
+				$subPath = str_replace($search, $replace, $subPath);
164
+			}
165
+
166
+			$filePath = $directory . '/' . $subPath;
167 167
             
168
-            // if the file is module.json, replace it with the custom manifest file name
169
-            if ($file->getFilename() === 'module.json' && $manifest) {
170
-                $filePath = str_replace('module.json', $manifest, $filePath);
171
-            }
168
+			// if the file is module.json, replace it with the custom manifest file name
169
+			if ($file->getFilename() === 'module.json' && $manifest) {
170
+				$filePath = str_replace('module.json', $manifest, $filePath);
171
+			}
172 172
             
173
-            // if the file is ModuleServiceProvider.php, replace it with the custom provider file name
174
-            if ($file->getFilename() === 'ModuleServiceProvider.php') {
175
-                $filePath = str_replace('ModuleServiceProvider', $provider, $filePath);
176
-            }
177
-            $filePath = $this->replacePlaceholders($filePath);
173
+			// if the file is ModuleServiceProvider.php, replace it with the custom provider file name
174
+			if ($file->getFilename() === 'ModuleServiceProvider.php') {
175
+				$filePath = str_replace('ModuleServiceProvider', $provider, $filePath);
176
+			}
177
+			$filePath = $this->replacePlaceholders($filePath);
178 178
             
179
-            $dir = dirname($filePath);
179
+			$dir = dirname($filePath);
180 180
             
181
-            if (! $this->files->isDirectory($dir)) {
182
-                $this->files->makeDirectory($dir, 0755, true);
183
-            }
184
-
185
-            $this->files->put($filePath, $contents);
186
-        }
187
-    }
188
-
189
-    protected function replacePlaceholders($contents)
190
-    {
191
-        $modelName = \Str::camel($this->container['slug']);
192
-        $modelNameSingular = \Str::singular($modelName);
193
-
194
-        $find = [
195
-            'DummyFactory',
196
-            'DummyModelName',
197
-            'DummyModuleSlug',
198
-            'DummyModule',
199
-            'DummyModel',
200
-            'DummyDatabaseSeeder',
201
-            'DummyTableSeeder',
202
-            'DummyController',
203
-            'DummyService',
204
-            'DummyRepository',
205
-            'DummyErrors',
206
-            'StoreDummy',
207
-            'DummyResource',
208
-            'DummyObserver',
209
-            'DummyTableName',
210
-            'DummyRoutePrefix',
211
-        ];
212
-
213
-        $replace = [
214
-            ucfirst($modelNameSingular) . 'Factory',
215
-            $modelNameSingular,
216
-            $this->container['slug'],
217
-            ucfirst($modelName),
218
-            ucfirst($modelNameSingular),
219
-            ucfirst($modelName) . 'DatabaseSeeder',
220
-            ucfirst($modelName) . 'TableSeeder',
221
-            ucfirst($modelNameSingular) . 'Controller',
222
-            ucfirst($modelNameSingular) . 'Service',
223
-            ucfirst($modelNameSingular) . 'Repository',
224
-            ucfirst($modelName) . 'Errors',
225
-            'Store' . ucfirst($modelNameSingular),
226
-            ucfirst($modelNameSingular),
227
-            ucfirst($modelNameSingular) . 'Observer',
228
-            \Str::snake($modelName),
229
-            $modelName,
230
-        ];
231
-
232
-        return str_replace($find, $replace, $contents);
233
-    }
234
-
235
-    /**
236
-     * Reset module cache of enabled and disabled modules.
237
-     */
238
-    protected function optimizeModules()
239
-    {
240
-        return $this->callSilent('module:optimize');
241
-    }
242
-
243
-    /**
244
-     * Generate table migrations.
245
-     */
246
-    protected function generateMigration()
247
-    {
248
-        $modelName = $this->container['slug'];
249
-        $migrationName = \Str::camel($modelName);
250
-        $migrationName = \Str::snake($migrationName);
251
-        return $this->callSilent('make:module:migration', ['slug' => $modelName, 'name' => 'create_' . $migrationName . '_table']);
252
-    }
181
+			if (! $this->files->isDirectory($dir)) {
182
+				$this->files->makeDirectory($dir, 0755, true);
183
+			}
184
+
185
+			$this->files->put($filePath, $contents);
186
+		}
187
+	}
188
+
189
+	protected function replacePlaceholders($contents)
190
+	{
191
+		$modelName = \Str::camel($this->container['slug']);
192
+		$modelNameSingular = \Str::singular($modelName);
193
+
194
+		$find = [
195
+			'DummyFactory',
196
+			'DummyModelName',
197
+			'DummyModuleSlug',
198
+			'DummyModule',
199
+			'DummyModel',
200
+			'DummyDatabaseSeeder',
201
+			'DummyTableSeeder',
202
+			'DummyController',
203
+			'DummyService',
204
+			'DummyRepository',
205
+			'DummyErrors',
206
+			'StoreDummy',
207
+			'DummyResource',
208
+			'DummyObserver',
209
+			'DummyTableName',
210
+			'DummyRoutePrefix',
211
+		];
212
+
213
+		$replace = [
214
+			ucfirst($modelNameSingular) . 'Factory',
215
+			$modelNameSingular,
216
+			$this->container['slug'],
217
+			ucfirst($modelName),
218
+			ucfirst($modelNameSingular),
219
+			ucfirst($modelName) . 'DatabaseSeeder',
220
+			ucfirst($modelName) . 'TableSeeder',
221
+			ucfirst($modelNameSingular) . 'Controller',
222
+			ucfirst($modelNameSingular) . 'Service',
223
+			ucfirst($modelNameSingular) . 'Repository',
224
+			ucfirst($modelName) . 'Errors',
225
+			'Store' . ucfirst($modelNameSingular),
226
+			ucfirst($modelNameSingular),
227
+			ucfirst($modelNameSingular) . 'Observer',
228
+			\Str::snake($modelName),
229
+			$modelName,
230
+		];
231
+
232
+		return str_replace($find, $replace, $contents);
233
+	}
234
+
235
+	/**
236
+	 * Reset module cache of enabled and disabled modules.
237
+	 */
238
+	protected function optimizeModules()
239
+	{
240
+		return $this->callSilent('module:optimize');
241
+	}
242
+
243
+	/**
244
+	 * Generate table migrations.
245
+	 */
246
+	protected function generateMigration()
247
+	{
248
+		$modelName = $this->container['slug'];
249
+		$migrationName = \Str::camel($modelName);
250
+		$migrationName = \Str::snake($migrationName);
251
+		return $this->callSilent('make:module:migration', ['slug' => $modelName, 'name' => 'create_' . $migrationName . '_table']);
252
+	}
253 253
 }
Please login to merge, or discard this patch.