Controller::isPermissionAllowed()   B
last analyzed

Complexity

Conditions 10
Paths 16

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 7.6666
c 0
b 0
f 0
cc 10
nc 16
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Fabrica\Http\Api;
4
5
use Illuminate\Foundation\Bus\DispatchesJobs;
6
use Illuminate\Routing\Controller as BaseController;
7
use Illuminate\Foundation\Validation\ValidatesRequests;
8
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
9
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
10
11
use Fabrica\Project\Eloquent\Project;
12
use Fabrica\Project\Eloquent\Watch;
13
use Fabrica\Project\Provider;
14
use Fabrica\Acl\Acl;
15
use Sentinel;
16
use DB;
17
18
use MongoDB\BSON\ObjectID; 
19
20
class Controller extends BaseController
21
{
22
    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
23
24
    public function __construct()
25
    {
26
        $this->user = Sentinel::getUser(); 
27
    }
28
29
    public function arrange($data)
30
    {
31
        if (!is_array($data)) {
32
            return $data;
33
        }
34
35
        if (array_key_exists('_id', $data)) {
36
            $data['_id'] = $data['_id'] instanceof ObjectID ? $data['_id']->__toString() : $data['_id'];
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectID does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
37
        }
38
39
        foreach ($data as $k => $val)
40
        {
41
            $data[$k] = $this->arrange($val);
42
        }
43
44
        return $data;
45
    }
46
47
    /**
48
     * if the permission is allowed in the project.
49
     *
50
     * string $project_key
51
     * string $permission
52
     *
53
     * @return bool
54
     */
55
    public function isPermissionAllowed($project_key, $permission, $user_id='')
56
    {
57
        $uid = isset($user_id) && $user_id ? $user_id : $this->user->id;
58
59
        $isAllowed = Acl::isAllowed($uid, $permission, $project_key);
60
        if (!$isAllowed && in_array($permission, [ 'view_project', 'manage_project' ])) {
61
            if ($this->user->email === '[email protected]') {
62
                return true;
63
            }
64
65
            $project = Project::where([ 'key' => $project_key ])->first();
66
            if ($project && isset($project->principal) && isset($project->principal['id']) && $uid === $project->principal['id']) {
67
                return true;
68
            }
69
        }
70
        return $isAllowed;
71
    }
72
73
    /**
74
     * check if the field is used by issue.
75
     *
76
     * @return true 
77
     */
78
    public function isFieldUsedByIssue($project_key, $field_key, $field, $ext_info='')
79
    {
80
        if ($field['project_key'] !== $project_key) {
81
             return true;
82
        }
83
84
        if ($project_key === '$_sys_$') {
85
            switch($field_key)
86
            {
87
            case 'type':
88
                return false;
89
            case 'state':
90
            case 'priority':
91
            case 'resolution':
92
                $projects = Project::all();
93
                foreach($projects as $project)
94
                {
95
                    $isUsed = DB::collection('issue_' . $project->key)
96
                                  ->where($field_key, isset($field['key']) ? $field['key'] : $field['_id'])
97
                                  ->where('del_flg', '<>', 1)
98
                                  ->exists();
99
                    if ($isUsed) {
100
                        return true;
101
                    }
102
                }
103
                return false;
104
            default:
105
                return true;
106
            }
107
        }
108
        else
109
        {
110
            switch($field_key)
111
            {
112
            case 'type':
113
            case 'state':
114
            case 'priority':
115
            case 'resolution':
116
            case 'epic':
117
                return DB::collection('issue_' . $project_key)
118
                    ->where($field_key, $field['_id'])
119
                    ->where('del_flg', '<>', 1)
120
                    ->exists();
121 View Code Duplication
            case 'module':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
122
                return DB::collection('issue_' . $project_key)
123
                    ->where($field_key, $field['_id'])
124
                    ->where('del_flg', '<>', 1)
125
                    ->exists();
126
            case 'version':
127
                if (!$ext_info) {
128
                    return false;
129
                }
130
131
                $vid = $field['_id'];
132
                return DB::collection('issue_' . $project_key)
133
                    ->where(
134
                        function ($query) use ($vid, $ext_info) {
135
                            foreach ($ext_info as $key => $vf) 
0 ignored issues
show
Bug introduced by
The expression $ext_info of type string is not traversable.
Loading history...
136
                            {
137
                                $query->orWhere($vf['key'], $vid);
138
                            }
139
                        }
140
                    )
141
                        ->where('del_flg', '<>', 1)
142
                        ->exists();
143 View Code Duplication
            case 'labels':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
144
                return DB::collection('issue_' . $project_key)
145
                    ->where($field_key, $field['name'])
146
                    ->where('del_flg', '<>', 1)
147
                    ->exists();
148
            default:
149
                return true;
150
            }
151
        }
152
    }
153
154
    public function getIssueQueryWhere($project_key, $query)
155
    {
156
        $special_fields = [
157
            [ 'key' => 'no', 'type' => 'Number' ],
158
            [ 'key' => 'type', 'type' => 'Select' ],
159
            [ 'key' => 'state', 'type' => 'Select' ],
160
            [ 'key' => 'assignee', 'type' => 'SingleUser' ],
161
            [ 'key' => 'reporter', 'type' => 'SingleUser' ],
162
            [ 'key' => 'resolver', 'type' => 'SingleUser' ],
163
            [ 'key' => 'closer', 'type' => 'SingleUser' ],
164
165
            [ 'key' => 'created_at', 'type' => 'Duration' ],
166
            [ 'key' => 'updated_at', 'type' => 'Duration' ],
167
            [ 'key' => 'resolved_at', 'type' => 'Duration' ],
168
            [ 'key' => 'closed_at', 'type' => 'Duration' ],
169
170
            [ 'key' => 'sprints', 'type' => 'Select' ],
171
        ];
172
173
        $fields = Provider::getFieldList($project_key, ['key', 'name', 'type']);
174
        // merge into the all valid fields in the project
175
        $all_fields = array_merge($fields ? $fields->toArray() : [], $special_fields);
176
        // convert into key-type array
177
        $key_type_fields = [];
178
        foreach ($all_fields as $key => $val) 
179
        {
180
            $key_type_fields[$val['key']] = $val['type'];
181
        }
182
        // get the query where value
183
        $where = array_only($query, array_column($all_fields, 'key'));
184
185
        $and = [];
186
        foreach ($where as $key => $val)
187
        {
188
            if ($key === 'no') {
189
                $and[] = [ 'no' => intval($val) ];
190
            }
191
            else if ($key === 'title') {
192
                if (is_numeric($val) && strpos($val, '.') === false) {
193
                    $and[] = [ '$or' => [ [ 'no' => $val + 0 ], [ 'title'  => [ '$regex' => $val ] ] ] ];
194
                }
195
                else if (strpos($val, ',') !== false) {
196
                    $nos = explode(',', $val);
197
                    $new_nos = [];
198
                    foreach ($nos as $no)
199
                    {
200
                        if ($no && is_numeric($no)) {
201
                            $new_nos[] = $no + 0;
202
                        }
203
                    }
204
                    $and[] = [ '$or' => [ [ 'no' => [ '$in' => $new_nos ] ], [ 'title'  => [ '$regex' => $val ] ] ] ];
205
                }
206
                else
207
                {
208
                    $and[] = [ 'title' => [ '$regex' => $val ] ];
209
                }
210
            }
211
            else if ($key === 'sprints') {
212
                $and[] = [ 'sprints' => $val + 0 ];
213
            }
214
            else if ($key_type_fields[$key] === 'SingleUser') {
215
                $users = explode(',', $val);
216
                if (in_array('me', $users)) {
217
                    array_push($users, $this->user->id);
218
                }
219
                $and[] = [ $key . '.' . 'id' => [ '$in' => $users ] ];
220
            }
221
            else if ($key_type_fields[$key] === 'MultiUser') {
222
                $or = [];
223
                $vals = explode(',', $val);
224
                foreach ($vals as $v)
225
                {
226
                    $or[] = [ $key . '_ids' => $v == 'me' ? $this->user->id : $v ];
227
                }
228
                $and[] = [ '$or' => $or ];
229
            }
230
            else if (in_array($key_type_fields[$key], [ 'Select', 'SingleVersion', 'RadioGroup' ])) {
231
                $and[] = [ $key => [ '$in' => explode(',', $val) ] ];
232
            }
233
            else if (in_array($key_type_fields[$key], [ 'MultiSelect', 'MultiVersion', 'CheckboxGroup' ])) {
234
                $or = [];
235
                $vals = explode(',', $val);
236
                foreach ($vals as $v)
237
                {
238
                    $or[] = [ $key => $v ];
239
                }
240
                $and[] = [ '$or' => $or ];
241
            }
242
            else if (in_array($key_type_fields[$key], [ 'Duration', 'DatePicker', 'DateTimePicker' ])) {
243
                if (strpos($val, '~') !== false) {
244
                    $sections = explode('~', $val);
245 View Code Duplication
                    if ($sections[0]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
246
                        $and[] = [ $key => [ '$gte' => strtotime($sections[0]) ] ];
247
                    }
248 View Code Duplication
                    if ($sections[1]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
249
                        $and[] = [ $key => [ '$lte' => strtotime($sections[1] . ' 23:59:59') ] ];
250
                    }
251
                }
252
                else if (in_array($val, [ '0d', '0w', '0m', '0y' ])) {
253
                    if ($val == '0d') {
254
                        $and[] = [ $key => [ '$gte' => strtotime(date('Y-m-d')), '$lte' => strtotime(date('Y-m-d') . ' 23:59:59') ] ];
255
                    }
256
                    else if ($val == '0w') {
257
                        $and[] = [ $key => [ '$gte' => mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y')), '$lte' => mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y')) ] ];
258
                    } 
259
                    else if ($val == '0m') {
260
                        $and[] = [ $key => [ '$gte' => mktime(0, 0, 0, date('m'), 1, date('Y')), '$lte' => mktime(23, 59, 59, date('m'), date('t'), date('Y')) ] ];
261
                    }
262
                    else
263
                    {
264
                        $and[] = [ $key => [ '$gte' => mktime(0, 0, 0, 1, 1, date('Y')), '$lte' => mktime(23, 59, 59, 12, 31, date('Y')) ] ];
265
                    }
266
                }
267
                else
268
                {
269
                    $unitMap = [ 'w' => 'week', 'm' => 'month', 'y' => 'year' ];
270
                    $unit = substr($val, -1);
271
                    if (in_array($unit, [ 'w', 'm', 'y' ])) {
272
                        $direct = substr($val, 0, 1);
273
                        $val = abs(substr($val, 0, -1));
274
                        if ($direct === '-') {
275
                            $and[] = [ $key => [ '$lt' => strtotime(date('Ymd', strtotime('-' . $val . ' ' . $unitMap[$unit]))) ] ];
276
                        }
277
                        else
278
                        {
279
                            $and[] = [ $key => [ '$gte' => strtotime(date('Ymd', strtotime('-' . $val . ' ' . $unitMap[$unit]))) ] ];
280
                        }
281
                    }
282
                }
283
            }
284
            else if (in_array($key_type_fields[$key], [ 'Text', 'TextArea', 'Url' ])) {
285
                $and[] = [ $key => [ '$regex' => $val ] ];
286
            }
287
            else if (in_array($key_type_fields[$key],  [ 'Number', 'Integer' ])) {
288
                if (strpos($val, '~') !== false) {
289
                    $sections = explode('~', $val);
290 View Code Duplication
                    if ($sections[0]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
291
                        $and[] = [ $key => [ '$gte' => $sections[0] + 0 ] ];
292
                    }
293 View Code Duplication
                    if ($sections[1]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
294
                        $and[] = [ $key => [ '$lte' => $sections[1] + 0 ] ];
295
                    }
296
                }
297
            }
298
            else if ($key_type_fields[$key] === 'TimeTracking') {
299
                if (strpos($val, '~') !== false) {
300
                    $sections = explode('~', $val);
301 View Code Duplication
                    if ($sections[0]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
302
                        $and[] = [ $key . '_m' => [ '$gte' => $this->ttHandleInM($sections[0]) ] ];
303
                    }
304 View Code Duplication
                    if ($sections[1]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
305
                        $and[] = [ $key . '_m' => [ '$lte' => $this->ttHandleInM($sections[1]) ] ];
306
                    }
307
                }
308
            }
309
        }
310
311
        if (isset($query['watcher']) && $query['watcher']) {
312
            $watcher = $query['watcher'] === 'me' ? $this->user->id : $query['watcher'];
313
314
            $watched_issues = Watch::where('project_key', $project_key)
315
                ->where('user.id', $watcher)
316
                ->get()
317
                ->toArray();
318
            $watched_issue_ids = array_column($watched_issues, 'issue_id');
319
320
            $watchedIds = [];
321
            foreach ($watched_issue_ids as $id)
322
            {
323
                $watchedIds[] = new ObjectID($id);
324
            }
325
            $and[] = [ '_id' => [ '$in' => $watchedIds ] ];
326
        }
327
328
        $and[] = [ 'del_flg' => [ '$ne' => 1 ] ];
329
        return [ '$and' => $and ];
330
    }
331
}
332