Completed
Push — master ( b7f417...e961f1 )
by Sherif
02:36
created
src/Modules/V1/Core/Providers/ModuleServiceProvider.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -7,44 +7,44 @@
 block discarded – undo
7 7
 class ModuleServiceProvider extends ServiceProvider
8 8
 {
9 9
 	/**
10
-     * Bootstrap the module services.
11
-     *
12
-     * @return void
13
-     */
14
-    public function boot()
15
-    {
16
-        $this->loadTranslationsFrom(__DIR__.'/../Resources/Lang', 'core');
17
-        $this->loadViewsFrom(__DIR__.'/../Resources/Views', 'core');
10
+	 * Bootstrap the module services.
11
+	 *
12
+	 * @return void
13
+	 */
14
+	public function boot()
15
+	{
16
+		$this->loadTranslationsFrom(__DIR__.'/../Resources/Lang', 'core');
17
+		$this->loadViewsFrom(__DIR__.'/../Resources/Views', 'core');
18 18
 
19
-        $factory = app('Illuminate\Database\Eloquent\Factory');
20
-        $factory->load(__DIR__.'/../Database/Factories');
21
-    }
19
+		$factory = app('Illuminate\Database\Eloquent\Factory');
20
+		$factory->load(__DIR__.'/../Database/Factories');
21
+	}
22 22
 
23
-    /**
24
-     * Register the module services.
25
-     *
26
-     * @return void
27
-     */
28
-    public function register()
29
-    {
30
-        //Bind Core Facade to the IoC Container
31
-        \App::bind('Core', function()
32
-        {
33
-            return new \App\Modules\V1\Core\Core;
34
-        });
23
+	/**
24
+	 * Register the module services.
25
+	 *
26
+	 * @return void
27
+	 */
28
+	public function register()
29
+	{
30
+		//Bind Core Facade to the IoC Container
31
+		\App::bind('Core', function()
32
+		{
33
+			return new \App\Modules\V1\Core\Core;
34
+		});
35 35
 
36
-        //Bind ErrorHandler Facade to the IoC Container
37
-        \App::bind('ErrorHandler', function()
38
-        {
39
-            return new \App\Modules\V1\Core\Utl\ErrorHandler;
40
-        });
36
+		//Bind ErrorHandler Facade to the IoC Container
37
+		\App::bind('ErrorHandler', function()
38
+		{
39
+			return new \App\Modules\V1\Core\Utl\ErrorHandler;
40
+		});
41 41
 
42
-        //Bind CoreConfig Facade to the IoC Container
43
-        \App::bind('CoreConfig', function()
44
-        {
45
-            return new \App\Modules\V1\Core\Utl\CoreConfig;
46
-        });
42
+		//Bind CoreConfig Facade to the IoC Container
43
+		\App::bind('CoreConfig', function()
44
+		{
45
+			return new \App\Modules\V1\Core\Utl\CoreConfig;
46
+		});
47 47
         
48
-        $this->app->register(RouteServiceProvider::class);
49
-    }
48
+		$this->app->register(RouteServiceProvider::class);
49
+	}
50 50
 }
Please login to merge, or discard this patch.
src/Modules/V1/Core/AbstractRepositories/AbstractRepository.php 1 patch
Indentation   +699 added lines, -699 removed lines patch added patch discarded remove patch
@@ -4,716 +4,716 @@
 block discarded – undo
4 4
 
5 5
 abstract class AbstractRepository implements RepositoryInterface
6 6
 {
7
-    /**
8
-     * The model implementation.
9
-     * 
10
-     * @var model
11
-     */
12
-    public $model;
7
+	/**
8
+	 * The model implementation.
9
+	 * 
10
+	 * @var model
11
+	 */
12
+	public $model;
13 13
     
14
-    /**
15
-     * The config implementation.
16
-     * 
17
-     * @var config
18
-     */
19
-    protected $config;
14
+	/**
15
+	 * The config implementation.
16
+	 * 
17
+	 * @var config
18
+	 */
19
+	protected $config;
20 20
     
21
-    /**
22
-     * Create new AbstractRepository instance.
23
-     */
24
-    public function __construct()
25
-    {   
26
-        $this->config = \CoreConfig::getConfig();
27
-        $this->model  = \App::make($this->getModel());
28
-    }
29
-
30
-    /**
31
-     * Fetch all records with relations from the storage.
32
-     *
33
-     * @param  array   $relations
34
-     * @param  string  $sortBy
35
-     * @param  boolean $desc
36
-     * @param  array   $columns
37
-     * @return collection
38
-     */
39
-    public function all($relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
40
-    {
41
-        $sort = $desc ? 'desc' : 'asc';
42
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->get($columns);
43
-    }
44
-
45
-    /**
46
-     * Fetch all records with relations from storage in pages 
47
-     * that matche the given query.
48
-     * 
49
-     * @param  string  $query
50
-     * @param  integer $perPage
51
-     * @param  array   $relations
52
-     * @param  string  $sortBy
53
-     * @param  boolean $desc
54
-     * @param  array   $columns
55
-     * @return collection
56
-     */
57
-    public function search($query, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
58
-    {
59
-        $model            = call_user_func_array("{$this->getModel()}::with", array($relations));
60
-        $conditionColumns = $this->model->searchable;
61
-        $sort             = $desc ? 'desc' : 'asc';
62
-
63
-        /**
64
-         * Construct the select conditions for the model.
65
-         */
66
-        $model->where(function ($q) use ($query, $conditionColumns, $relations){
67
-
68
-            if (count($conditionColumns)) 
69
-            {
70
-                $column = 'LOWER(' . array_shift($conditionColumns) . ')';
71
-                if (str_contains($column, '->')) 
72
-                {
73
-                    $column = $this->wrapJsonSelector($column);
74
-                }
75
-
76
-                /**
77
-                 * Use the first element in the model columns to construct the first condition.
78
-                 */
79
-                $q->where(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
80
-            }
81
-
82
-            /**
83
-             * Loop through the rest of the columns to construct or where conditions.
84
-             */
85
-            foreach ($conditionColumns as $column) 
86
-            {
87
-                $column = 'LOWER(' . $column . ')';
88
-                if (str_contains($column, '->')) 
89
-                {
90
-                    $column = $this->wrapJsonSelector($column);
91
-                }
92
-
93
-                $q->orWhere(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
94
-            }
95
-
96
-            /**
97
-             * Loop through the model relations.
98
-             */
99
-            foreach ($relations as $relation) 
100
-            {
101
-                /**
102
-                 * Remove the sub relation if exists.
103
-                 */
104
-                $relation = explode('.', $relation)[0];
105
-
106
-                /**
107
-                 * Try to fetch the relation repository from the core.
108
-                 */
109
-                if (\Core::$relation()) 
110
-                {
111
-                    /**
112
-                     * Construct the relation condition.
113
-                     */
114
-                    $q->orWhereHas($relation, function ($subModel) use ($query, $relation){
115
-
116
-                        $subModel->where(function ($q) use ($query, $relation){
117
-
118
-                            /**
119
-                             * Get columns of the relation.
120
-                             */
121
-                            $subConditionColumns = \Core::$relation()->model->searchable;
122
-
123
-                            if (count($subConditionColumns)) 
124
-                            {
125
-
126
-                                $column = 'LOWER(' . array_shift($subConditionColumns) . ')';
127
-                                if (str_contains($column, '->')) 
128
-                                {
129
-                                    $column = $this->wrapJsonSelector($column);
130
-                                }
131
-
132
-                                /**
133
-                                * Use the first element in the relation model columns to construct the first condition.
134
-                                 */
135
-                                $q->where(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
136
-                            }
137
-
138
-                            /**
139
-                             * Loop through the rest of the columns to construct or where conditions.
140
-                             */
141
-                            foreach ($subConditionColumns as $subConditionColumn)
142
-                            {
143
-                                $column = 'LOWER(' . $subConditionColumn . ')';
144
-                                if (str_contains($column, '->')) 
145
-                                {
146
-                                    $column = $this->wrapJsonSelector($column);
147
-                                }
21
+	/**
22
+	 * Create new AbstractRepository instance.
23
+	 */
24
+	public function __construct()
25
+	{   
26
+		$this->config = \CoreConfig::getConfig();
27
+		$this->model  = \App::make($this->getModel());
28
+	}
29
+
30
+	/**
31
+	 * Fetch all records with relations from the storage.
32
+	 *
33
+	 * @param  array   $relations
34
+	 * @param  string  $sortBy
35
+	 * @param  boolean $desc
36
+	 * @param  array   $columns
37
+	 * @return collection
38
+	 */
39
+	public function all($relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
40
+	{
41
+		$sort = $desc ? 'desc' : 'asc';
42
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->get($columns);
43
+	}
44
+
45
+	/**
46
+	 * Fetch all records with relations from storage in pages 
47
+	 * that matche the given query.
48
+	 * 
49
+	 * @param  string  $query
50
+	 * @param  integer $perPage
51
+	 * @param  array   $relations
52
+	 * @param  string  $sortBy
53
+	 * @param  boolean $desc
54
+	 * @param  array   $columns
55
+	 * @return collection
56
+	 */
57
+	public function search($query, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
58
+	{
59
+		$model            = call_user_func_array("{$this->getModel()}::with", array($relations));
60
+		$conditionColumns = $this->model->searchable;
61
+		$sort             = $desc ? 'desc' : 'asc';
62
+
63
+		/**
64
+		 * Construct the select conditions for the model.
65
+		 */
66
+		$model->where(function ($q) use ($query, $conditionColumns, $relations){
67
+
68
+			if (count($conditionColumns)) 
69
+			{
70
+				$column = 'LOWER(' . array_shift($conditionColumns) . ')';
71
+				if (str_contains($column, '->')) 
72
+				{
73
+					$column = $this->wrapJsonSelector($column);
74
+				}
75
+
76
+				/**
77
+				 * Use the first element in the model columns to construct the first condition.
78
+				 */
79
+				$q->where(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
80
+			}
81
+
82
+			/**
83
+			 * Loop through the rest of the columns to construct or where conditions.
84
+			 */
85
+			foreach ($conditionColumns as $column) 
86
+			{
87
+				$column = 'LOWER(' . $column . ')';
88
+				if (str_contains($column, '->')) 
89
+				{
90
+					$column = $this->wrapJsonSelector($column);
91
+				}
92
+
93
+				$q->orWhere(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
94
+			}
95
+
96
+			/**
97
+			 * Loop through the model relations.
98
+			 */
99
+			foreach ($relations as $relation) 
100
+			{
101
+				/**
102
+				 * Remove the sub relation if exists.
103
+				 */
104
+				$relation = explode('.', $relation)[0];
105
+
106
+				/**
107
+				 * Try to fetch the relation repository from the core.
108
+				 */
109
+				if (\Core::$relation()) 
110
+				{
111
+					/**
112
+					 * Construct the relation condition.
113
+					 */
114
+					$q->orWhereHas($relation, function ($subModel) use ($query, $relation){
115
+
116
+						$subModel->where(function ($q) use ($query, $relation){
117
+
118
+							/**
119
+							 * Get columns of the relation.
120
+							 */
121
+							$subConditionColumns = \Core::$relation()->model->searchable;
122
+
123
+							if (count($subConditionColumns)) 
124
+							{
125
+
126
+								$column = 'LOWER(' . array_shift($subConditionColumns) . ')';
127
+								if (str_contains($column, '->')) 
128
+								{
129
+									$column = $this->wrapJsonSelector($column);
130
+								}
131
+
132
+								/**
133
+								 * Use the first element in the relation model columns to construct the first condition.
134
+								 */
135
+								$q->where(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
136
+							}
137
+
138
+							/**
139
+							 * Loop through the rest of the columns to construct or where conditions.
140
+							 */
141
+							foreach ($subConditionColumns as $subConditionColumn)
142
+							{
143
+								$column = 'LOWER(' . $subConditionColumn . ')';
144
+								if (str_contains($column, '->')) 
145
+								{
146
+									$column = $this->wrapJsonSelector($column);
147
+								}
148 148
                                 
149
-                                $q->orWhere(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
150
-                            } 
151
-                        });
152
-
153
-                    });
154
-                }
155
-            }
156
-        });
149
+								$q->orWhere(\DB::raw($column), 'LIKE', '%' . strtolower($query) . '%');
150
+							} 
151
+						});
152
+
153
+					});
154
+				}
155
+			}
156
+		});
157 157
         
158
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
159
-    }
158
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
159
+	}
160 160
     
161
-    /**
162
-     * Fetch all records with relations from storage in pages.
163
-     * 
164
-     * @param  integer $perPage
165
-     * @param  array   $relations
166
-     * @param  string  $sortBy
167
-     * @param  boolean $desc
168
-     * @param  array   $columns
169
-     * @return collection
170
-     */
171
-    public function paginate($perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
172
-    {
173
-        $sort = $desc ? 'desc' : 'asc';
174
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->paginate($perPage, $columns);
175
-    }
176
-
177
-    /**
178
-     * Fetch all records with relations based on
179
-     * the given condition from storage in pages.
180
-     * 
181
-     * @param  array   $conditions array of conditions
182
-     * @param  integer $perPage
183
-     * @param  array   $relations
184
-     * @param  string  $sortBy
185
-     * @param  boolean $desc
186
-     * @param  array   $columns
187
-     * @return collection
188
-     */
189
-    public function paginateBy($conditions, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
190
-    {
191
-        unset($conditions['page']);
192
-        $conditions = $this->constructConditions($conditions, $this->model);
193
-        $sort       = $desc ? 'desc' : 'asc';
194
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
195
-    }
161
+	/**
162
+	 * Fetch all records with relations from storage in pages.
163
+	 * 
164
+	 * @param  integer $perPage
165
+	 * @param  array   $relations
166
+	 * @param  string  $sortBy
167
+	 * @param  boolean $desc
168
+	 * @param  array   $columns
169
+	 * @return collection
170
+	 */
171
+	public function paginate($perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
172
+	{
173
+		$sort = $desc ? 'desc' : 'asc';
174
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->orderBy($sortBy, $sort)->paginate($perPage, $columns);
175
+	}
176
+
177
+	/**
178
+	 * Fetch all records with relations based on
179
+	 * the given condition from storage in pages.
180
+	 * 
181
+	 * @param  array   $conditions array of conditions
182
+	 * @param  integer $perPage
183
+	 * @param  array   $relations
184
+	 * @param  string  $sortBy
185
+	 * @param  boolean $desc
186
+	 * @param  array   $columns
187
+	 * @return collection
188
+	 */
189
+	public function paginateBy($conditions, $perPage = 15, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
190
+	{
191
+		unset($conditions['page']);
192
+		$conditions = $this->constructConditions($conditions, $this->model);
193
+		$sort       = $desc ? 'desc' : 'asc';
194
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->paginate($perPage, $columns);
195
+	}
196 196
     
197
-    /**
198
-     * Save the given model to the storage.
199
-     * 
200
-     * @param  array   $data
201
-     * @return object
202
-     */
203
-    public function save(array $data)
204
-    {
205
-        $model      = false;
206
-        $modelClass = $this->model;
207
-        $relations  = [];
208
-
209
-        \DB::transaction(function () use (&$model, &$relations, $data, $modelClass) {
210
-            /**
211
-             * If the id is present in the data then select the model for updating,
212
-             * else create new model.
213
-             * @var array
214
-             */
215
-            $model = array_key_exists('id', $data) ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
216
-            if ( ! $model) 
217
-            {
218
-                \ErrorHandler::notFound(class_basename($modelClass) . ' with id : ' . $data['id']);
219
-            }
220
-
221
-            /**
222
-             * Construct the model object with the given data,
223
-             * and if there is a relation add it to relations array,
224
-             * then save the model.
225
-             */
226
-            foreach ($data as $key => $value) 
227
-            {
228
-                /**
229
-                 * If the attribute is a relation.
230
-                 */
231
-                $relation = camel_case($key);
232
-                if (method_exists($model, $relation) && \Core::$relation())
233
-                {
234
-                    /**
235
-                     * Check if the relation is a collection.
236
-                     */
237
-                    if (class_basename($model->$relation) == 'Collection') 
238
-                    {   
239
-                        /**
240
-                         * If the relation has no value then marke the relation data 
241
-                         * related to the model to be deleted.
242
-                         */
243
-                        if ( ! $value || ! count($value)) 
244
-                        {
245
-                            $relations[$relation] = 'delete';
246
-                        }   
247
-                    }
248
-                    if (is_array($value)) 
249
-                    {
250
-                        /**
251
-                         * Loop through the relation data.
252
-                         */
253
-                        foreach ($value as $attr => $val) 
254
-                        {
255
-                            /**
256
-                             * Get the relation model.
257
-                             */
258
-                            $relationBaseModel = \Core::$relation()->model;
259
-
260
-                            /**
261
-                             * Check if the relation is a collection.
262
-                             */
263
-                            if (class_basename($model->$relation) == 'Collection')
264
-                            {
265
-                                /**
266
-                                 * If the id is present in the data then select the relation model for updating,
267
-                                 * else create new model.
268
-                                 */
269
-                                $relationModel = array_key_exists('id', $val) ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
270
-
271
-                                /**
272
-                                 * If model doesn't exists.
273
-                                 */
274
-                                if ( ! $relationModel) 
275
-                                {
276
-                                    \ErrorHandler::notFound(class_basename($relationBaseModel) . ' with id : ' . $val['id']);
277
-                                }
278
-
279
-                                /**
280
-                                 * Loop through the relation attributes.
281
-                                 */
282
-                                foreach ($val as $attr => $val) 
283
-                                {
284
-                                    /**
285
-                                     * Prevent the sub relations or attributes not in the fillable.
286
-                                     */
287
-                                    if (gettype($val) !== 'object' && gettype($val) !== 'array' &&  array_search($attr, $relationModel->getFillable(), true) !== false)
288
-                                    {
289
-                                        $relationModel->$attr = $val;
290
-                                    }
291
-                                }
292
-
293
-                                $relations[$relation][] = $relationModel;
294
-                            }
295
-                            /**
296
-                             * If not collection.
297
-                             */
298
-                            else
299
-                            {
300
-                                /**
301
-                                 * Prevent the sub relations.
302
-                                 */
303
-                                if (gettype($val) !== 'object' && gettype($val) !== 'array') 
304
-                                {
305
-
306
-                                    /**
307
-                                     * If the id is present in the data then select the relation model for updating,
308
-                                     * else create new model.
309
-                                     */
310
-                                    $relationModel = array_key_exists('id', $value) ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
311
-
312
-                                    /**
313
-                                     * If model doesn't exists.
314
-                                     */
315
-                                    if ( ! $relationModel) 
316
-                                    {
317
-                                        \ErrorHandler::notFound(class_basename($relationBaseModel) . ' with id : ' . $value['id']);
318
-                                    }
319
-
320
-                                    foreach ($value as $relationAttribute => $relationValue) 
321
-                                    {
322
-                                        /**
323
-                                         * Prevent attributes not in the fillable.
324
-                                         */
325
-                                        if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) 
326
-                                        {
327
-                                            $relationModel->$relationAttribute = $relationValue;
328
-                                        }
329
-                                    }
330
-
331
-                                    $relations[$relation] = $relationModel;
332
-                                }
333
-                            }
334
-                        }
335
-                    }
336
-                }
337
-                /**
338
-                 * If the attribute isn't a relation and prevent attributes not in the fillable.
339
-                 */
340
-                else if (array_search($key, $model->getFillable(), true) !== false)
341
-                {
342
-                    $model->$key = $value;   
343
-                }
344
-            }
345
-
346
-            /**
347
-             * Loop through the relations array.
348
-             */
349
-            foreach ($relations as $key => $value) 
350
-            {
351
-                /**
352
-                 * If the relation is marked for delete then delete it.
353
-                 */
354
-                if ($value == 'delete' && $model->$key()->count())
355
-                {
356
-                    $model->$key()->delete();
357
-                }
358
-                /**
359
-                 * If the relation is an array.
360
-                 */
361
-                else if (gettype($value) == 'array') 
362
-                {
363
-                    /**
364
-                     * Save the model.
365
-                     */
366
-                    $model->save();
367
-                    $ids = [];
368
-
369
-                    /**
370
-                     * Loop through the relations.
371
-                     */
372
-                    foreach ($value as $val) 
373
-                    {
374
-                        switch (class_basename($model->$key())) 
375
-                        {
376
-                            /**
377
-                             * If the relation is one to many then update it's foreign key with
378
-                             * the model id and save it then add its id to ids array to delete all 
379
-                             * relations who's id isn't in the ids array.
380
-                             */
381
-                            case 'HasMany':
382
-                                $foreignKeyName       = $model->$key()->getForeignKeyName();
383
-                                $val->$foreignKeyName = $model->id;
384
-                                $val->save();
385
-                                $ids[] = $val->id;
386
-                                break;
387
-
388
-                            /**
389
-                             * If the relation is many to many then add it's id to the ids array to
390
-                             * attache these ids to the model.
391
-                             */
392
-                            case 'BelongsToMany':
393
-                                $val->save();
394
-                                $ids[] = $val->id;
395
-                                break;
396
-                        }
397
-                    }
398
-                    switch (class_basename($model->$key())) 
399
-                    {
400
-                        /**
401
-                         * If the relation is one to many then delete all 
402
-                         * relations who's id isn't in the ids array.
403
-                         */
404
-                        case 'HasMany':
405
-                            $model->$key()->whereNotIn('id', $ids)->delete();
406
-                            break;
407
-
408
-                        /**
409
-                         * If the relation is many to many then 
410
-                         * detach the previous data and attach 
411
-                         * the ids array to the model.
412
-                         */
413
-                        case 'BelongsToMany':
414
-                            $model->$key()->detach();
415
-                            $model->$key()->attach($ids);
416
-                            break;
417
-                    }
418
-                }
419
-                /**
420
-                 * If the relation isn't array.
421
-                 */
422
-                else
423
-                {
424
-                    switch (class_basename($model->$key())) 
425
-                    {
426
-                        /**
427
-                         * If the relation is one to one.
428
-                         */
429
-                        case 'HasOne':
430
-                            /**
431
-                             * Save the model.
432
-                             */
433
-                            $model->save();
434
-                            $foreignKeyName         = $model->$key()->getForeignKeyName();
435
-                            $value->$foreignKeyName = $model->id;
436
-                            $value->save();
437
-                            break;
438
-                        case 'BelongsTo':
439
-                            /**
440
-                             * Save the model.
441
-                             */
442
-                            $value->save();
443
-                            $model->$key()->associate($value);
444
-                            break;
445
-                    }
446
-                }
447
-            }
448
-
449
-            /**
450
-             * Save the model.
451
-             */
452
-            $model->save();
453
-        });
197
+	/**
198
+	 * Save the given model to the storage.
199
+	 * 
200
+	 * @param  array   $data
201
+	 * @return object
202
+	 */
203
+	public function save(array $data)
204
+	{
205
+		$model      = false;
206
+		$modelClass = $this->model;
207
+		$relations  = [];
208
+
209
+		\DB::transaction(function () use (&$model, &$relations, $data, $modelClass) {
210
+			/**
211
+			 * If the id is present in the data then select the model for updating,
212
+			 * else create new model.
213
+			 * @var array
214
+			 */
215
+			$model = array_key_exists('id', $data) ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
216
+			if ( ! $model) 
217
+			{
218
+				\ErrorHandler::notFound(class_basename($modelClass) . ' with id : ' . $data['id']);
219
+			}
220
+
221
+			/**
222
+			 * Construct the model object with the given data,
223
+			 * and if there is a relation add it to relations array,
224
+			 * then save the model.
225
+			 */
226
+			foreach ($data as $key => $value) 
227
+			{
228
+				/**
229
+				 * If the attribute is a relation.
230
+				 */
231
+				$relation = camel_case($key);
232
+				if (method_exists($model, $relation) && \Core::$relation())
233
+				{
234
+					/**
235
+					 * Check if the relation is a collection.
236
+					 */
237
+					if (class_basename($model->$relation) == 'Collection') 
238
+					{   
239
+						/**
240
+						 * If the relation has no value then marke the relation data 
241
+						 * related to the model to be deleted.
242
+						 */
243
+						if ( ! $value || ! count($value)) 
244
+						{
245
+							$relations[$relation] = 'delete';
246
+						}   
247
+					}
248
+					if (is_array($value)) 
249
+					{
250
+						/**
251
+						 * Loop through the relation data.
252
+						 */
253
+						foreach ($value as $attr => $val) 
254
+						{
255
+							/**
256
+							 * Get the relation model.
257
+							 */
258
+							$relationBaseModel = \Core::$relation()->model;
259
+
260
+							/**
261
+							 * Check if the relation is a collection.
262
+							 */
263
+							if (class_basename($model->$relation) == 'Collection')
264
+							{
265
+								/**
266
+								 * If the id is present in the data then select the relation model for updating,
267
+								 * else create new model.
268
+								 */
269
+								$relationModel = array_key_exists('id', $val) ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
270
+
271
+								/**
272
+								 * If model doesn't exists.
273
+								 */
274
+								if ( ! $relationModel) 
275
+								{
276
+									\ErrorHandler::notFound(class_basename($relationBaseModel) . ' with id : ' . $val['id']);
277
+								}
278
+
279
+								/**
280
+								 * Loop through the relation attributes.
281
+								 */
282
+								foreach ($val as $attr => $val) 
283
+								{
284
+									/**
285
+									 * Prevent the sub relations or attributes not in the fillable.
286
+									 */
287
+									if (gettype($val) !== 'object' && gettype($val) !== 'array' &&  array_search($attr, $relationModel->getFillable(), true) !== false)
288
+									{
289
+										$relationModel->$attr = $val;
290
+									}
291
+								}
292
+
293
+								$relations[$relation][] = $relationModel;
294
+							}
295
+							/**
296
+							 * If not collection.
297
+							 */
298
+							else
299
+							{
300
+								/**
301
+								 * Prevent the sub relations.
302
+								 */
303
+								if (gettype($val) !== 'object' && gettype($val) !== 'array') 
304
+								{
305
+
306
+									/**
307
+									 * If the id is present in the data then select the relation model for updating,
308
+									 * else create new model.
309
+									 */
310
+									$relationModel = array_key_exists('id', $value) ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
311
+
312
+									/**
313
+									 * If model doesn't exists.
314
+									 */
315
+									if ( ! $relationModel) 
316
+									{
317
+										\ErrorHandler::notFound(class_basename($relationBaseModel) . ' with id : ' . $value['id']);
318
+									}
319
+
320
+									foreach ($value as $relationAttribute => $relationValue) 
321
+									{
322
+										/**
323
+										 * Prevent attributes not in the fillable.
324
+										 */
325
+										if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) 
326
+										{
327
+											$relationModel->$relationAttribute = $relationValue;
328
+										}
329
+									}
330
+
331
+									$relations[$relation] = $relationModel;
332
+								}
333
+							}
334
+						}
335
+					}
336
+				}
337
+				/**
338
+				 * If the attribute isn't a relation and prevent attributes not in the fillable.
339
+				 */
340
+				else if (array_search($key, $model->getFillable(), true) !== false)
341
+				{
342
+					$model->$key = $value;   
343
+				}
344
+			}
345
+
346
+			/**
347
+			 * Loop through the relations array.
348
+			 */
349
+			foreach ($relations as $key => $value) 
350
+			{
351
+				/**
352
+				 * If the relation is marked for delete then delete it.
353
+				 */
354
+				if ($value == 'delete' && $model->$key()->count())
355
+				{
356
+					$model->$key()->delete();
357
+				}
358
+				/**
359
+				 * If the relation is an array.
360
+				 */
361
+				else if (gettype($value) == 'array') 
362
+				{
363
+					/**
364
+					 * Save the model.
365
+					 */
366
+					$model->save();
367
+					$ids = [];
368
+
369
+					/**
370
+					 * Loop through the relations.
371
+					 */
372
+					foreach ($value as $val) 
373
+					{
374
+						switch (class_basename($model->$key())) 
375
+						{
376
+							/**
377
+							 * If the relation is one to many then update it's foreign key with
378
+							 * the model id and save it then add its id to ids array to delete all 
379
+							 * relations who's id isn't in the ids array.
380
+							 */
381
+							case 'HasMany':
382
+								$foreignKeyName       = $model->$key()->getForeignKeyName();
383
+								$val->$foreignKeyName = $model->id;
384
+								$val->save();
385
+								$ids[] = $val->id;
386
+								break;
387
+
388
+							/**
389
+							 * If the relation is many to many then add it's id to the ids array to
390
+							 * attache these ids to the model.
391
+							 */
392
+							case 'BelongsToMany':
393
+								$val->save();
394
+								$ids[] = $val->id;
395
+								break;
396
+						}
397
+					}
398
+					switch (class_basename($model->$key())) 
399
+					{
400
+						/**
401
+						 * If the relation is one to many then delete all 
402
+						 * relations who's id isn't in the ids array.
403
+						 */
404
+						case 'HasMany':
405
+							$model->$key()->whereNotIn('id', $ids)->delete();
406
+							break;
407
+
408
+						/**
409
+						 * If the relation is many to many then 
410
+						 * detach the previous data and attach 
411
+						 * the ids array to the model.
412
+						 */
413
+						case 'BelongsToMany':
414
+							$model->$key()->detach();
415
+							$model->$key()->attach($ids);
416
+							break;
417
+					}
418
+				}
419
+				/**
420
+				 * If the relation isn't array.
421
+				 */
422
+				else
423
+				{
424
+					switch (class_basename($model->$key())) 
425
+					{
426
+						/**
427
+						 * If the relation is one to one.
428
+						 */
429
+						case 'HasOne':
430
+							/**
431
+							 * Save the model.
432
+							 */
433
+							$model->save();
434
+							$foreignKeyName         = $model->$key()->getForeignKeyName();
435
+							$value->$foreignKeyName = $model->id;
436
+							$value->save();
437
+							break;
438
+						case 'BelongsTo':
439
+							/**
440
+							 * Save the model.
441
+							 */
442
+							$value->save();
443
+							$model->$key()->associate($value);
444
+							break;
445
+					}
446
+				}
447
+			}
448
+
449
+			/**
450
+			 * Save the model.
451
+			 */
452
+			$model->save();
453
+		});
454 454
             
455
-        return $model;
456
-    }
455
+		return $model;
456
+	}
457 457
     
458
-    /**
459
-     * Update record in the storage based on the given
460
-     * condition.
461
-     * 
462
-     * @param  var $value condition value
463
-     * @param  array $data
464
-     * @param  string $attribute condition column name
465
-     * @return void
466
-     */
467
-    public function update($value, array $data, $attribute = 'id')
468
-    {
469
-        if ($attribute == 'id') 
470
-        {
471
-            $model = $this->model->lockForUpdate()->find($value);
472
-            $model ? $model->update($data) : 0;
473
-        }
474
-        else
475
-        {
476
-            call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model) use ($data){
477
-                $model->update($data);
478
-            });
479
-        }
480
-    }
481
-
482
-    /**
483
-     * Delete record from the storage based on the given
484
-     * condition.
485
-     * 
486
-     * @param  var $value condition value
487
-     * @param  string $attribute condition column name
488
-     * @return void
489
-     */
490
-    public function delete($value, $attribute = 'id')
491
-    {
492
-        if ($attribute == 'id') 
493
-        {
494
-            \DB::transaction(function () use ($value, $attribute, &$result) {
495
-                $model = $this->model->lockForUpdate()->find($value);
496
-                if ( ! $model) 
497
-                {
498
-                    \ErrorHandler::notFound(class_basename($this->model) . ' with id : ' . $value);
499
-                }
458
+	/**
459
+	 * Update record in the storage based on the given
460
+	 * condition.
461
+	 * 
462
+	 * @param  var $value condition value
463
+	 * @param  array $data
464
+	 * @param  string $attribute condition column name
465
+	 * @return void
466
+	 */
467
+	public function update($value, array $data, $attribute = 'id')
468
+	{
469
+		if ($attribute == 'id') 
470
+		{
471
+			$model = $this->model->lockForUpdate()->find($value);
472
+			$model ? $model->update($data) : 0;
473
+		}
474
+		else
475
+		{
476
+			call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model) use ($data){
477
+				$model->update($data);
478
+			});
479
+		}
480
+	}
481
+
482
+	/**
483
+	 * Delete record from the storage based on the given
484
+	 * condition.
485
+	 * 
486
+	 * @param  var $value condition value
487
+	 * @param  string $attribute condition column name
488
+	 * @return void
489
+	 */
490
+	public function delete($value, $attribute = 'id')
491
+	{
492
+		if ($attribute == 'id') 
493
+		{
494
+			\DB::transaction(function () use ($value, $attribute, &$result) {
495
+				$model = $this->model->lockForUpdate()->find($value);
496
+				if ( ! $model) 
497
+				{
498
+					\ErrorHandler::notFound(class_basename($this->model) . ' with id : ' . $value);
499
+				}
500 500
                 
501
-                $model->delete();
502
-            });
503
-        }
504
-        else
505
-        {
506
-            \DB::transaction(function () use ($value, $attribute, &$result) {
507
-                call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model){
508
-                    $model->delete();
509
-                });
510
-            });   
511
-        }
512
-    }
501
+				$model->delete();
502
+			});
503
+		}
504
+		else
505
+		{
506
+			\DB::transaction(function () use ($value, $attribute, &$result) {
507
+				call_user_func_array("{$this->getModel()}::where", array($attribute, '=', $value))->lockForUpdate()->get()->each(function ($model){
508
+					$model->delete();
509
+				});
510
+			});   
511
+		}
512
+	}
513 513
     
514
-    /**
515
-     * Fetch records from the storage based on the given
516
-     * id.
517
-     * 
518
-     * @param  integer $id
519
-     * @param  array   $relations
520
-     * @param  array   $columns
521
-     * @return object
522
-     */
523
-    public function find($id, $relations = [], $columns = array('*'))
524
-    {
525
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->find($id, $columns);
526
-    }
514
+	/**
515
+	 * Fetch records from the storage based on the given
516
+	 * id.
517
+	 * 
518
+	 * @param  integer $id
519
+	 * @param  array   $relations
520
+	 * @param  array   $columns
521
+	 * @return object
522
+	 */
523
+	public function find($id, $relations = [], $columns = array('*'))
524
+	{
525
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->find($id, $columns);
526
+	}
527 527
     
528
-    /**
529
-     * Fetch records from the storage based on the given
530
-     * condition.
531
-     * 
532
-     * @param  array   $conditions array of conditions
533
-     * @param  array   $relations
534
-     * @param  string  $sortBy
535
-     * @param  boolean $desc
536
-     * @param  array   $columns
537
-     * @return collection
538
-     */
539
-    public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
540
-    {
541
-        $conditions = $this->constructConditions($conditions, $this->model);
542
-        $sort       = $desc ? 'desc' : 'asc';
543
-        return call_user_func_array("{$this->getModel()}::with",  array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
544
-    }
545
-
546
-    /**
547
-     * Fetch the first record from the storage based on the given
548
-     * condition.
549
-     *
550
-     * @param  array   $conditions array of conditions
551
-     * @param  array   $relations
552
-     * @param  array   $columns
553
-     * @return object
554
-     */
555
-    public function first($conditions, $relations = [], $columns = array('*'))
556
-    {
557
-        $conditions = $this->constructConditions($conditions, $this->model);
558
-        return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);  
559
-    }
560
-
561
-    /**
562
-     * Return the deleted models in pages based on the given conditions.
563
-     * 
564
-     * @param  array   $conditions array of conditions
565
-     * @param  integer $perPage
566
-     * @param  string  $sortBy
567
-     * @param  boolean $desc
568
-     * @param  array   $columns
569
-     * @return collection
570
-     */
571
-    public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = array('*'))
572
-    {
573
-        unset($conditions['page']);
574
-        $conditions = $this->constructConditions($conditions, $this->model);
575
-        $sort       = $desc ? 'desc' : 'asc';
576
-        $model      = $this->model->onlyTrashed();
577
-
578
-        if (count($conditions['conditionValues']))
579
-        {
580
-            $model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
581
-        }
582
-
583
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);;
584
-    }
585
-
586
-    /**
587
-     * Restore the deleted model.
588
-     * 
589
-     * @param  integer $id
590
-     * @return void
591
-     */
592
-    public function restore($id)
593
-    {
594
-        $model = $this->model->onlyTrashed()->find($id);
595
-
596
-        if ( ! $model) 
597
-        {
598
-            \ErrorHandler::notFound(class_basename($this->model) . ' with id : ' . $id);
599
-        }
600
-
601
-        $model->restore();
602
-    }
603
-
604
-    /**
605
-     * Build the conditions recursively for the retrieving methods.
606
-     * @param  array $conditions
607
-     * @return array
608
-     */
609
-    protected function constructConditions($conditions, $model)
610
-    {   
611
-        $conditionString = '';
612
-        $conditionValues = [];
613
-        foreach ($conditions as $key => $value) 
614
-        {
615
-            if (str_contains($key, '->')) 
616
-            {
617
-                $key = $this->wrapJsonSelector($key);
618
-            }
619
-
620
-            if ($key == 'and') 
621
-            {
622
-                $conditions       = $this->constructConditions($value, $model);
623
-                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']) . ' {op} ';
624
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
625
-            }
626
-            else if ($key == 'or')
627
-            {
628
-                $conditions       = $this->constructConditions($value, $model);
629
-                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']) . ' {op} ';
630
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
631
-            }
632
-            else
633
-            {
634
-                if (is_array($value)) 
635
-                {
636
-                    $operator = $value['op'];
637
-                    if (strtolower($operator) == 'between') 
638
-                    {
639
-                        $value1 = $value['val1'];
640
-                        $value2 = $value['val2'];
641
-                    }
642
-                    else
643
-                    {
644
-                        $value = array_key_exists('val', $value) ? $value['val'] : '';
645
-                    }
646
-                }
647
-                else
648
-                {
649
-                    $operator = '=';
650
-                }
528
+	/**
529
+	 * Fetch records from the storage based on the given
530
+	 * condition.
531
+	 * 
532
+	 * @param  array   $conditions array of conditions
533
+	 * @param  array   $relations
534
+	 * @param  string  $sortBy
535
+	 * @param  boolean $desc
536
+	 * @param  array   $columns
537
+	 * @return collection
538
+	 */
539
+	public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = array('*'))
540
+	{
541
+		$conditions = $this->constructConditions($conditions, $this->model);
542
+		$sort       = $desc ? 'desc' : 'asc';
543
+		return call_user_func_array("{$this->getModel()}::with",  array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
544
+	}
545
+
546
+	/**
547
+	 * Fetch the first record from the storage based on the given
548
+	 * condition.
549
+	 *
550
+	 * @param  array   $conditions array of conditions
551
+	 * @param  array   $relations
552
+	 * @param  array   $columns
553
+	 * @return object
554
+	 */
555
+	public function first($conditions, $relations = [], $columns = array('*'))
556
+	{
557
+		$conditions = $this->constructConditions($conditions, $this->model);
558
+		return call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);  
559
+	}
560
+
561
+	/**
562
+	 * Return the deleted models in pages based on the given conditions.
563
+	 * 
564
+	 * @param  array   $conditions array of conditions
565
+	 * @param  integer $perPage
566
+	 * @param  string  $sortBy
567
+	 * @param  boolean $desc
568
+	 * @param  array   $columns
569
+	 * @return collection
570
+	 */
571
+	public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = array('*'))
572
+	{
573
+		unset($conditions['page']);
574
+		$conditions = $this->constructConditions($conditions, $this->model);
575
+		$sort       = $desc ? 'desc' : 'asc';
576
+		$model      = $this->model->onlyTrashed();
577
+
578
+		if (count($conditions['conditionValues']))
579
+		{
580
+			$model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
581
+		}
582
+
583
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);;
584
+	}
585
+
586
+	/**
587
+	 * Restore the deleted model.
588
+	 * 
589
+	 * @param  integer $id
590
+	 * @return void
591
+	 */
592
+	public function restore($id)
593
+	{
594
+		$model = $this->model->onlyTrashed()->find($id);
595
+
596
+		if ( ! $model) 
597
+		{
598
+			\ErrorHandler::notFound(class_basename($this->model) . ' with id : ' . $id);
599
+		}
600
+
601
+		$model->restore();
602
+	}
603
+
604
+	/**
605
+	 * Build the conditions recursively for the retrieving methods.
606
+	 * @param  array $conditions
607
+	 * @return array
608
+	 */
609
+	protected function constructConditions($conditions, $model)
610
+	{   
611
+		$conditionString = '';
612
+		$conditionValues = [];
613
+		foreach ($conditions as $key => $value) 
614
+		{
615
+			if (str_contains($key, '->')) 
616
+			{
617
+				$key = $this->wrapJsonSelector($key);
618
+			}
619
+
620
+			if ($key == 'and') 
621
+			{
622
+				$conditions       = $this->constructConditions($value, $model);
623
+				$conditionString .= str_replace('{op}', 'and', $conditions['conditionString']) . ' {op} ';
624
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
625
+			}
626
+			else if ($key == 'or')
627
+			{
628
+				$conditions       = $this->constructConditions($value, $model);
629
+				$conditionString .= str_replace('{op}', 'or', $conditions['conditionString']) . ' {op} ';
630
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
631
+			}
632
+			else
633
+			{
634
+				if (is_array($value)) 
635
+				{
636
+					$operator = $value['op'];
637
+					if (strtolower($operator) == 'between') 
638
+					{
639
+						$value1 = $value['val1'];
640
+						$value2 = $value['val2'];
641
+					}
642
+					else
643
+					{
644
+						$value = array_key_exists('val', $value) ? $value['val'] : '';
645
+					}
646
+				}
647
+				else
648
+				{
649
+					$operator = '=';
650
+				}
651 651
                 
652
-                if (strtolower($operator) == 'between') 
653
-                {
654
-                    $conditionString  .= $key . ' >= ? and ';
655
-                    $conditionValues[] = $value1;
656
-
657
-                    $conditionString  .= $key . ' <= ? {op} ';
658
-                    $conditionValues[] = $value2;
659
-                }
660
-                elseif (strtolower($operator) == 'in') 
661
-                {
662
-                    $conditionValues  = array_merge($conditionValues, $value);
663
-                    $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
664
-                    $conditionString .= $key . ' in (' . rtrim($inBindingsString, ',') . ') {op} ';
665
-                }
666
-                elseif (strtolower($operator) == 'null') 
667
-                {
668
-                    $conditionString .= $key . ' is null {op} ';
669
-                }
670
-                elseif (strtolower($operator) == 'not null') 
671
-                {
672
-                    $conditionString .= $key . ' is not null {op} ';
673
-                }
674
-                elseif (strtolower($operator) == 'has') 
675
-                {
676
-                    $sql              = $model->withTrashed()->has($key)->toSql();
677
-                    $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
678
-                    $conditionString .= rtrim(substr($sql, strpos($sql, 'exists')), ')') . ' and ' . $conditions['conditionString'] . ') {op} ';
679
-                    $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
680
-                }
681
-                else
682
-                {
683
-                    $conditionString  .= $key . ' ' . $operator . ' ? {op} ';
684
-                    $conditionValues[] = $value;
685
-                }
686
-            }
687
-        }
688
-        $conditionString = '(' . rtrim($conditionString, '{op} ') . ')';
689
-        return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
690
-    }
691
-
692
-    /**
693
-     * Wrap the given JSON selector.
694
-     *
695
-     * @param  string  $value
696
-     * @return string
697
-     */
698
-    protected function wrapJsonSelector($value)
699
-    {
700
-        $removeLast = strpos($value, ')');
701
-        $value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
702
-        $path       = explode('->', $value);
703
-        $field      = array_shift($path);
704
-        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
705
-            return '"'.$part.'"';
706
-        })->implode('.'));
652
+				if (strtolower($operator) == 'between') 
653
+				{
654
+					$conditionString  .= $key . ' >= ? and ';
655
+					$conditionValues[] = $value1;
656
+
657
+					$conditionString  .= $key . ' <= ? {op} ';
658
+					$conditionValues[] = $value2;
659
+				}
660
+				elseif (strtolower($operator) == 'in') 
661
+				{
662
+					$conditionValues  = array_merge($conditionValues, $value);
663
+					$inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
664
+					$conditionString .= $key . ' in (' . rtrim($inBindingsString, ',') . ') {op} ';
665
+				}
666
+				elseif (strtolower($operator) == 'null') 
667
+				{
668
+					$conditionString .= $key . ' is null {op} ';
669
+				}
670
+				elseif (strtolower($operator) == 'not null') 
671
+				{
672
+					$conditionString .= $key . ' is not null {op} ';
673
+				}
674
+				elseif (strtolower($operator) == 'has') 
675
+				{
676
+					$sql              = $model->withTrashed()->has($key)->toSql();
677
+					$conditions       = $this->constructConditions($value, $model->$key()->getRelated());
678
+					$conditionString .= rtrim(substr($sql, strpos($sql, 'exists')), ')') . ' and ' . $conditions['conditionString'] . ') {op} ';
679
+					$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
680
+				}
681
+				else
682
+				{
683
+					$conditionString  .= $key . ' ' . $operator . ' ? {op} ';
684
+					$conditionValues[] = $value;
685
+				}
686
+			}
687
+		}
688
+		$conditionString = '(' . rtrim($conditionString, '{op} ') . ')';
689
+		return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
690
+	}
691
+
692
+	/**
693
+	 * Wrap the given JSON selector.
694
+	 *
695
+	 * @param  string  $value
696
+	 * @return string
697
+	 */
698
+	protected function wrapJsonSelector($value)
699
+	{
700
+		$removeLast = strpos($value, ')');
701
+		$value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
702
+		$path       = explode('->', $value);
703
+		$field      = array_shift($path);
704
+		$result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
705
+			return '"'.$part.'"';
706
+		})->implode('.'));
707 707
         
708
-        return $removeLast === false ? $result : $result . ')';
709
-    }
710
-
711
-    /**
712
-     * Abstract method that return the necessary 
713
-     * information (full model namespace)
714
-     * needed to preform the previous actions.
715
-     * 
716
-     * @return string
717
-     */
718
-    abstract protected function getModel();
708
+		return $removeLast === false ? $result : $result . ')';
709
+	}
710
+
711
+	/**
712
+	 * Abstract method that return the necessary 
713
+	 * information (full model namespace)
714
+	 * needed to preform the previous actions.
715
+	 * 
716
+	 * @return string
717
+	 */
718
+	abstract protected function getModel();
719 719
 }
720 720
\ No newline at end of file
Please login to merge, or discard this patch.
src/Modules/V1/Reporting/Repositories/ReportRepository.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -4,67 +4,67 @@
 block discarded – undo
4 4
 
5 5
 class ReportRepository extends AbstractRepository
6 6
 {
7
-    /**
8
-     * Return the model full namespace.
9
-     * 
10
-     * @return string
11
-     */
12
-    protected function getModel()
13
-    {
14
-        return 'App\Modules\V1\Reporting\Report';
15
-    }
7
+	/**
8
+	 * Return the model full namespace.
9
+	 * 
10
+	 * @return string
11
+	 */
12
+	protected function getModel()
13
+	{
14
+		return 'App\Modules\V1\Reporting\Report';
15
+	}
16 16
 
17
-    /**
18
-     * Render the given report db view based on the given
19
-     * condition.
20
-     *
21
-     * @param  string  $reportName
22
-     * @param  array   $conditions array of conditions
23
-     * @param  integer $perPage
24
-     * @param  array   $relations
25
-     * @param  boolean   $skipPermission
26
-     * @return object
27
-     */
28
-    public function getReport($reportName, $conditions = false, $perPage = 0, $relations = [], $skipPermission = false)
29
-    {
30
-        /**
31
-         * Fetch the report from db.
32
-         */
33
-        $reportConditions = $this->constructConditions(['report_name' => $reportName], $this->model);
34
-        $report           = call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($reportConditions['conditionString'], $reportConditions['conditionValues'])->first();
17
+	/**
18
+	 * Render the given report db view based on the given
19
+	 * condition.
20
+	 *
21
+	 * @param  string  $reportName
22
+	 * @param  array   $conditions array of conditions
23
+	 * @param  integer $perPage
24
+	 * @param  array   $relations
25
+	 * @param  boolean   $skipPermission
26
+	 * @return object
27
+	 */
28
+	public function getReport($reportName, $conditions = false, $perPage = 0, $relations = [], $skipPermission = false)
29
+	{
30
+		/**
31
+		 * Fetch the report from db.
32
+		 */
33
+		$reportConditions = $this->constructConditions(['report_name' => $reportName], $this->model);
34
+		$report           = call_user_func_array("{$this->getModel()}::with", array($relations))->whereRaw($reportConditions['conditionString'], $reportConditions['conditionValues'])->first();
35 35
         
36
-        /**
37
-         * Check report existance and permission.
38
-         */
39
-        if ( ! $report) 
40
-        {
41
-            \ErrorHandler::notFound('report');
42
-        }
43
-        else if (! $skipPermission && ! \Core::users()->can($report->view_name, 'reports'))
44
-        {
45
-            \ErrorHandler::noPermissions();
46
-        }
36
+		/**
37
+		 * Check report existance and permission.
38
+		 */
39
+		if ( ! $report) 
40
+		{
41
+			\ErrorHandler::notFound('report');
42
+		}
43
+		else if (! $skipPermission && ! \Core::users()->can($report->view_name, 'reports'))
44
+		{
45
+			\ErrorHandler::noPermissions();
46
+		}
47 47
 
48
-        /**
49
-         * Fetch data from the report based on the given conditions.
50
-         */
51
-        $report = \DB::table($report->view_name);
52
-        unset($conditions['page']);
53
-        if (count($conditions))
54
-        {
55
-            $conditions = $this->constructConditions($conditions, $this->model);
56
-            $report->whereRaw($conditions['conditionString'], $conditions['conditionValues']);   
57
-        }
58
-        /**
59
-         * Paginate or all data.
60
-         */
61
-        if ($perPage) 
62
-        {
63
-            return $report->paginate($perPage);
64
-        }
65
-        else
66
-        {
67
-            return $report->get();  
68
-        }
69
-    }
48
+		/**
49
+		 * Fetch data from the report based on the given conditions.
50
+		 */
51
+		$report = \DB::table($report->view_name);
52
+		unset($conditions['page']);
53
+		if (count($conditions))
54
+		{
55
+			$conditions = $this->constructConditions($conditions, $this->model);
56
+			$report->whereRaw($conditions['conditionString'], $conditions['conditionValues']);   
57
+		}
58
+		/**
59
+		 * Paginate or all data.
60
+		 */
61
+		if ($perPage) 
62
+		{
63
+			return $report->paginate($perPage);
64
+		}
65
+		else
66
+		{
67
+			return $report->get();  
68
+		}
69
+	}
70 70
 }
Please login to merge, or discard this patch.
src/Modules/V1/Notifications/Notification.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -5,23 +5,23 @@
 block discarded – undo
5 5
 
6 6
 class Notification extends DatabaseNotification{
7 7
 
8
-    public function getCreatedAtAttribute($value)
9
-    {
10
-        return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
11
-    }
8
+	public function getCreatedAtAttribute($value)
9
+	{
10
+		return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
11
+	}
12 12
 
13
-    public function getUpdatedAtAttribute($value)
14
-    {
15
-        return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
16
-    }
13
+	public function getUpdatedAtAttribute($value)
14
+	{
15
+		return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
16
+	}
17 17
 
18
-    public function getDeletedAtAttribute($value)
19
-    {
20
-        return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
21
-    }
18
+	public function getDeletedAtAttribute($value)
19
+	{
20
+		return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
21
+	}
22 22
 
23
-    public function getReadAtAttribute($value)
24
-    {
25
-        return ! $value ? false : \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
26
-    }
23
+	public function getReadAtAttribute($value)
24
+	{
25
+		return ! $value ? false : \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
26
+	}
27 27
 }
Please login to merge, or discard this patch.
src/Modules/V1/Notifications/Http/Controllers/NotificationsController.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -7,60 +7,60 @@
 block discarded – undo
7 7
 
8 8
 class NotificationsController extends BaseApiController
9 9
 {
10
-    /**
11
-     * The name of the model that is used by the base api controller 
12
-     * to preform actions like (add, edit ... etc).
13
-     * @var string
14
-     */
15
-    protected $model            = 'notifications';
10
+	/**
11
+	 * The name of the model that is used by the base api controller 
12
+	 * to preform actions like (add, edit ... etc).
13
+	 * @var string
14
+	 */
15
+	protected $model            = 'notifications';
16 16
 
17
-    /**
18
-     * List of all route actions that the base api controller
19
-     * will skip permissions check for them.
20
-     * @var array
21
-     */
22
-    protected $skipPermissionCheck = ['markAsRead', 'markAllAsRead', 'list', 'unread'];
17
+	/**
18
+	 * List of all route actions that the base api controller
19
+	 * will skip permissions check for them.
20
+	 * @var array
21
+	 */
22
+	protected $skipPermissionCheck = ['markAsRead', 'markAllAsRead', 'list', 'unread'];
23 23
 
24
-    /**
25
-     * Retrieve all notifications of the logged in user.
26
-     * 
27
-     * @param  integer $perPage Number of rows per page default all data.
28
-     * @return \Illuminate\Http\Response
29
-     */
30
-    public function list($perPage = 0)
31
-    {
32
-        return \Response::json($this->repo->list($perPage), 200);
33
-    }
24
+	/**
25
+	 * Retrieve all notifications of the logged in user.
26
+	 * 
27
+	 * @param  integer $perPage Number of rows per page default all data.
28
+	 * @return \Illuminate\Http\Response
29
+	 */
30
+	public function list($perPage = 0)
31
+	{
32
+		return \Response::json($this->repo->list($perPage), 200);
33
+	}
34 34
 
35
-    /**
36
-     * Retrieve unread notifications of the logged in user.
37
-     * 
38
-     * @param  integer $perPage Number of rows per page default all data.
39
-     * @return \Illuminate\Http\Response
40
-     */
41
-    public function unread($perPage = 0)
42
-    {
43
-        return \Response::json($this->repo->unread($perPage), 200);
44
-    }
35
+	/**
36
+	 * Retrieve unread notifications of the logged in user.
37
+	 * 
38
+	 * @param  integer $perPage Number of rows per page default all data.
39
+	 * @return \Illuminate\Http\Response
40
+	 */
41
+	public function unread($perPage = 0)
42
+	{
43
+		return \Response::json($this->repo->unread($perPage), 200);
44
+	}
45 45
 
46
-    /**
47
-     * Mark the notification as read.
48
-     * 
49
-     * @param  integer  $id Id of the notification.
50
-     * @return \Illuminate\Http\Response
51
-     */
52
-    public function markAsRead($id)
53
-    {
54
-        return \Response::json($this->repo->markAsRead($id), 200);
55
-    }
46
+	/**
47
+	 * Mark the notification as read.
48
+	 * 
49
+	 * @param  integer  $id Id of the notification.
50
+	 * @return \Illuminate\Http\Response
51
+	 */
52
+	public function markAsRead($id)
53
+	{
54
+		return \Response::json($this->repo->markAsRead($id), 200);
55
+	}
56 56
 
57
-    /**
58
-     * Mark all notifications as read.
59
-     * 
60
-     * @return \Illuminate\Http\Response
61
-     */
62
-    public function markAllAsRead()
63
-    {
64
-        return \Response::json($this->repo->markAllAsRead(), 200);
65
-    }
57
+	/**
58
+	 * Mark all notifications as read.
59
+	 * 
60
+	 * @return \Illuminate\Http\Response
61
+	 */
62
+	public function markAllAsRead()
63
+	{
64
+		return \Response::json($this->repo->markAllAsRead(), 200);
65
+	}
66 66
 }
Please login to merge, or discard this patch.
src/Modules/V1/Acl/ModelObservers/AclUserObserver.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -5,56 +5,56 @@
 block discarded – undo
5 5
  */
6 6
 class AclUserObserver {
7 7
 
8
-    public function saving($model)
9
-    {
10
-        //
11
-    }
12
-
13
-    public function saved($model)
14
-    {
15
-        //
16
-    }
17
-
18
-    public function creating($model)
19
-    {
20
-        //
21
-    }
22
-
23
-    public function created($model)
24
-    {
25
-        //
26
-    }
27
-
28
-    public function updating($model)
29
-    {
30
-        //
31
-    }
32
-
33
-    public function updated($model)
34
-    {
35
-        //
36
-    }
37
-
38
-    public function deleting($model)
39
-    {
40
-        if ($model->getOriginal('id') == \Auth::id()) 
41
-        {
42
-            \ErrorHandler::noPermissions();
43
-        }
44
-    }
45
-
46
-    public function deleted($model)
47
-    {
48
-        //
49
-    }
50
-
51
-    public function restoring($model)
52
-    {
53
-        //
54
-    }
55
-
56
-    public function restored($model)
57
-    {
58
-        //
59
-    }
8
+	public function saving($model)
9
+	{
10
+		//
11
+	}
12
+
13
+	public function saved($model)
14
+	{
15
+		//
16
+	}
17
+
18
+	public function creating($model)
19
+	{
20
+		//
21
+	}
22
+
23
+	public function created($model)
24
+	{
25
+		//
26
+	}
27
+
28
+	public function updating($model)
29
+	{
30
+		//
31
+	}
32
+
33
+	public function updated($model)
34
+	{
35
+		//
36
+	}
37
+
38
+	public function deleting($model)
39
+	{
40
+		if ($model->getOriginal('id') == \Auth::id()) 
41
+		{
42
+			\ErrorHandler::noPermissions();
43
+		}
44
+	}
45
+
46
+	public function deleted($model)
47
+	{
48
+		//
49
+	}
50
+
51
+	public function restoring($model)
52
+	{
53
+		//
54
+	}
55
+
56
+	public function restored($model)
57
+	{
58
+		//
59
+	}
60 60
 }
61 61
\ No newline at end of file
Please login to merge, or discard this patch.
src/Modules/V1/Acl/AclUser.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -7,119 +7,119 @@
 block discarded – undo
7 7
 
8 8
 class AclUser extends User {
9 9
 
10
-    use SoftDeletes, HasApiTokens;
11
-    protected $table    = 'users';
12
-    protected $dates    = ['created_at', 'updated_at', 'deleted_at'];
13
-    protected $hidden   = ['password', 'remember_token','deleted_at', 'two_factor_code'];
14
-    protected $guarded  = ['id'];
15
-    protected $fillable = ['name', 'email', 'password'];
16
-    public $searchable  = ['name', 'email'];
10
+	use SoftDeletes, HasApiTokens;
11
+	protected $table    = 'users';
12
+	protected $dates    = ['created_at', 'updated_at', 'deleted_at'];
13
+	protected $hidden   = ['password', 'remember_token','deleted_at', 'two_factor_code'];
14
+	protected $guarded  = ['id'];
15
+	protected $fillable = ['name', 'email', 'password'];
16
+	public $searchable  = ['name', 'email'];
17 17
     
18
-    public function getCreatedAtAttribute($value)
19
-    {
20
-        return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
21
-    }
22
-
23
-    public function getUpdatedAtAttribute($value)
24
-    {
25
-        return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
26
-    }
27
-
28
-    public function getDeletedAtAttribute($value)
29
-    {
30
-        return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
31
-    }
32
-
33
-    /**
34
-     * Encrypt the password attribute before
35
-     * saving it in the storage.
36
-     * 
37
-     * @param string $value 
38
-     */
39
-    public function setPasswordAttribute($value)
40
-    {
41
-        $this->attributes['password'] = bcrypt($value);
42
-    }
43
-
44
-    /**
45
-     * Get the entity's notifications.
46
-     */
47
-    public function notifications()
48
-    {
49
-        return $this->morphMany('\App\Modules\V1\Notifications\Notification', 'notifiable')->orderBy('created_at', 'desc');
50
-    }
51
-
52
-    /**
53
-     * Get the entity's read notifications.
54
-     */
55
-    public function readNotifications()
56
-    {
57
-        return $this->notifications()->whereNotNull('read_at');
58
-    }
59
-
60
-    /**
61
-     * Get the entity's unread notifications.
62
-     */
63
-    public function unreadNotifications()
64
-    {
65
-        return $this->notifications()->whereNull('read_at');
66
-    }
67
-
68
-    public function groups()
69
-    {
70
-        return $this->belongsToMany('\App\Modules\V1\Acl\AclGroup','users_groups','user_id','group_id')->whereNull('users_groups.deleted_at')->withTimestamps();
71
-    }
72
-
73
-    public function oauthClients()
74
-    {
75
-        return $this->hasMany('App\Modules\V1\Acl\OauthClient', 'user_id');
76
-    }
77
-
78
-    /**
79
-     * Return fcm device tokens that will be used in sending fcm notifications.
80
-     * 
81
-     * @return array
82
-     */
83
-    public function routeNotificationForFCM()
84
-    {
85
-        $devices = \Core::pushNotificationsDevices()->findBy(['user_id' => $this->id]);
86
-        $tokens  = [];
87
-
88
-        foreach ($devices as $device) 
89
-        {
90
-            $accessToken = decrypt($device->access_token);
91
-
92
-            try
93
-            {
94
-                if (\Core::users()->accessTokenExpiredOrRevoked($accessToken)) 
95
-                {
96
-                    continue;
97
-                }
98
-
99
-                $tokens[] = $device->device_token;
100
-            } 
101
-            catch (\Exception $e) 
102
-            {
103
-                $device->forceDelete();
104
-            }
105
-        }
106
-
107
-        return $tokens;
108
-    }
109
-
110
-    /**
111
-     * The channels the user receives notification broadcasts on.
112
-     *
113
-     * @return string
114
-     */
115
-    public function receivesBroadcastNotificationsOn()
116
-    {
117
-        return 'users.' . $this->id;
118
-    }
18
+	public function getCreatedAtAttribute($value)
19
+	{
20
+		return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
21
+	}
22
+
23
+	public function getUpdatedAtAttribute($value)
24
+	{
25
+		return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
26
+	}
27
+
28
+	public function getDeletedAtAttribute($value)
29
+	{
30
+		return \Carbon\Carbon::parse($value)->addHours(\Session::get('timeZoneDiff'))->toDateTimeString();
31
+	}
32
+
33
+	/**
34
+	 * Encrypt the password attribute before
35
+	 * saving it in the storage.
36
+	 * 
37
+	 * @param string $value 
38
+	 */
39
+	public function setPasswordAttribute($value)
40
+	{
41
+		$this->attributes['password'] = bcrypt($value);
42
+	}
43
+
44
+	/**
45
+	 * Get the entity's notifications.
46
+	 */
47
+	public function notifications()
48
+	{
49
+		return $this->morphMany('\App\Modules\V1\Notifications\Notification', 'notifiable')->orderBy('created_at', 'desc');
50
+	}
51
+
52
+	/**
53
+	 * Get the entity's read notifications.
54
+	 */
55
+	public function readNotifications()
56
+	{
57
+		return $this->notifications()->whereNotNull('read_at');
58
+	}
59
+
60
+	/**
61
+	 * Get the entity's unread notifications.
62
+	 */
63
+	public function unreadNotifications()
64
+	{
65
+		return $this->notifications()->whereNull('read_at');
66
+	}
67
+
68
+	public function groups()
69
+	{
70
+		return $this->belongsToMany('\App\Modules\V1\Acl\AclGroup','users_groups','user_id','group_id')->whereNull('users_groups.deleted_at')->withTimestamps();
71
+	}
72
+
73
+	public function oauthClients()
74
+	{
75
+		return $this->hasMany('App\Modules\V1\Acl\OauthClient', 'user_id');
76
+	}
77
+
78
+	/**
79
+	 * Return fcm device tokens that will be used in sending fcm notifications.
80
+	 * 
81
+	 * @return array
82
+	 */
83
+	public function routeNotificationForFCM()
84
+	{
85
+		$devices = \Core::pushNotificationsDevices()->findBy(['user_id' => $this->id]);
86
+		$tokens  = [];
87
+
88
+		foreach ($devices as $device) 
89
+		{
90
+			$accessToken = decrypt($device->access_token);
91
+
92
+			try
93
+			{
94
+				if (\Core::users()->accessTokenExpiredOrRevoked($accessToken)) 
95
+				{
96
+					continue;
97
+				}
98
+
99
+				$tokens[] = $device->device_token;
100
+			} 
101
+			catch (\Exception $e) 
102
+			{
103
+				$device->forceDelete();
104
+			}
105
+		}
106
+
107
+		return $tokens;
108
+	}
109
+
110
+	/**
111
+	 * The channels the user receives notification broadcasts on.
112
+	 *
113
+	 * @return string
114
+	 */
115
+	public function receivesBroadcastNotificationsOn()
116
+	{
117
+		return 'users.' . $this->id;
118
+	}
119 119
     
120
-    public static function boot()
121
-    {
122
-        parent::boot();
123
-        parent::observe(\App::make('App\Modules\V1\Acl\ModelObservers\AclUserObserver'));
124
-    }
120
+	public static function boot()
121
+	{
122
+		parent::boot();
123
+		parent::observe(\App::make('App\Modules\V1\Acl\ModelObservers\AclUserObserver'));
124
+	}
125 125
 }
Please login to merge, or discard this patch.