Completed
Push — develop ( 8c7bb2...93b53d )
by Mohamed
07:37
created

Issue::fields()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 13
Bugs 4 Features 3
Metric Value
c 13
b 4
f 3
dl 0
loc 20
rs 9.4285
ccs 5
cts 5
cp 1
cc 3
eloc 10
nc 4
nop 0
crap 3
1
<?php
2
3
/*
4
 * This file is part of the Tinyissue package.
5
 *
6
 * (c) Mohamed Alsharaf <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Tinyissue\Form;
13
14
use Tinyissue\Model;
15
16
/**
17
 * Issue is a class to defines fields & rules for add/edit issue form.
18
 *
19
 * @author Mohamed Alsharaf <[email protected]>
20
 */
21
class Issue extends FormAbstract
22
{
23
    /**
24
     * An instance of project model.
25
     *
26
     * @var Model\Project
27
     */
28
    protected $project;
29
30
    /**
31
     * Collection of all tags
32
     *
33
     * @var \Illuminate\Database\Eloquent\Collection
34
     */
35 6
    protected $tags = null;
36
37 6
    /**
38 6
     * @param string $type
39 2
     *
40
     * @return \Illuminate\Database\Eloquent\Collection|null
41 6
     */
42
    protected function getTags($type = null)
43
    {
44
        if ($this->tags === null) {
45
            $this->tags = (new Model\Tag())->getGroupTags();
46 6
        }
47
48
        if ($type) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
49 6
            return $this->tags->where('name', $type)->first()->tags;
50
        }
51
52
        return $this->tags;
53
    }
54
55
    /**
56 6
     * Get issue tag for specific type/group
57
     *
58 6
     * @param string $type
59
     *
60 6
     * @return int
61 6
     */
62 6
    protected function getIssueTagId($type)
63
    {
64
        if (!$this->isEditing()) {
65 6
            return 0;
66 6
        }
67
68
        $groupId = $this->getTags($type)->first()->parent_id;
69
        $selectedTag = $this->getModel()->tags->where('parent_id', $groupId);
70 6
71 5
        if ($selectedTag->count() === 0) {
72
            return 0;
73
        }
74
75 6
        return $selectedTag->last()->id;
76 6
    }
77
78
    /**
79 6
     * @param array $params
80
     *
81
     * @return void
82
     */
83
    public function setup(array $params)
84
    {
85
        $this->project = $params['project'];
86
        if (!empty($params['issue'])) {
87 7
            $this->editingModel($params['issue']);
88
        }
89
    }
90
91
    /**
92
     * @return array
93 7
     */
94
    public function actions()
95
    {
96
        return [
97
            'submit' => $this->isEditing() ? 'update_issue' : 'create_issue',
98
        ];
99
    }
100
101
    /**
102 7
     * @return array
103
     */
104
    public function fields()
105
    {
106
        $issueModify = \Auth::user()->permission('issue-modify');
107
108 7
        $fields = $this->fieldTitle();
109
        $fields += $this->fieldBody();
110
        $fields += $this->fieldTypeTags();
111
112
        // Only on creating new issue
113
        if (!$this->isEditing()) {
114
            $fields += $this->fieldUpload();
115
        }
116
117 6
        // Show fields for users with issue modify permission
118
        if ($issueModify) {
119
            $fields += $this->issueModifyFields();
120 6
        }
121
122 2
        return $fields;
123 2
    }
124
125
    /**
126
     * Return a list of fields for users with issue modify permission
127
     *
128
     * @return array
129 2
     */
130
    protected function issueModifyFields()
131 5
    {
132
        $fields = [];
133
134
        $fields['internal_status'] = [
135
            'type' => 'legend',
136 6
        ];
137 6
138
        // Status tags
139 6
        $fields += $this->fieldStatusTags();
140 6
141 6
        // Assign users
142
        $fields += $this->fieldAssignedTo();
143
144
        // Quotes
145
        $fields += $this->fieldTimeQuote();
146
147
        // Resolution tags
148
        $fields += $this->fieldResolutionTags();
149
150 6
        return $fields;
151
    }
152
153
    /**
154 6
     * Returns title field.
155 6
     *
156 6
     * @return array
157 6
     */
158
    protected function fieldTitle()
159
    {
160
        return [
161
            'title' => [
162
                'type'  => 'text',
163
                'label' => 'title',
164
            ],
165
        ];
166
    }
167 6
168
    /**
169 6
     * Returns body field.
170 6
     *
171 6
     * @return array
172
     */
173 6
    protected function fieldBody()
174
    {
175
        return [
176
            'body' => [
177
                'type'  => 'textarea',
178
                'label' => 'issue',
179
            ],
180
        ];
181 6
    }
182
183
    /**
184
     * Returns status tag field.
185 6
     *
186 6
     * @return array
187
     */
188 View Code Duplication
    protected function fieldStatusTags()
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...
189 6
    {
190 6
        $tags = $this->getTags('status');
191 6
        $options = [];
192 6
        foreach ($tags as $tag) {
0 ignored issues
show
Bug introduced by
The expression $tags of type object<Illuminate\Databa...oquent\Collection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
193
            $options[ucwords($tag->name)] = [
194
                'name'      => 'tag_status',
195 6
                'value'     => $tag->id,
196 6
                'data-tags' => $tag->id,
197 6
                'color'     => $tag->bgcolor,
198 6
            ];
199
        }
200
201 6
        $fields['tag_status'] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fields = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
202
            'label'  => 'status',
203
            'type'   => 'radioButton',
204
            'radios' => $options,
205
            'check'  => $this->getIssueTagId('status'),
206
        ];
207
208
        return $fields;
209 7
    }
210
    /**
211
     * Returns tags field.
212 7
     *
213
     * @return array
214
     */
215 View Code Duplication
    protected function fieldTypeTags()
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...
216 7
    {
217
        $tags = $this->getTags('type');
218
        $options = [];
219
        foreach ($tags as $tag) {
0 ignored issues
show
Bug introduced by
The expression $tags of type object<Illuminate\Databa...oquent\Collection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
220
            $options[ucwords($tag->name)] = [
221
                'name'      => 'tag_type',
222
                'value'     => $tag->id,
223
                'data-tags' => $tag->id,
224
                'color'     => $tag->bgcolor,
225
            ];
226
        }
227
228
        $fields['tag_type'] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fields = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
229
            'label'  => 'type',
230
            'type'   => 'radioButton',
231
            'radios' => $options,
232
            'check'  => $this->getIssueTagId('type')
233
        ];
234
235
        return $fields;
236
    }
237
238 6
    /**
239
     * Returns tags field.
240 6
     *
241 2
     * @return array
242 2
     */
243 2
    protected function fieldResolutionTags()
244
    {
245
        $tags = $this->getTags('resolution');
246 2
        $options = [
247 2
            trans('tinyissue.none') => [
248
                'name'      => 'tag_resolution',
249
                'value'     => 0,
250
                'data-tags' => 0,
251 5
                'color'     => '#62CFFC',
252
            ]
253
        ];
254
        foreach ($tags as $tag) {
0 ignored issues
show
Bug introduced by
The expression $tags of type object<Illuminate\Databa...oquent\Collection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
255
            $options[ucwords($tag->name)] = [
256
                'name'      => 'tag_resolution',
257
                'value'     => $tag->id,
258
                'data-tags' => $tag->id,
259
                'color'     => $tag->bgcolor,
260
            ];
261
        }
262
263
        $fields['tag_resolution'] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fields = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
264
            'label'  => 'resolution',
265
            'type'   => 'radioButton',
266
            'radios' => $options,
267
            'check'  => $this->getIssueTagId('resolution')
268
        ];
269
270
        return $fields;
271
    }
272
273
    /**
274
     * Returns assigned to field.
275
     *
276
     * @return array
277
     */
278
    protected function fieldAssignedTo()
279
    {
280
        return [
281
            'assigned_to' => [
282
                'type'    => 'select',
283
                'label'   => 'assigned_to',
284
                'options' => [0 => ''] + $this->project->usersCanFixIssue()->get()->lists('fullname', 'id')->all(),
285
                'value'   => (int) $this->project->default_assignee,
286
            ],
287
        ];
288
    }
289
290
    /**
291
     * Returns upload field.
292
     *
293
     * @return array
294
     */
295
    protected function fieldUpload()
296
    {
297
        $user                      = \Auth::guest() ? new Model\User() : \Auth::user();
298
        $fields                    = $this->projectUploadFields('upload', $this->project, $user);
299
        $fields['upload']['label'] = 'attachments';
300
301
        return $fields;
302
    }
303
304
    /**
305
     * Returns time quote field.
306
     *
307
     * @return array
308
     */
309
    protected function fieldTimeQuote()
310
    {
311
        return [
312
            'time_quote' => [
313
                'type'   => 'groupField',
314
                'label'  => 'quote',
315
                'fields' => [
316
                    'h' => [
317
                        'type'          => 'number',
318
                        'append'        => trans('tinyissue.hours'),
319
                        'value'         => $this->extractQuoteValue('h'),
320
                        'addGroupClass' => 'col-sm-12 col-md-12 col-lg-4',
321
                    ],
322
                    'm' => [
323
                        'type'          => 'number',
324
                        'append'        => trans('tinyissue.minutes'),
325
                        'value'         => $this->extractQuoteValue('m'),
326
                        'addGroupClass' => 'col-sm-12 col-md-12 col-lg-4',
327
                    ],
328
                ],
329
                'addClass' => 'row issue-quote',
330
            ],
331
        ];
332
    }
333
334
    /**
335
     * @return array
336
     */
337
    public function rules()
338
    {
339
        $rules = [
340
            'title' => 'required|max:200',
341
            'body'  => 'required',
342
        ];
343
344
        return $rules;
345
    }
346
347
    /**
348
     * @return string
349
     */
350
    public function getRedirectUrl()
351
    {
352
        if ($this->isEditing()) {
353
            return $this->getModel()->to('edit');
354
        }
355
356
        return 'project/' . $this->project->id . '/issue/new';
357
    }
358
359
    /**
360
     * Extract number of hours, or minutes, or seconds from a quote.
361
     *
362
     * @param string $part
363
     *
364
     * @return float|int
365
     */
366
    protected function extractQuoteValue($part)
367
    {
368
        if ($this->getModel() instanceof Model\Project\Issue) {
369
            $seconds = $this->getModel()->time_quote;
370
            if ($part === 'h') {
371
                return floor($seconds / 3600);
372
            }
373
374
            if ($part === 'm') {
375
                return ($seconds / 60) % 60;
376
            }
377
        }
378
379
        return 0;
380
    }
381
}
382