Completed
Push — master ( 91df31...876b8b )
by Sherif
01:12
created
src/Modules/Users/Database/Factories/UserFactory.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -7,27 +7,27 @@
 block discarded – undo
7 7
 
8 8
 class UserFactory extends Factory
9 9
 {
10
-    /**
11
-     * The name of the factory's corresponding model.
12
-     *
13
-     * @var string
14
-     */
15
-    protected $model = AclUser::class;
10
+	/**
11
+	 * The name of the factory's corresponding model.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $model = AclUser::class;
16 16
 
17
-    /**
18
-     * Define the model's default state.
19
-     *
20
-     * @return array
21
-     */
22
-    public function definition()
23
-    {
24
-        return [
25
-            'profile_picture' => 'https://picsum.photos/200/300',
26
-            'name'            => $this->faker->name(),
27
-            'email'           => $this->faker->safeEmail(),
28
-            'password'        => 123456,
29
-            'created_at'      => $this->faker->dateTimeBetween('-1 years', 'now'),
30
-            'updated_at'      => $this->faker->dateTimeBetween('-1 years', 'now')
31
-        ];
32
-    }
17
+	/**
18
+	 * Define the model's default state.
19
+	 *
20
+	 * @return array
21
+	 */
22
+	public function definition()
23
+	{
24
+		return [
25
+			'profile_picture' => 'https://picsum.photos/200/300',
26
+			'name'            => $this->faker->name(),
27
+			'email'           => $this->faker->safeEmail(),
28
+			'password'        => 123456,
29
+			'created_at'      => $this->faker->dateTimeBetween('-1 years', 'now'),
30
+			'updated_at'      => $this->faker->dateTimeBetween('-1 years', 'now')
31
+		];
32
+	}
33 33
 }
Please login to merge, or discard this patch.
src/Modules/Permissions/Providers/ModuleServiceProvider.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -6,29 +6,29 @@
 block discarded – undo
6 6
 
7 7
 class ModuleServiceProvider extends ServiceProvider
8 8
 {
9
-    /**
10
-     * Bootstrap the module services.
11
-     *
12
-     * @return void
13
-     */
14
-    public function boot()
15
-    {
16
-        $this->loadTranslationsFrom(__DIR__.'/../Resources/Lang', 'permissions');
17
-        $this->loadViewsFrom(__DIR__.'/../Resources/Views', 'permissions');
9
+	/**
10
+	 * Bootstrap the module services.
11
+	 *
12
+	 * @return void
13
+	 */
14
+	public function boot()
15
+	{
16
+		$this->loadTranslationsFrom(__DIR__.'/../Resources/Lang', 'permissions');
17
+		$this->loadViewsFrom(__DIR__.'/../Resources/Views', 'permissions');
18 18
 
19
-        $this->loadMigrationsFrom(module_path('permissions', 'Database/Migrations', 'app'));
20
-        if (!$this->app->configurationIsCached()) {
21
-            $this->loadConfigsFrom(module_path('permissions', 'Config', 'app'));
22
-        }
23
-    }
19
+		$this->loadMigrationsFrom(module_path('permissions', 'Database/Migrations', 'app'));
20
+		if (!$this->app->configurationIsCached()) {
21
+			$this->loadConfigsFrom(module_path('permissions', 'Config', 'app'));
22
+		}
23
+	}
24 24
 
25
-    /**
26
-     * Register the module services.
27
-     *
28
-     * @return void
29
-     */
30
-    public function register()
31
-    {
32
-        $this->app->register(RouteServiceProvider::class);
33
-    }
25
+	/**
26
+	 * Register the module services.
27
+	 *
28
+	 * @return void
29
+	 */
30
+	public function register()
31
+	{
32
+		$this->app->register(RouteServiceProvider::class);
33
+	}
34 34
 }
Please login to merge, or discard this patch.
src/Modules/Permissions/Database/Factories/PermissionFactory.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -7,25 +7,25 @@
 block discarded – undo
7 7
 
8 8
 class PermissionFactory extends Factory
9 9
 {
10
-    /**
11
-     * The name of the factory's corresponding model.
12
-     *
13
-     * @var string
14
-     */
15
-    protected $model = Permission::class;
10
+	/**
11
+	 * The name of the factory's corresponding model.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $model = Permission::class;
16 16
 
17
-    /**
18
-     * Define the model's default state.
19
-     *
20
-     * @return array
21
-     */
22
-    public function definition()
23
-    {
24
-        return [
25
-            'name'       => $this->faker->randomElement(['save', 'delete', 'find', 'paginate']),
26
-            'model'      => $this->faker->randomElement(['users', 'roles', 'settings', 'notifications']),
27
-            'created_at' => $this->faker->dateTimeBetween('-1 years', 'now'),
28
-            'updated_at' => $this->faker->dateTimeBetween('-1 years', 'now')
29
-        ];
30
-    }
17
+	/**
18
+	 * Define the model's default state.
19
+	 *
20
+	 * @return array
21
+	 */
22
+	public function definition()
23
+	{
24
+		return [
25
+			'name'       => $this->faker->randomElement(['save', 'delete', 'find', 'paginate']),
26
+			'model'      => $this->faker->randomElement(['users', 'roles', 'settings', 'notifications']),
27
+			'created_at' => $this->faker->dateTimeBetween('-1 years', 'now'),
28
+			'updated_at' => $this->faker->dateTimeBetween('-1 years', 'now')
29
+		];
30
+	}
31 31
 }
Please login to merge, or discard this patch.
src/Modules/Core/Config/core.php 1 patch
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 
3 3
 return [
4 4
 
5
-    /*
5
+	/*
6 6
     |--------------------------------------------------------------------------
7 7
     | Relations Between Models
8 8
     |--------------------------------------------------------------------------
@@ -11,43 +11,43 @@  discard block
 block discarded – undo
11 11
     |
12 12
     */
13 13
     
14
-    'relations' => [
15
-        'user' => [
16
-            'index' => [],
17
-            'show' => [],
18
-            'account' => [],
19
-        ],
20
-        'permission' => [
21
-            'index' => [],
22
-            'show' => [],
23
-        ],
24
-        'role' => [
25
-            'index' => [],
26
-            'show' => [],
27
-        ],
28
-        'oauthClient' => [
29
-            'index' => [],
30
-            'show' => [],
31
-        ],
32
-        'notification' => [
33
-            'index' => [],
34
-            'unread' => [],
35
-        ],
36
-        'pushNotificationDevice' => [
37
-            'index' => [],
38
-            'show' => [],
39
-        ],
40
-        'report' => [
41
-            'index' => [],
42
-            'show' => [],
43
-        ],
44
-        'setting' => [
45
-            'index' => [],
46
-            'show' => [],
47
-        ],
48
-    ],
14
+	'relations' => [
15
+		'user' => [
16
+			'index' => [],
17
+			'show' => [],
18
+			'account' => [],
19
+		],
20
+		'permission' => [
21
+			'index' => [],
22
+			'show' => [],
23
+		],
24
+		'role' => [
25
+			'index' => [],
26
+			'show' => [],
27
+		],
28
+		'oauthClient' => [
29
+			'index' => [],
30
+			'show' => [],
31
+		],
32
+		'notification' => [
33
+			'index' => [],
34
+			'unread' => [],
35
+		],
36
+		'pushNotificationDevice' => [
37
+			'index' => [],
38
+			'show' => [],
39
+		],
40
+		'report' => [
41
+			'index' => [],
42
+			'show' => [],
43
+		],
44
+		'setting' => [
45
+			'index' => [],
46
+			'show' => [],
47
+		],
48
+	],
49 49
 
50
-    /*
50
+	/*
51 51
     |--------------------------------------------------------------------------
52 52
     | Cache Configurations
53 53
     |--------------------------------------------------------------------------
@@ -56,40 +56,40 @@  discard block
 block discarded – undo
56 56
     |
57 57
     */
58 58
 
59
-    'cache_config' => [
60
-        'oauthClient' => [
61
-            'cache' => [
62
-                'list',
63
-                'find',
64
-                'findBy',
65
-                'paginate',
66
-                'paginateBy',
67
-                'first',
68
-                'deleted'
69
-            ],
70
-            'clear' => [
71
-                'save' => ['oauthClient'],
72
-                'delete' => ['oauthClient'],
73
-                'restore' => ['oauthClient'],
74
-                'revoke' => ['oauthClient'],
75
-                'ubRevoke' => ['oauthClient'],
76
-                'regenerateSecret' => ['oauthClient'],
77
-            ],
78
-        ],
79
-        'setting' => [
80
-            'cache' => [
81
-                'list',
82
-                'find',
83
-                'findBy',
84
-                'paginate',
85
-                'paginateBy',
86
-                'first',
87
-                'deleted'
88
-            ],
89
-            'clear' => [
90
-                'save' => ['setting'],
91
-                'saveMany' => ['setting'],
92
-            ]
93
-        ]
94
-    ]
59
+	'cache_config' => [
60
+		'oauthClient' => [
61
+			'cache' => [
62
+				'list',
63
+				'find',
64
+				'findBy',
65
+				'paginate',
66
+				'paginateBy',
67
+				'first',
68
+				'deleted'
69
+			],
70
+			'clear' => [
71
+				'save' => ['oauthClient'],
72
+				'delete' => ['oauthClient'],
73
+				'restore' => ['oauthClient'],
74
+				'revoke' => ['oauthClient'],
75
+				'ubRevoke' => ['oauthClient'],
76
+				'regenerateSecret' => ['oauthClient'],
77
+			],
78
+		],
79
+		'setting' => [
80
+			'cache' => [
81
+				'list',
82
+				'find',
83
+				'findBy',
84
+				'paginate',
85
+				'paginateBy',
86
+				'first',
87
+				'deleted'
88
+			],
89
+			'clear' => [
90
+				'save' => ['setting'],
91
+				'saveMany' => ['setting'],
92
+			]
93
+		]
94
+	]
95 95
 ];
Please login to merge, or discard this patch.
src/Modules/Core/Providers/ModuleServiceProvider.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -6,50 +6,50 @@
 block discarded – undo
6 6
 
7 7
 class ModuleServiceProvider extends ServiceProvider
8 8
 {
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');
18
-
19
-        $this->loadMigrationsFrom(module_path('core', 'Database/Migrations', 'app'));
20
-        if (!$this->app->configurationIsCached()) {
21
-            $this->loadConfigsFrom(module_path('core', 'Config', 'app'));
22
-        }
23
-    }
24
-
25
-    /**
26
-     * Register the module services.
27
-     *
28
-     * @return void
29
-     */
30
-    public function register()
31
-    {
32
-        //Bind Core Facade to the Service Container
33
-        $this->app->singleton('Core', function () {
34
-            return new \App\Modules\Core\Core;
35
-        });
36
-
37
-        //Bind Errors Facade to the Service Container
38
-        $this->app->singleton('Errors', function () {
39
-            return new \App\Modules\Core\Errors\Errors;
40
-        });
41
-
42
-        //Bind Media Facade to the Service Container
43
-        $this->app->singleton('Media', function () {
44
-            return new \App\Modules\Core\Utl\Media;
45
-        });
46
-
47
-        //Bind ApiConsumer Facade to the Service Container
48
-        $this->app->singleton('ApiConsumer', function () {
49
-            $app = app();
50
-            return new \App\Modules\Core\Utl\ApiConsumer($app, $app['request'], $app['router']);
51
-        });
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');
18
+
19
+		$this->loadMigrationsFrom(module_path('core', 'Database/Migrations', 'app'));
20
+		if (!$this->app->configurationIsCached()) {
21
+			$this->loadConfigsFrom(module_path('core', 'Config', 'app'));
22
+		}
23
+	}
24
+
25
+	/**
26
+	 * Register the module services.
27
+	 *
28
+	 * @return void
29
+	 */
30
+	public function register()
31
+	{
32
+		//Bind Core Facade to the Service Container
33
+		$this->app->singleton('Core', function () {
34
+			return new \App\Modules\Core\Core;
35
+		});
36
+
37
+		//Bind Errors Facade to the Service Container
38
+		$this->app->singleton('Errors', function () {
39
+			return new \App\Modules\Core\Errors\Errors;
40
+		});
41
+
42
+		//Bind Media Facade to the Service Container
43
+		$this->app->singleton('Media', function () {
44
+			return new \App\Modules\Core\Utl\Media;
45
+		});
46
+
47
+		//Bind ApiConsumer Facade to the Service Container
48
+		$this->app->singleton('ApiConsumer', function () {
49
+			$app = app();
50
+			return new \App\Modules\Core\Utl\ApiConsumer($app, $app['request'], $app['router']);
51
+		});
52 52
         
53
-        $this->app->register(RouteServiceProvider::class);
54
-    }
53
+		$this->app->register(RouteServiceProvider::class);
54
+	}
55 55
 }
Please login to merge, or discard this patch.
src/Modules/Core/Http/Middleware/CheckPermissions.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -11,68 +11,68 @@
 block discarded – undo
11 11
 
12 12
 class CheckPermissions
13 13
 {
14
-    protected $route;
15
-    protected $auth;
16
-    protected $authMiddleware;
17
-    protected $userService;
18
-    protected $arr;
14
+	protected $route;
15
+	protected $auth;
16
+	protected $authMiddleware;
17
+	protected $userService;
18
+	protected $arr;
19 19
     
20
-    /**
21
-     * Init new object.
22
-     *
23
-     * @param   Route          $route
24
-     * @param   Auth           $auth
25
-     * @param   AuthMiddleware $authMiddleware
26
-     * @param   UserService    $userService
27
-     * @param   Arr            $arr
28
-     *
29
-     * @return  void
30
-     */
31
-    public function __construct(Route $route, Auth $auth, AuthMiddleware $authMiddleware, UserService $userService, Arr $arr)
32
-    {
33
-        $this->route = $route;
34
-        $this->auth = $auth;
35
-        $this->authMiddleware = $authMiddleware;
36
-        $this->userService = $userService;
37
-        $this->arr = $arr;
38
-    }
20
+	/**
21
+	 * Init new object.
22
+	 *
23
+	 * @param   Route          $route
24
+	 * @param   Auth           $auth
25
+	 * @param   AuthMiddleware $authMiddleware
26
+	 * @param   UserService    $userService
27
+	 * @param   Arr            $arr
28
+	 *
29
+	 * @return  void
30
+	 */
31
+	public function __construct(Route $route, Auth $auth, AuthMiddleware $authMiddleware, UserService $userService, Arr $arr)
32
+	{
33
+		$this->route = $route;
34
+		$this->auth = $auth;
35
+		$this->authMiddleware = $authMiddleware;
36
+		$this->userService = $userService;
37
+		$this->arr = $arr;
38
+	}
39 39
 
40
-    /**
41
-     * Handle an incoming request.
42
-     *
43
-     * @param  \Illuminate\Http\Request  $request
44
-     * @param  \Closure  $next
45
-     * @return mixed
46
-     */
47
-    public function handle($request, Closure $next)
48
-    {
49
-        $routeActions        = explode('@', $this->route->currentRouteAction());
50
-        $reflectionClass     = new \ReflectionClass($routeActions[0]);
51
-        $classProperties     = $reflectionClass->getDefaultProperties();
52
-        $skipPermissionCheck = $this->arr->get($classProperties, 'skipPermissionCheck', []);
53
-        $skipLoginCheck      = $this->arr->get($classProperties, 'skipLoginCheck', []);
54
-        $modelName           = explode('\\', $routeActions[0]);
55
-        $modelName           = lcfirst(str_replace('Controller', '', end($modelName)));
56
-        $permission          = $routeActions[1];
40
+	/**
41
+	 * Handle an incoming request.
42
+	 *
43
+	 * @param  \Illuminate\Http\Request  $request
44
+	 * @param  \Closure  $next
45
+	 * @return mixed
46
+	 */
47
+	public function handle($request, Closure $next)
48
+	{
49
+		$routeActions        = explode('@', $this->route->currentRouteAction());
50
+		$reflectionClass     = new \ReflectionClass($routeActions[0]);
51
+		$classProperties     = $reflectionClass->getDefaultProperties();
52
+		$skipPermissionCheck = $this->arr->get($classProperties, 'skipPermissionCheck', []);
53
+		$skipLoginCheck      = $this->arr->get($classProperties, 'skipLoginCheck', []);
54
+		$modelName           = explode('\\', $routeActions[0]);
55
+		$modelName           = lcfirst(str_replace('Controller', '', end($modelName)));
56
+		$permission          = $routeActions[1];
57 57
 
58
-        $this->auth->shouldUse('api');
59
-        if (! in_array($permission, $skipLoginCheck)) {
60
-            $this->authMiddleware->handle($request, function ($request) use ($modelName, $skipPermissionCheck, $permission) {
61
-                $user             = $this->auth->user();
62
-                $isPasswordClient = $user->token() ? $user->token()->client->password_client : false;
58
+		$this->auth->shouldUse('api');
59
+		if (! in_array($permission, $skipLoginCheck)) {
60
+			$this->authMiddleware->handle($request, function ($request) use ($modelName, $skipPermissionCheck, $permission) {
61
+				$user             = $this->auth->user();
62
+				$isPasswordClient = $user->token() ? $user->token()->client->password_client : false;
63 63
     
64
-                if ($user->blocked) {
65
-                    \Errors::userIsBlocked();
66
-                }
64
+				if ($user->blocked) {
65
+					\Errors::userIsBlocked();
66
+				}
67 67
     
68
-                if ($isPasswordClient && (in_array($permission, $skipPermissionCheck) || $this->userService->can($permission, $modelName))) {
69
-                } elseif (! $isPasswordClient && $user->tokenCan($modelName.'-'.$permission)) {
70
-                } else {
71
-                    \Errors::noPermissions();
72
-                }
73
-            });
74
-        }
68
+				if ($isPasswordClient && (in_array($permission, $skipPermissionCheck) || $this->userService->can($permission, $modelName))) {
69
+				} elseif (! $isPasswordClient && $user->tokenCan($modelName.'-'.$permission)) {
70
+				} else {
71
+					\Errors::noPermissions();
72
+				}
73
+			});
74
+		}
75 75
 
76
-        return $next($request);
77
-    }
76
+		return $next($request);
77
+	}
78 78
 }
Please login to merge, or discard this patch.
src/Modules/Core/BaseClasses/BaseRepository.php 1 patch
Indentation   +664 added lines, -664 removed lines patch added patch discarded remove patch
@@ -8,681 +8,681 @@
 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 = false)
84
-    {
85
-        if($conditions) {
86
-            $conditions = $this->constructConditions($conditions, $this->model);
87
-            return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->count();
88
-        }
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 = false)
84
+	{
85
+		if($conditions) {
86
+			$conditions = $this->constructConditions($conditions, $this->model);
87
+			return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->count();
88
+		}
89 89
         
90
-        return $this->model->count();
91
-    }
92
-
93
-    /**
94
-     * Return max value for the given column.
95
-     *
96
-     * @param  column
97
-     * @return integer
98
-     */
99
-    public function max($column)
100
-    {
101
-        return $this->model->max($column);
102
-    }
103
-
104
-    /**
105
-     * Pluck column based on the given condition from storage.
106
-     *
107
-     * @param  array   $conditions array of conditions
108
-     * @param  string   $column
109
-     * @return collection
110
-     */
111
-    public function pluck($conditions, $column)
112
-    {
113
-        $conditions = $this->constructConditions($conditions, $this->model);
114
-        return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->pluck($column);
115
-    }
116
-
117
-    /**
118
-     * Update the given data based on the given conditions.
119
-     *
120
-     * @param  array   $conditions array of conditions
121
-     * @param  array   $data
122
-     * @return collection
123
-     */
124
-    public function update($conditions, $data)
125
-    {
126
-        $conditions = $this->constructConditions($conditions, $this->model);
127
-        return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->update($data);
128
-    }
90
+		return $this->model->count();
91
+	}
92
+
93
+	/**
94
+	 * Return max value for the given column.
95
+	 *
96
+	 * @param  column
97
+	 * @return integer
98
+	 */
99
+	public function max($column)
100
+	{
101
+		return $this->model->max($column);
102
+	}
103
+
104
+	/**
105
+	 * Pluck column based on the given condition from storage.
106
+	 *
107
+	 * @param  array   $conditions array of conditions
108
+	 * @param  string   $column
109
+	 * @return collection
110
+	 */
111
+	public function pluck($conditions, $column)
112
+	{
113
+		$conditions = $this->constructConditions($conditions, $this->model);
114
+		return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->pluck($column);
115
+	}
116
+
117
+	/**
118
+	 * Update the given data based on the given conditions.
119
+	 *
120
+	 * @param  array   $conditions array of conditions
121
+	 * @param  array   $data
122
+	 * @return collection
123
+	 */
124
+	public function update($conditions, $data)
125
+	{
126
+		$conditions = $this->constructConditions($conditions, $this->model);
127
+		return $this->model->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->update($data);
128
+	}
129 129
     
130
-    /**
131
-     * Save the given model to the storage.
132
-     *
133
-     * @param  array $data
134
-     * @return mixed
135
-     */
136
-    public function save(array $data)
137
-    {
138
-        $local = \Session::get('locale');
139
-        \Session::put('locale', 'all');
140
-        $model      = false;
141
-        $relations  = [];
142
-
143
-        \DB::transaction(function () use (&$model, &$relations, $data) {
130
+	/**
131
+	 * Save the given model to the storage.
132
+	 *
133
+	 * @param  array $data
134
+	 * @return mixed
135
+	 */
136
+	public function save(array $data)
137
+	{
138
+		$local = \Session::get('locale');
139
+		\Session::put('locale', 'all');
140
+		$model      = false;
141
+		$relations  = [];
142
+
143
+		\DB::transaction(function () use (&$model, &$relations, $data) {
144 144
             
145
-            $model     = $this->prepareModel($data);
146
-            $relations = $this->prepareRelations($data, $model);
147
-            $model     = $this->saveModel($model, $relations);
148
-        });
149
-        \Session::put('locale', $local);
145
+			$model     = $this->prepareModel($data);
146
+			$relations = $this->prepareRelations($data, $model);
147
+			$model     = $this->saveModel($model, $relations);
148
+		});
149
+		\Session::put('locale', $local);
150 150
         
151
-        if (count($relations)) {
152
-            $model->load(...array_keys($relations));
153
-        }
151
+		if (count($relations)) {
152
+			$model->load(...array_keys($relations));
153
+		}
154 154
 
155
-        return $model;
156
-    }
155
+		return $model;
156
+	}
157 157
     
158
-    /**
159
-     * Insert the given model/models to the storage.
160
-     *
161
-     * @param  array $data
162
-     * @return mixed
163
-     */
164
-    public function insert(array $data)
165
-    {
166
-        return $this->model->insert($data);
167
-    }
168
-
169
-    /**
170
-     * Delete record from the storage based on the given
171
-     * condition.
172
-     *
173
-     * @param  var $value condition value
174
-     * @param  string $attribute condition column name
175
-     * @return void
176
-     */
177
-    public function delete($value, $attribute = 'id')
178
-    {
179
-        \DB::transaction(function () use ($value, $attribute) {
180
-            $this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
181
-                $model->delete();
182
-            });
183
-        });
184
-    }
158
+	/**
159
+	 * Insert the given model/models to the storage.
160
+	 *
161
+	 * @param  array $data
162
+	 * @return mixed
163
+	 */
164
+	public function insert(array $data)
165
+	{
166
+		return $this->model->insert($data);
167
+	}
168
+
169
+	/**
170
+	 * Delete record from the storage based on the given
171
+	 * condition.
172
+	 *
173
+	 * @param  var $value condition value
174
+	 * @param  string $attribute condition column name
175
+	 * @return void
176
+	 */
177
+	public function delete($value, $attribute = 'id')
178
+	{
179
+		\DB::transaction(function () use ($value, $attribute) {
180
+			$this->model->where($attribute, '=', $value)->lockForUpdate()->get()->each(function ($model) {
181
+				$model->delete();
182
+			});
183
+		});
184
+	}
185 185
     
186
-    /**
187
-     * Fetch records from the storage based on the given
188
-     * id.
189
-     *
190
-     * @param  integer $id
191
-     * @param  string[]   $relations
192
-     * @param  array   $columns
193
-     * @return object
194
-     */
195
-    public function find($id, $relations = [], $columns = ['*'])
196
-    {
197
-        return $this->model->with($relations)->find($id, $columns);
198
-    }
186
+	/**
187
+	 * Fetch records from the storage based on the given
188
+	 * id.
189
+	 *
190
+	 * @param  integer $id
191
+	 * @param  string[]   $relations
192
+	 * @param  array   $columns
193
+	 * @return object
194
+	 */
195
+	public function find($id, $relations = [], $columns = ['*'])
196
+	{
197
+		return $this->model->with($relations)->find($id, $columns);
198
+	}
199 199
     
200
-    /**
201
-     * Fetch records from the storage based on the given
202
-     * condition.
203
-     *
204
-     * @param  array   $conditions array of conditions
205
-     * @param  array   $relations
206
-     * @param  string  $sortBy
207
-     * @param  boolean $desc
208
-     * @param  array   $columns
209
-     * @return collection
210
-     */
211
-    public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
212
-    {
213
-        $conditions = $this->constructConditions($conditions, $this->model);
214
-        $sort       = $desc ? 'desc' : 'asc';
215
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
216
-    }
217
-
218
-    /**
219
-     * Fetch the first record from the storage based on the given
220
-     * condition.
221
-     *
222
-     * @param  array   $conditions array of conditions
223
-     * @param  array   $relations
224
-     * @param  array   $columns
225
-     * @return object
226
-     */
227
-    public function first($conditions, $relations = [], $columns = ['*'])
228
-    {
229
-        $conditions = $this->constructConditions($conditions, $this->model);
230
-        return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
231
-    }
232
-
233
-    /**
234
-     * Return the deleted models in pages based on the given conditions.
235
-     *
236
-     * @param  array   $conditions array of conditions
237
-     * @param  integer $perPage
238
-     * @param  string  $sortBy
239
-     * @param  boolean $desc
240
-     * @param  array   $columns
241
-     * @return collection
242
-     */
243
-    public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = ['*'])
244
-    {
245
-        unset($conditions['page']);
246
-        unset($conditions['perPage']);
247
-        unset($conditions['sortBy']);
248
-        unset($conditions['sort']);
249
-        $conditions = $this->constructConditions($conditions, $this->model);
250
-        $sort       = $desc ? 'desc' : 'asc';
251
-        $model      = $this->model->onlyTrashed();
252
-
253
-        if (count($conditions['conditionValues'])) {
254
-            $model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
255
-        }
256
-
257
-        return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
258
-    }
259
-
260
-    /**
261
-     * Restore the deleted model.
262
-     *
263
-     * @param  integer $id
264
-     * @return void
265
-     */
266
-    public function restore($id)
267
-    {
268
-        $model = $this->model->onlyTrashed()->find($id);
269
-
270
-        if (! $model) {
271
-            \Errors::notFound(class_basename($this->model).' with id : '.$id);
272
-        }
273
-
274
-        $model->restore();
275
-    }
276
-
277
-    /**
278
-     * Fill the model with the given data.
279
-     *
280
-     * @param   array  $data
281
-     *
282
-     * @return  object
283
-     */
284
-    public function prepareModel($data)
285
-    {
286
-        $modelClass = $this->model;
287
-
288
-        /**
289
-         * If the id is present in the data then select the model for updating,
290
-         * else create new model.
291
-         * @var array
292
-         */
293
-        $model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
294
-        if (! $model) {
295
-            \Errors::notFound(class_basename($modelClass).' with id : '.$data['id']);
296
-        }
297
-
298
-        /**
299
-         * Construct the model object with the given data,
300
-         * and if there is a relation add it to relations array,
301
-         * then save the model.
302
-         */
303
-        foreach ($data as $key => $value) {
304
-            if (array_search($key, $model->getFillable(), true) !== false) {
305
-                /**
306
-                 * If the attribute isn't a relation and prevent attributes not in the fillable.
307
-                 */
308
-                $model->$key = $value;
309
-            }
310
-        }
311
-
312
-        return $model;
313
-    }
200
+	/**
201
+	 * Fetch records from the storage based on the given
202
+	 * condition.
203
+	 *
204
+	 * @param  array   $conditions array of conditions
205
+	 * @param  array   $relations
206
+	 * @param  string  $sortBy
207
+	 * @param  boolean $desc
208
+	 * @param  array   $columns
209
+	 * @return collection
210
+	 */
211
+	public function findBy($conditions, $relations = [], $sortBy = 'created_at', $desc = 1, $columns = ['*'])
212
+	{
213
+		$conditions = $this->constructConditions($conditions, $this->model);
214
+		$sort       = $desc ? 'desc' : 'asc';
215
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->orderBy($sortBy, $sort)->get($columns);
216
+	}
217
+
218
+	/**
219
+	 * Fetch the first record from the storage based on the given
220
+	 * condition.
221
+	 *
222
+	 * @param  array   $conditions array of conditions
223
+	 * @param  array   $relations
224
+	 * @param  array   $columns
225
+	 * @return object
226
+	 */
227
+	public function first($conditions, $relations = [], $columns = ['*'])
228
+	{
229
+		$conditions = $this->constructConditions($conditions, $this->model);
230
+		return $this->model->with($relations)->whereRaw($conditions['conditionString'], $conditions['conditionValues'])->first($columns);
231
+	}
232
+
233
+	/**
234
+	 * Return the deleted models in pages based on the given conditions.
235
+	 *
236
+	 * @param  array   $conditions array of conditions
237
+	 * @param  integer $perPage
238
+	 * @param  string  $sortBy
239
+	 * @param  boolean $desc
240
+	 * @param  array   $columns
241
+	 * @return collection
242
+	 */
243
+	public function deleted($conditions, $perPage = 15, $sortBy = 'created_at', $desc = 1, $columns = ['*'])
244
+	{
245
+		unset($conditions['page']);
246
+		unset($conditions['perPage']);
247
+		unset($conditions['sortBy']);
248
+		unset($conditions['sort']);
249
+		$conditions = $this->constructConditions($conditions, $this->model);
250
+		$sort       = $desc ? 'desc' : 'asc';
251
+		$model      = $this->model->onlyTrashed();
252
+
253
+		if (count($conditions['conditionValues'])) {
254
+			$model->whereRaw($conditions['conditionString'], $conditions['conditionValues']);
255
+		}
256
+
257
+		return $model->orderBy($sortBy, $sort)->paginate($perPage, $columns);
258
+	}
259
+
260
+	/**
261
+	 * Restore the deleted model.
262
+	 *
263
+	 * @param  integer $id
264
+	 * @return void
265
+	 */
266
+	public function restore($id)
267
+	{
268
+		$model = $this->model->onlyTrashed()->find($id);
269
+
270
+		if (! $model) {
271
+			\Errors::notFound(class_basename($this->model).' with id : '.$id);
272
+		}
273
+
274
+		$model->restore();
275
+	}
276
+
277
+	/**
278
+	 * Fill the model with the given data.
279
+	 *
280
+	 * @param   array  $data
281
+	 *
282
+	 * @return  object
283
+	 */
284
+	public function prepareModel($data)
285
+	{
286
+		$modelClass = $this->model;
287
+
288
+		/**
289
+		 * If the id is present in the data then select the model for updating,
290
+		 * else create new model.
291
+		 * @var array
292
+		 */
293
+		$model = Arr::has($data, 'id') ? $modelClass->lockForUpdate()->find($data['id']) : new $modelClass;
294
+		if (! $model) {
295
+			\Errors::notFound(class_basename($modelClass).' with id : '.$data['id']);
296
+		}
297
+
298
+		/**
299
+		 * Construct the model object with the given data,
300
+		 * and if there is a relation add it to relations array,
301
+		 * then save the model.
302
+		 */
303
+		foreach ($data as $key => $value) {
304
+			if (array_search($key, $model->getFillable(), true) !== false) {
305
+				/**
306
+				 * If the attribute isn't a relation and prevent attributes not in the fillable.
307
+				 */
308
+				$model->$key = $value;
309
+			}
310
+		}
311
+
312
+		return $model;
313
+	}
314 314
     
315
-    /**
316
-     * Prepare related models based on the given data for the given model.
317
-     *
318
-     * @param   array  $data
319
-     * @param   object $model
320
-     *
321
-     * @return  array
322
-     */
323
-    public function prepareRelations($data, $model)
324
-    {
325
-        /**
326
-         * Init the relation array
327
-         *
328
-         * @var array
329
-         */
330
-        $relations = [];
331
-
332
-        /**
333
-         * Construct the model object with the given data,
334
-         * and if there is a relation add it to relations array,
335
-         * then save the model.
336
-         */
337
-        foreach ($data as $key => $value) {
338
-            /**
339
-             * If the attribute is a relation.
340
-             */
341
-            $relation = \Str::camel($key);
342
-            if (method_exists($model, $relation) && \Core::$relation()) {
343
-                /**
344
-                 * Check if the relation is a collection.
345
-                 */
346
-                if (class_basename($model->$relation) == 'Collection') {
347
-                    /**
348
-                     * If the relation has no value then marke the relation data
349
-                     * related to the model to be deleted.
350
-                     */
351
-                    if (! $value || ! count($value)) {
352
-                        $relations[$relation] = 'delete';
353
-                    }
354
-                }
355
-                if (is_array($value)) {
356
-                    /**
357
-                     * Loop through the relation data.
358
-                     */
359
-                    foreach ($value as $attr => $val) {
360
-                        /**
361
-                         * Get the relation model.
362
-                         */
363
-                        $relationBaseModel = \Core::$relation()->model;
364
-
365
-                        /**
366
-                         * Check if the relation is a collection.
367
-                         */
368
-                        if (class_basename($model->$relation) == 'Collection') {
369
-                            if (! is_array($val)) {
370
-                                $relationModel = $relationBaseModel->lockForUpdate()->find($val);
371
-                            } else {
372
-                                /**
373
-                                 * If the id is present in the data then select the relation model for updating,
374
-                                 * else create new model.
375
-                                 */
376
-                                $relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
377
-                            }
378
-
379
-                            /**
380
-                             * If model doesn't exists.
381
-                             */
382
-                            if (! $relationModel) {
383
-                                \Errors::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
384
-                            }
385
-
386
-                            if (is_array($val)) {
387
-                                /**
388
-                                 * Loop through the relation attributes.
389
-                                 */
390
-                                foreach ($val as $attr => $val) {
391
-                                    /**
392
-                                     * Prevent the sub relations or attributes not in the fillable.
393
-                                     */
394
-                                    if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false && class_basename($model->$key()) !== 'BelongsToMany') {
395
-                                        $relationModel->$attr = $val;
396
-                                    } elseif (gettype($val) !== 'object' && gettype($val) !== 'array' && $attr !== 'id') {
397
-                                        $extra[$attr] = $val;
398
-                                    }
399
-                                }
400
-                            }
401
-
402
-                            if (isset($extra)) {
403
-                                $relationModel->extra = $extra;
404
-                            }
405
-                            $relations[$relation][] = $relationModel;
406
-                        } else {
407
-                            /**
408
-                             * Prevent the sub relations.
409
-                             */
410
-                            if (gettype($val) !== 'object' && gettype($val) !== 'array') {
411
-                                /**
412
-                                 * If the id is present in the data then select the relation model for updating,
413
-                                 * else create new model.
414
-                                 */
415
-                                $relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
416
-
417
-                                /**
418
-                                 * If model doesn't exists.
419
-                                 */
420
-                                if (! $relationModel) {
421
-                                    \Errors::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
422
-                                }
423
-
424
-                                foreach ($value as $relationAttribute => $relationValue) {
425
-                                    /**
426
-                                     * Prevent attributes not in the fillable.
427
-                                     */
428
-                                    if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
429
-                                        $relationModel->$relationAttribute = $relationValue;
430
-                                    }
431
-                                }
432
-
433
-                                $relations[$relation] = $relationModel;
434
-                            }
435
-                        }
436
-                    }
437
-                }
438
-            }
439
-        }
440
-
441
-        return $relations;
442
-    }
443
-
444
-    /**
445
-     * Save the model with related models.
446
-     *
447
-     * @param   object  $model
448
-     * @param   array   $relations
449
-     *
450
-     * @return  object
451
-     */
452
-    public function saveModel($model, $relations)
453
-    {
454
-        /**
455
-         * Sort relations.
456
-         */
457
-        $belongsTo = [];
458
-        $hasOne = [];
459
-        $array = [];
460
-        foreach ($relations as $key => $value) {
461
-            if (class_basename($model->$key()) === 'BelongsTo') {
462
-                $belongsTo[$key] = $value;
463
-            } elseif (class_basename($model->$key()) === 'HasOne') {
464
-                $hasOne[$key] = $value;
465
-            } else {
466
-                $array[$key] = $value;
467
-            }
468
-        };
469
-
470
-        $relations = array_merge($belongsTo, $hasOne, $array);
471
-
472
-        /**
473
-         * Loop through the relations array.
474
-         */
475
-        foreach ($relations as $key => $value) {
476
-            /**
477
-             * If the relation is marked for delete then delete it.
478
-             */
479
-            if ($value == 'delete' && $model->$key()->count()) {
480
-                switch (class_basename($model->$key())) {
481
-                    /**
482
-                     * If the relation is one to many then delete all
483
-                     * relations who's id isn't in the ids array.
484
-                     */
485
-                    case 'HasMany':
486
-                        $model->$key()->delete();
487
-                        break;
488
-
489
-                    /**
490
-                     * If the relation is many to many then
491
-                     * detach the previous data and attach
492
-                     * the ids array to the model.
493
-                     */
494
-                    case 'BelongsToMany':
495
-                        $model->$key()->detach();
496
-                        break;
497
-                }
498
-            } elseif (gettype($value) == 'array') {
499
-                /**
500
-                 * Save the model.
501
-                 */
502
-                $model->save();
503
-                $ids = [];
504
-
505
-                /**
506
-                 * Loop through the relations.
507
-                 */
508
-                foreach ($value as $val) {
509
-                    switch (class_basename($model->$key())) {
510
-                        /**
511
-                         * If the relation is one to many then update it's foreign key with
512
-                         * the model id and save it then add its id to ids array to delete all
513
-                         * relations who's id isn't in the ids array.
514
-                         */
515
-                        case 'HasMany':
516
-                            $foreignKeyName       = $model->$key()->getForeignKeyName();
517
-                            $val->$foreignKeyName = $model->id;
518
-                            $val->save();
519
-                            $ids[] = $val->id;
520
-                            break;
521
-
522
-                        /**
523
-                         * If the relation is many to many then add it's id to the ids array to
524
-                         * attache these ids to the model.
525
-                         */
526
-                        case 'BelongsToMany':
527
-                        case 'MorphToMany':
528
-                            $extra = $val->extra;
529
-                            unset($val->extra);
530
-                            $val->save();
531
-                            $ids[$val->id] = $extra ?? [];
532
-                            break;
533
-                    }
534
-                }
535
-                switch (class_basename($model->$key())) {
536
-                    /**
537
-                     * If the relation is one to many then delete all
538
-                     * relations who's id isn't in the ids array.
539
-                     */
540
-                    case 'HasMany':
541
-                        $model->$key()->whereNotIn('id', $ids)->delete();
542
-                        break;
543
-
544
-                    /**
545
-                     * If the relation is many to many then
546
-                     * detach the previous data and attach
547
-                     * the ids array to the model.
548
-                     */
549
-                    case 'BelongsToMany':
550
-                    case 'MorphToMany':
551
-                        $model->$key()->detach();
552
-                        $model->$key()->attach($ids);
553
-                        break;
554
-                }
555
-            } else {
556
-                switch (class_basename($model->$key())) {
557
-                    /**
558
-                     * If the relation is one to one.
559
-                     */
560
-                    case 'HasOne':
561
-                        /**
562
-                         * Save the model.
563
-                         */
564
-                        $model->save();
565
-                        $foreignKeyName         = $model->$key()->getForeignKeyName();
566
-                        $value->$foreignKeyName = $model->id;
567
-                        $value->save();
568
-                        break;
569
-                    case 'BelongsTo':
570
-                        /**
571
-                         * Save the model.
572
-                         */
573
-                        $value->save();
574
-                        $model->$key()->associate($value);
575
-                        break;
576
-                }
577
-            }
578
-        }
579
-
580
-        /**
581
-         * Save the model.
582
-         */
583
-        $model->save();
584
-
585
-        return $model;
586
-    }
587
-
588
-    /**
589
-     * Build the conditions recursively for the retrieving methods.
590
-     * @param  array $conditions
591
-     * @return array
592
-     */
593
-    protected function constructConditions($conditions, $model)
594
-    {
595
-        $conditionString = '';
596
-        $conditionValues = [];
597
-        foreach ($conditions as $key => $value) {
598
-            if (Str::contains($key, '->')) {
599
-                $key = $this->wrapJsonSelector($key);
600
-            }
601
-
602
-            if ($key == 'and') {
603
-                $conditions       = $this->constructConditions($value, $model);
604
-                $conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
605
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
606
-            } elseif ($key == 'or') {
607
-                $conditions       = $this->constructConditions($value, $model);
608
-                $conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
609
-                $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
610
-            } else {
611
-                if (is_array($value)) {
612
-                    $operator = $value['op'];
613
-                    if (strtolower($operator) == 'between') {
614
-                        $value1 = $value['val1'];
615
-                        $value2 = $value['val2'];
616
-                    } else {
617
-                        $value = Arr::get($value, 'val', '');
618
-                    }
619
-                } else {
620
-                    $operator = '=';
621
-                }
315
+	/**
316
+	 * Prepare related models based on the given data for the given model.
317
+	 *
318
+	 * @param   array  $data
319
+	 * @param   object $model
320
+	 *
321
+	 * @return  array
322
+	 */
323
+	public function prepareRelations($data, $model)
324
+	{
325
+		/**
326
+		 * Init the relation array
327
+		 *
328
+		 * @var array
329
+		 */
330
+		$relations = [];
331
+
332
+		/**
333
+		 * Construct the model object with the given data,
334
+		 * and if there is a relation add it to relations array,
335
+		 * then save the model.
336
+		 */
337
+		foreach ($data as $key => $value) {
338
+			/**
339
+			 * If the attribute is a relation.
340
+			 */
341
+			$relation = \Str::camel($key);
342
+			if (method_exists($model, $relation) && \Core::$relation()) {
343
+				/**
344
+				 * Check if the relation is a collection.
345
+				 */
346
+				if (class_basename($model->$relation) == 'Collection') {
347
+					/**
348
+					 * If the relation has no value then marke the relation data
349
+					 * related to the model to be deleted.
350
+					 */
351
+					if (! $value || ! count($value)) {
352
+						$relations[$relation] = 'delete';
353
+					}
354
+				}
355
+				if (is_array($value)) {
356
+					/**
357
+					 * Loop through the relation data.
358
+					 */
359
+					foreach ($value as $attr => $val) {
360
+						/**
361
+						 * Get the relation model.
362
+						 */
363
+						$relationBaseModel = \Core::$relation()->model;
364
+
365
+						/**
366
+						 * Check if the relation is a collection.
367
+						 */
368
+						if (class_basename($model->$relation) == 'Collection') {
369
+							if (! is_array($val)) {
370
+								$relationModel = $relationBaseModel->lockForUpdate()->find($val);
371
+							} else {
372
+								/**
373
+								 * If the id is present in the data then select the relation model for updating,
374
+								 * else create new model.
375
+								 */
376
+								$relationModel = Arr::has($val, 'id') ? $relationBaseModel->lockForUpdate()->find($val['id']) : new $relationBaseModel;
377
+							}
378
+
379
+							/**
380
+							 * If model doesn't exists.
381
+							 */
382
+							if (! $relationModel) {
383
+								\Errors::notFound(class_basename($relationBaseModel).' with id : '.$val['id']);
384
+							}
385
+
386
+							if (is_array($val)) {
387
+								/**
388
+								 * Loop through the relation attributes.
389
+								 */
390
+								foreach ($val as $attr => $val) {
391
+									/**
392
+									 * Prevent the sub relations or attributes not in the fillable.
393
+									 */
394
+									if (gettype($val) !== 'object' && gettype($val) !== 'array' && array_search($attr, $relationModel->getFillable(), true) !== false && class_basename($model->$key()) !== 'BelongsToMany') {
395
+										$relationModel->$attr = $val;
396
+									} elseif (gettype($val) !== 'object' && gettype($val) !== 'array' && $attr !== 'id') {
397
+										$extra[$attr] = $val;
398
+									}
399
+								}
400
+							}
401
+
402
+							if (isset($extra)) {
403
+								$relationModel->extra = $extra;
404
+							}
405
+							$relations[$relation][] = $relationModel;
406
+						} else {
407
+							/**
408
+							 * Prevent the sub relations.
409
+							 */
410
+							if (gettype($val) !== 'object' && gettype($val) !== 'array') {
411
+								/**
412
+								 * If the id is present in the data then select the relation model for updating,
413
+								 * else create new model.
414
+								 */
415
+								$relationModel = Arr::has($value, 'id') ? $relationBaseModel->lockForUpdate()->find($value['id']) : new $relationBaseModel;
416
+
417
+								/**
418
+								 * If model doesn't exists.
419
+								 */
420
+								if (! $relationModel) {
421
+									\Errors::notFound(class_basename($relationBaseModel).' with id : '.$value['id']);
422
+								}
423
+
424
+								foreach ($value as $relationAttribute => $relationValue) {
425
+									/**
426
+									 * Prevent attributes not in the fillable.
427
+									 */
428
+									if (array_search($relationAttribute, $relationModel->getFillable(), true) !== false) {
429
+										$relationModel->$relationAttribute = $relationValue;
430
+									}
431
+								}
432
+
433
+								$relations[$relation] = $relationModel;
434
+							}
435
+						}
436
+					}
437
+				}
438
+			}
439
+		}
440
+
441
+		return $relations;
442
+	}
443
+
444
+	/**
445
+	 * Save the model with related models.
446
+	 *
447
+	 * @param   object  $model
448
+	 * @param   array   $relations
449
+	 *
450
+	 * @return  object
451
+	 */
452
+	public function saveModel($model, $relations)
453
+	{
454
+		/**
455
+		 * Sort relations.
456
+		 */
457
+		$belongsTo = [];
458
+		$hasOne = [];
459
+		$array = [];
460
+		foreach ($relations as $key => $value) {
461
+			if (class_basename($model->$key()) === 'BelongsTo') {
462
+				$belongsTo[$key] = $value;
463
+			} elseif (class_basename($model->$key()) === 'HasOne') {
464
+				$hasOne[$key] = $value;
465
+			} else {
466
+				$array[$key] = $value;
467
+			}
468
+		};
469
+
470
+		$relations = array_merge($belongsTo, $hasOne, $array);
471
+
472
+		/**
473
+		 * Loop through the relations array.
474
+		 */
475
+		foreach ($relations as $key => $value) {
476
+			/**
477
+			 * If the relation is marked for delete then delete it.
478
+			 */
479
+			if ($value == 'delete' && $model->$key()->count()) {
480
+				switch (class_basename($model->$key())) {
481
+					/**
482
+					 * If the relation is one to many then delete all
483
+					 * relations who's id isn't in the ids array.
484
+					 */
485
+					case 'HasMany':
486
+						$model->$key()->delete();
487
+						break;
488
+
489
+					/**
490
+					 * If the relation is many to many then
491
+					 * detach the previous data and attach
492
+					 * the ids array to the model.
493
+					 */
494
+					case 'BelongsToMany':
495
+						$model->$key()->detach();
496
+						break;
497
+				}
498
+			} elseif (gettype($value) == 'array') {
499
+				/**
500
+				 * Save the model.
501
+				 */
502
+				$model->save();
503
+				$ids = [];
504
+
505
+				/**
506
+				 * Loop through the relations.
507
+				 */
508
+				foreach ($value as $val) {
509
+					switch (class_basename($model->$key())) {
510
+						/**
511
+						 * If the relation is one to many then update it's foreign key with
512
+						 * the model id and save it then add its id to ids array to delete all
513
+						 * relations who's id isn't in the ids array.
514
+						 */
515
+						case 'HasMany':
516
+							$foreignKeyName       = $model->$key()->getForeignKeyName();
517
+							$val->$foreignKeyName = $model->id;
518
+							$val->save();
519
+							$ids[] = $val->id;
520
+							break;
521
+
522
+						/**
523
+						 * If the relation is many to many then add it's id to the ids array to
524
+						 * attache these ids to the model.
525
+						 */
526
+						case 'BelongsToMany':
527
+						case 'MorphToMany':
528
+							$extra = $val->extra;
529
+							unset($val->extra);
530
+							$val->save();
531
+							$ids[$val->id] = $extra ?? [];
532
+							break;
533
+					}
534
+				}
535
+				switch (class_basename($model->$key())) {
536
+					/**
537
+					 * If the relation is one to many then delete all
538
+					 * relations who's id isn't in the ids array.
539
+					 */
540
+					case 'HasMany':
541
+						$model->$key()->whereNotIn('id', $ids)->delete();
542
+						break;
543
+
544
+					/**
545
+					 * If the relation is many to many then
546
+					 * detach the previous data and attach
547
+					 * the ids array to the model.
548
+					 */
549
+					case 'BelongsToMany':
550
+					case 'MorphToMany':
551
+						$model->$key()->detach();
552
+						$model->$key()->attach($ids);
553
+						break;
554
+				}
555
+			} else {
556
+				switch (class_basename($model->$key())) {
557
+					/**
558
+					 * If the relation is one to one.
559
+					 */
560
+					case 'HasOne':
561
+						/**
562
+						 * Save the model.
563
+						 */
564
+						$model->save();
565
+						$foreignKeyName         = $model->$key()->getForeignKeyName();
566
+						$value->$foreignKeyName = $model->id;
567
+						$value->save();
568
+						break;
569
+					case 'BelongsTo':
570
+						/**
571
+						 * Save the model.
572
+						 */
573
+						$value->save();
574
+						$model->$key()->associate($value);
575
+						break;
576
+				}
577
+			}
578
+		}
579
+
580
+		/**
581
+		 * Save the model.
582
+		 */
583
+		$model->save();
584
+
585
+		return $model;
586
+	}
587
+
588
+	/**
589
+	 * Build the conditions recursively for the retrieving methods.
590
+	 * @param  array $conditions
591
+	 * @return array
592
+	 */
593
+	protected function constructConditions($conditions, $model)
594
+	{
595
+		$conditionString = '';
596
+		$conditionValues = [];
597
+		foreach ($conditions as $key => $value) {
598
+			if (Str::contains($key, '->')) {
599
+				$key = $this->wrapJsonSelector($key);
600
+			}
601
+
602
+			if ($key == 'and') {
603
+				$conditions       = $this->constructConditions($value, $model);
604
+				$conditionString .= str_replace('{op}', 'and', $conditions['conditionString']).' {op} ';
605
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
606
+			} elseif ($key == 'or') {
607
+				$conditions       = $this->constructConditions($value, $model);
608
+				$conditionString .= str_replace('{op}', 'or', $conditions['conditionString']).' {op} ';
609
+				$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
610
+			} else {
611
+				if (is_array($value)) {
612
+					$operator = $value['op'];
613
+					if (strtolower($operator) == 'between') {
614
+						$value1 = $value['val1'];
615
+						$value2 = $value['val2'];
616
+					} else {
617
+						$value = Arr::get($value, 'val', '');
618
+					}
619
+				} else {
620
+					$operator = '=';
621
+				}
622 622
                 
623
-                if (strtolower($operator) == 'between') {
624
-                    $conditionString  .= $key.' >= ? and ';
625
-                    $conditionValues[] = $value1;
626
-
627
-                    $conditionString  .= $key.' <= ? {op} ';
628
-                    $conditionValues[] = $value2;
629
-                } elseif (strtolower($operator) == 'in') {
630
-                    $conditionValues  = array_merge($conditionValues, $value);
631
-                    $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
632
-                    $conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
633
-                } elseif (strtolower($operator) == 'not in') {
634
-                    $conditionValues  = array_merge($conditionValues, $value);
635
-                    $inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
636
-                    $conditionString .= $key.' not in ('.rtrim($inBindingsString, ',').') {op} ';
637
-                } elseif (strtolower($operator) == 'null') {
638
-                    $conditionString .= $key.' is null {op} ';
639
-                } elseif (strtolower($operator) == 'not null') {
640
-                    $conditionString .= $key.' is not null {op} ';
641
-                } elseif (strtolower($operator) == 'has') {
642
-                    $sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
643
-                    $bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
644
-                    if($value) {
645
-                        $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
646
-                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
647
-                        $conditionValues  = array_merge($conditionValues, $bindings);
648
-                        $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
649
-                    } else {
650
-                        $conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).') {op} ';
651
-                        $conditionValues  = array_merge($conditionValues, $bindings);
652
-                    }
653
-                } elseif ($operator == 'doesntHave') {
654
-                    $sql              = $model->withTrashed()->withoutGlobalScopes()->whereDoesntHave($key)->toSql();
655
-                    $bindings         = $model->withTrashed()->withoutGlobalScopes()->whereDoesntHave($key)->getBindings();
656
-                    $conditions       = $this->constructConditions($value, $model->$key()->getRelated());
657
-                    $conditionString .= substr(substr($sql, strpos($sql, 'not exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
658
-                    $conditionValues  = array_merge($conditionValues, $bindings);
659
-                    $conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
660
-                } else {
661
-                    $conditionString  .= $key.' '.$operator.' ? {op} ';
662
-                    $conditionValues[] = $value;
663
-                }
664
-            }
665
-        }
666
-        $conditionString = '('.rtrim($conditionString, '{op} ').')';
667
-        return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
668
-    }
669
-
670
-    /**
671
-     * Wrap the given JSON selector.
672
-     *
673
-     * @param  string  $value
674
-     * @return string
675
-     */
676
-    protected function wrapJsonSelector($value)
677
-    {
678
-        $removeLast = strpos($value, ')');
679
-        $value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
680
-        $path       = explode('->', $value);
681
-        $field      = array_shift($path);
682
-        $result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
683
-            return '"'.$part.'"';
684
-        })->implode('.'));
623
+				if (strtolower($operator) == 'between') {
624
+					$conditionString  .= $key.' >= ? and ';
625
+					$conditionValues[] = $value1;
626
+
627
+					$conditionString  .= $key.' <= ? {op} ';
628
+					$conditionValues[] = $value2;
629
+				} elseif (strtolower($operator) == 'in') {
630
+					$conditionValues  = array_merge($conditionValues, $value);
631
+					$inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
632
+					$conditionString .= $key.' in ('.rtrim($inBindingsString, ',').') {op} ';
633
+				} elseif (strtolower($operator) == 'not in') {
634
+					$conditionValues  = array_merge($conditionValues, $value);
635
+					$inBindingsString = rtrim(str_repeat('?,', count($value)), ',');
636
+					$conditionString .= $key.' not in ('.rtrim($inBindingsString, ',').') {op} ';
637
+				} elseif (strtolower($operator) == 'null') {
638
+					$conditionString .= $key.' is null {op} ';
639
+				} elseif (strtolower($operator) == 'not null') {
640
+					$conditionString .= $key.' is not null {op} ';
641
+				} elseif (strtolower($operator) == 'has') {
642
+					$sql              = $model->withTrashed()->withoutGlobalScopes()->has($key)->toSql();
643
+					$bindings         = $model->withTrashed()->withoutGlobalScopes()->has($key)->getBindings();
644
+					if($value) {
645
+						$conditions       = $this->constructConditions($value, $model->$key()->getRelated());
646
+						$conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
647
+						$conditionValues  = array_merge($conditionValues, $bindings);
648
+						$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
649
+					} else {
650
+						$conditionString .= substr(substr($sql, strpos($sql, 'exists')), 0, -1).') {op} ';
651
+						$conditionValues  = array_merge($conditionValues, $bindings);
652
+					}
653
+				} elseif ($operator == 'doesntHave') {
654
+					$sql              = $model->withTrashed()->withoutGlobalScopes()->whereDoesntHave($key)->toSql();
655
+					$bindings         = $model->withTrashed()->withoutGlobalScopes()->whereDoesntHave($key)->getBindings();
656
+					$conditions       = $this->constructConditions($value, $model->$key()->getRelated());
657
+					$conditionString .= substr(substr($sql, strpos($sql, 'not exists')), 0, -1).' and '.$conditions['conditionString'].') {op} ';
658
+					$conditionValues  = array_merge($conditionValues, $bindings);
659
+					$conditionValues  = array_merge($conditionValues, $conditions['conditionValues']);
660
+				} else {
661
+					$conditionString  .= $key.' '.$operator.' ? {op} ';
662
+					$conditionValues[] = $value;
663
+				}
664
+			}
665
+		}
666
+		$conditionString = '('.rtrim($conditionString, '{op} ').')';
667
+		return ['conditionString' => $conditionString, 'conditionValues' => $conditionValues];
668
+	}
669
+
670
+	/**
671
+	 * Wrap the given JSON selector.
672
+	 *
673
+	 * @param  string  $value
674
+	 * @return string
675
+	 */
676
+	protected function wrapJsonSelector($value)
677
+	{
678
+		$removeLast = strpos($value, ')');
679
+		$value      = $removeLast === false ? $value : substr($value, 0, $removeLast);
680
+		$path       = explode('->', $value);
681
+		$field      = array_shift($path);
682
+		$result     = sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) {
683
+			return '"'.$part.'"';
684
+		})->implode('.'));
685 685
         
686
-        return $removeLast === false ? $result : $result.')';
687
-    }
686
+		return $removeLast === false ? $result : $result.')';
687
+	}
688 688
 }
Please login to merge, or discard this patch.
src/Modules/Core/BaseClasses/BaseEnum.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -6,58 +6,58 @@
 block discarded – undo
6 6
 
7 7
 class BaseEnum
8 8
 {
9
-    /**
10
-     * Get all constants as an array.
11
-     *
12
-     * @return  array
13
-     */
14
-    public static function all()
15
-    {
16
-        return (new ReflectionClass(get_called_class()))->getConstants();
17
-    }
18
-
19
-    /**
20
-     * Get all constants values as an array.
21
-     *
22
-     * @return  array
23
-     */
24
-    public static function values()
25
-    {
26
-        return array_values(self::all());
27
-    }
28
-
29
-    /**
30
-     * Get all constants keys as an array.
31
-     *
32
-     * @return  array
33
-     */
34
-    public static function keys()
35
-    {
36
-        return array_keys(self::all());
37
-    }
38
-
39
-    /**
40
-     * Get constant key for the given value.
41
-     *
42
-     * @return  mixed
43
-     */
44
-    public static function key($type)
45
-    {
46
-        return collect(self::all())->search($type);
47
-    }
48
-
49
-    /**
50
-     * Convert the consts to key: value comma seperated string.
51
-     *
52
-     * @return  string
53
-     */
54
-    public static function toString()
55
-    {
56
-        $stringArr = [];
57
-        collect(self::all())->each(function($item, $key) use (&$stringArr) {
58
-            $stringArr[] = $key . ': ' . $item;
59
-        });
60
-
61
-        return implode(',', $stringArr);
62
-    }
9
+	/**
10
+	 * Get all constants as an array.
11
+	 *
12
+	 * @return  array
13
+	 */
14
+	public static function all()
15
+	{
16
+		return (new ReflectionClass(get_called_class()))->getConstants();
17
+	}
18
+
19
+	/**
20
+	 * Get all constants values as an array.
21
+	 *
22
+	 * @return  array
23
+	 */
24
+	public static function values()
25
+	{
26
+		return array_values(self::all());
27
+	}
28
+
29
+	/**
30
+	 * Get all constants keys as an array.
31
+	 *
32
+	 * @return  array
33
+	 */
34
+	public static function keys()
35
+	{
36
+		return array_keys(self::all());
37
+	}
38
+
39
+	/**
40
+	 * Get constant key for the given value.
41
+	 *
42
+	 * @return  mixed
43
+	 */
44
+	public static function key($type)
45
+	{
46
+		return collect(self::all())->search($type);
47
+	}
48
+
49
+	/**
50
+	 * Convert the consts to key: value comma seperated string.
51
+	 *
52
+	 * @return  string
53
+	 */
54
+	public static function toString()
55
+	{
56
+		$stringArr = [];
57
+		collect(self::all())->each(function($item, $key) use (&$stringArr) {
58
+			$stringArr[] = $key . ': ' . $item;
59
+		});
60
+
61
+		return implode(',', $stringArr);
62
+	}
63 63
 }
Please login to merge, or discard this patch.
src/Modules/Core/Database/Factories/SettingFactory.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -7,26 +7,26 @@
 block discarded – undo
7 7
 
8 8
 class SettingFactory extends Factory
9 9
 {
10
-    /**
11
-     * The name of the factory's corresponding model.
12
-     *
13
-     * @var string
14
-     */
15
-    protected $model = Setting::class;
10
+	/**
11
+	 * The name of the factory's corresponding model.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $model = Setting::class;
16 16
 
17
-    /**
18
-     * Define the model's default state.
19
-     *
20
-     * @return array
21
-     */
22
-    public function definition()
23
-    {
24
-        return [
25
-            'name'       => $this->faker->randomElement(['Company Name', 'Title', 'Header Image']),
26
-            'value'      => $this->faker->word(),
27
-            'key'        => $this->faker->word(),
28
-            'created_at' => $this->faker->dateTimeBetween('-1 years', 'now'),
29
-            'updated_at' => $this->faker->dateTimeBetween('-1 years', 'now')
30
-        ];
31
-    }
17
+	/**
18
+	 * Define the model's default state.
19
+	 *
20
+	 * @return array
21
+	 */
22
+	public function definition()
23
+	{
24
+		return [
25
+			'name'       => $this->faker->randomElement(['Company Name', 'Title', 'Header Image']),
26
+			'value'      => $this->faker->word(),
27
+			'key'        => $this->faker->word(),
28
+			'created_at' => $this->faker->dateTimeBetween('-1 years', 'now'),
29
+			'updated_at' => $this->faker->dateTimeBetween('-1 years', 'now')
30
+		];
31
+	}
32 32
 }
Please login to merge, or discard this patch.