Completed
Push — master ( 3cae80...41e9e9 )
by Sherif
02:59
created

BaseApiController::setSessions()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.439
c 0
b 0
f 0
cc 5
eloc 20
nc 4
nop 0
1
<?php
2
namespace App\Modules\V1\Core\Http\Controllers;
3
4
use App\Http\Controllers\Controller;
5
use Illuminate\Http\Request;
6
7
class BaseApiController extends Controller
8
{
9
    /**
10
     * The model implementation.
11
     * 
12
     * @var model
13
     */
14
    protected $model;
15
16
    /**
17
     * The config implementation.
18
     * 
19
     * @var config
20
     */
21
    protected $config;
22
23
    /**
24
     * The relations implementation.
25
     * 
26
     * @var relations
27
     */
28
    protected $relations;
29
30
    public function __construct()
31
    {        
32
        $this->config              = \CoreConfig::getConfig();
33
        $this->model               = property_exists($this, 'model') ? $this->model : false;
0 ignored issues
show
Documentation Bug introduced by
It seems like property_exists($this, '... ? $this->model : false can also be of type false. However, the property $model is declared as type object<App\Modules\V1\Co...Http\Controllers\model>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
34
        $this->validationRules     = property_exists($this, 'validationRules') ? $this->validationRules : false;
35
        $this->skipPermissionCheck = property_exists($this, 'skipPermissionCheck') ? $this->skipPermissionCheck : [];
36
        $this->skipLoginCheck      = property_exists($this, 'skipLoginCheck') ? $this->skipLoginCheck : [];
37
        $route                     = explode('@',\Route::currentRouteAction())[1];
38
39
        $this->checkPermission($route);
40
        $this->setRelations($route);
41
        $this->setSessions();
42
    }
43
44
    /**
45
     * Fetch all records with relations from model repository.
46
     * 
47
     * @param  string  $sortBy
48
     * @param  boolean $desc
49
     * @return \Illuminate\Http\Response
50
     */
51
    public function index($sortBy = 'created_at', $desc = 1) 
52
    {
53
        if ($this->model)
54
        {
55
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->all($this->relations, $sortBy, $desc), 200);
56
        }
57
    }
58
59
    /**
60
     * Fetch the single object with relations from model repository.
61
     * 
62
     * @param  integer $id
63
     * @return \Illuminate\Http\Response
64
     */
65
    public function find($id) 
66
    {
67
        if ($this->model) 
68
        {
69
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->find($id, $this->relations), 200);
70
        }
71
    }
72
73
    /**
74
     * Paginate all records with relations from model repository
75
     * that matche the given query.
76
     * 
77
     * @param  string  $query
78
     * @param  integer $perPage
79
     * @param  string  $sortBy
80
     * @param  boolean $desc
81
     * @return \Illuminate\Http\Response
82
     */
83 View Code Duplication
    public function search($query = '', $perPage = 15, $sortBy = 'created_at', $desc = 1) 
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
    {
85
        if ($this->model) 
86
        {
87
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->search($query, $perPage, $this->relations, $sortBy, $desc), 200);
88
        }
89
    }
90
91
    /**
92
     * Fetch records from the storage based on the given
93
     * condition.
94
     * 
95
     * @param  \Illuminate\Http\Request  $request
96
     * @param  string  $sortBy
97
     * @param  boolean $desc
98
     * @return \Illuminate\Http\Response
99
     */
100 View Code Duplication
    public function findby(Request $request, $sortBy = 'created_at', $desc = 1) 
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
    {
102
        if ($this->model) 
103
        {
104
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->findBy($request->all(), $this->relations, $sortBy, $desc), 200);
105
        }
106
    }
107
108
    /**
109
     * Fetch the first record from the storage based on the given
110
     * condition.
111
     * 
112
     * @param  \Illuminate\Http\Request  $request
113
     * @return \Illuminate\Http\Response
114
     */
115 View Code Duplication
    public function first(Request $request) 
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
    {
117
        if ($this->model) 
118
        {
119
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->first($request->all(), $this->relations), 200);
120
        }
121
    }
122
123
    /**
124
     * Paginate all records with relations from model repository.
125
     * 
126
     * @param  integer $perPage
127
     * @param  string  $sortBy
128
     * @param  boolean $desc
129
     * @return \Illuminate\Http\Response
130
     */
131 View Code Duplication
    public function paginate($perPage = 15, $sortBy = 'created_at', $desc = 1) 
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133
        if ($this->model) 
134
        {
135
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->paginate($perPage, $this->relations, $sortBy, $desc), 200);
136
        }
137
    }
138
139
    /**
140
     * Fetch all records with relations based on
141
     * the given condition from storage in pages.
142
     * 
143
     * @param  \Illuminate\Http\Request  $request
144
     * @param  integer $perPage
145
     * @param  string  $sortBy
146
     * @param  boolean $desc
147
     * @return \Illuminate\Http\Response
148
     */
149 View Code Duplication
    public function paginateby(Request $request, $perPage = 15, $sortBy = 'created_at', $desc = 1) 
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
    {
151
        if ($this->model) 
152
        {
153
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->paginateBy($request->all(), $perPage, $this->relations, $sortBy, $desc), 200);
154
        }
155
    }
156
157
    /**
158
     * Save the given model to repository.
159
     * 
160
     * @param  \Illuminate\Http\Request  $request
161
     * @return \Illuminate\Http\Response
162
     */
163 View Code Duplication
    public function save(Request $request) 
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
    {
165
        foreach ($this->validationRules as &$rule) 
166
        {
167
            if (strpos($rule, 'exists') && ! strpos($rule, 'deleted_at,NULL')) 
168
            {
169
                $rule .= ',deleted_at,NULL';
170
            }
171
172
            if ($request->has('id')) 
173
            {
174
                $rule = str_replace('{id}', $request->get('id'), $rule);
175
            }
176
            else
177
            {
178
                $rule = str_replace(',{id}', '', $rule);
179
            }
180
        }
181
        
182
        $this->validate($request, $this->validationRules);
183
184
        if ($this->model) 
185
        {
186
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->save($request->all()), 200);
187
        }
188
    }
189
190
    /**
191
     * Delete by the given id from model repository.
192
     * 
193
     * @param  integer  $id
194
     * @return \Illuminate\Http\Response
195
     */
196
    public function delete($id) 
197
    {
198
        if ($this->model) 
199
        {
200
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->delete($id), 200);
201
        }
202
    }
203
204
    /**
205
     * Return the deleted models in pages based on the given conditions.
206
     *
207
     * @param  \Illuminate\Http\Request  $request
208
     * @param  integer $perPage
209
     * @param  string  $sortBy
210
     * @param  boolean $desc
211
     * @return \Illuminate\Http\Response
212
     */
213
    public function deleted(Request $request, $perPage = 15, $sortBy = 'created_at', $desc = 1) 
214
    {
215
        return \Response::json(call_user_func_array("\Core::{$this->model}", [])->deleted($request->all(), $perPage, $sortBy, $desc), 200);
216
    }
217
218
    /**
219
     * Restore the deleted model.
220
     * 
221
     * @param  integer  $id
222
     * @return \Illuminate\Http\Response
223
     */
224
    public function restore($id) 
225
    {
226
        if ($this->model) 
227
        {
228
            return \Response::json(call_user_func_array("\Core::{$this->model}", [])->restore($id), 200);
229
        }
230
    }
231
232
    /**
233
     * Check if the logged in user can do the given permission.
234
     * 
235
     * @param  string $permission
236
     * @return void
237
     */
238
    private function checkPermission($permission)
239
    {
240
        $permission = $permission !== 'index' ? $permission : 'list';
241
        if ( ! in_array($permission, $this->skipLoginCheck)) 
242
        {
243
            $user = \Core::users()->find(\JWTAuth::parseToken()->authenticate()->id);
244
            if ($user->blocked)
245
            {
246
                \ErrorHandler::userIsBlocked();
247
            }
248
            
249
            if ( ! in_array($permission, $this->skipPermissionCheck) && ! \Core::users()->can($permission, $this->model))
250
            {
251
                \ErrorHandler::noPermissions();
252
            }
253
        }
254
    }
255
256
    /**
257
     * Set sessions based on the given headers in the request.
258
     * 
259
     * @return void
260
     */
261
    private function setSessions()
262
    {
263
        \Session::put('timeZoneDiff', \Request::header('time-zone-diff') ?: 0);
264
265
        $locale = \Request::header('locale');
266
        switch ($locale) 
267
        {
268
            case 'en':
269
            \App::setLocale('en');
270
            \Session::put('locale', 'en');
271
            break;
272
273
            case 'ar':
274
            \App::setLocale('ar');
275
            \Session::put('locale', 'ar');
276
            break;
277
278
            case 'all':
279
            \App::setLocale('en');
280
            \Session::put('locale', 'all');
281
            break;
282
283
            default:
284
            \App::setLocale('en');
285
            \Session::put('locale', 'en');
286
            break;
287
        }
288
    }
289
290
    /**
291
     * Set relation based on the called api.
292
     * 
293
     * @param  string $route
294
     * @return void
295
     */
296
    private function setRelations($route)
297
    {
298
        $route           = $route !== 'index' ? $route : 'list';
299
        $relations       = array_key_exists($this->model, $this->config['relations']) ? $this->config['relations'][$this->model] : false;
300
        $this->relations = $relations && $relations[$route] ? $relations[$route] : [];
301
    }
302
}
303