Completed
Push — master ( fa5230...195b94 )
by Mohamed
16:12 queued 06:12
created

Issue::fieldBody()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
ccs 1
cts 1
cp 1
rs 9.6666
cc 1
eloc 5
nc 1
nop 0
crap 1
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
    protected $tags = null;
36
37
    /**
38
     * @param string $type
39
     *
40
     * @return \Illuminate\Database\Eloquent\Collection|null
41
     */
42 7
    protected function getTags($type = null)
43
    {
44 7
        if ($this->tags === null) {
45 7
            $this->tags = (new Model\Tag())->getGroupTags();
46
        }
47
48 7
        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 7
            return $this->tags->where('name', $type)->first()->tags;
50
        }
51
52
        return $this->tags;
53
    }
54
55
    /**
56
     * Get issue tag for specific type/group.
57
     *
58
     * @param string $type
59
     *
60
     * @return int
61
     */
62 7
    protected function getIssueTagId($type)
63
    {
64 7
        if (!$this->isEditing()) {
65 2
            return 0;
66 2
        }
67
68 2
        $groupId     = $this->getTags($type)->first()->parent_id;
69
        $selectedTag = $this->getModel()->tags->where('parent_id', $groupId);
70
71
        if ($selectedTag->count() === 0) {
72
            return 0;
73 7
        }
74
75
        return $selectedTag->last()->id;
76
    }
77
78
    /**
79
     * @param array $params
80
     *
81 6
     * @return void
82
     */
83 6
    public function setup(array $params)
84 6
    {
85 2
        $this->project = $params['project'];
86
        if (!empty($params['issue'])) {
87 6
            $this->editingModel($params['issue']);
88
        }
89
    }
90
91
    /**
92 6
     * @return array
93
     */
94
    public function actions()
95 6
    {
96
        return [
97
            'submit' => $this->isEditing() ? 'update_issue' : 'create_issue',
98
        ];
99
    }
100
101
    /**
102 6
     * @return array
103
     */
104 6
    public function fields()
105
    {
106 6
        $issueModify = \Auth::user()->permission('issue-modify');
107 6
108 6
        $fields = $this->fieldTitle();
109
        $fields += $this->fieldBody();
110
        $fields += $this->fieldTypeTags();
111 6
112 5
        // Only on creating new issue
113
        if (!$this->isEditing()) {
114
            $fields += $this->fieldUpload();
115
        }
116 6
117 6
        // Show fields for users with issue modify permission
118
        if ($issueModify) {
119
            $fields += $this->issueModifyFields();
120 6
        }
121
122
        return $fields;
123
    }
124
125
    /**
126
     * Return a list of fields for users with issue modify permission.
127
     *
128 6
     * @return array
129
     */
130 6
    protected function issueModifyFields()
131
    {
132 6
        $fields = [];
133
134
        $fields['internal_status'] = [
135
            'type' => 'legend',
136
        ];
137 6
138
        // Status tags
139
        $fields += $this->fieldStatusTags();
140 6
141
        // Assign users
142
        $fields += $this->fieldAssignedTo();
143 6
144
        // Quotes
145
        $fields += $this->fieldTimeQuote();
146 6
147
        // Resolution tags
148 6
        $fields += $this->fieldResolutionTags();
149
150
        return $fields;
151
    }
152
153
    /**
154
     * Returns title field.
155
     *
156 7
     * @return array
157
     */
158
    protected function fieldTitle()
159
    {
160
        return [
161
            'title' => [
162 7
                'type'  => 'text',
163
                'label' => 'title',
164
            ],
165
        ];
166
    }
167
168
    /**
169
     * Returns body field.
170
     *
171 7
     * @return array
172
     */
173
    protected function fieldBody()
174
    {
175
        return [
176
            'body' => [
177 7
                'type'  => 'textarea',
178
                'label' => 'issue',
179
            ],
180
        ];
181
    }
182
183
    /**
184
     * Returns status tag field.
185
     *
186 6
     * @return array
187
     */
188 6 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
    {
190 6
        $tags    = $this->getTags('status');
191
        $options = [];
192
        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 6
            $options[ucwords($tag->name)] = [
194
                'name'      => 'tag_status',
195
                'value'     => $tag->id,
196 6
                'data-tags' => $tag->id,
197 6
                'color'     => $tag->bgcolor,
198 6
            ];
199 6
        }
200 6
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 6
            'label'  => 'status',
203
            'type'   => 'radioButton',
204
            'radios' => $options,
205
            'check'  => $this->getIssueTagId('status'),
206 6
        ];
207 6
208 6
        return $fields;
209 6
    }
210 6
    /**
211
     * Returns tags field.
212
     *
213 6
     * @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
    {
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 7
                'name'      => 'tag_type',
222
                'value'     => $tag->id,
223 7
                'data-tags' => $tag->id,
224
                'color'     => $tag->bgcolor,
225 7
            ];
226
        }
227
228 7
        $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 7
            'radios' => $options,
232 7
            'check'  => $this->getIssueTagId('type'),
233 7
        ];
234 7
235 7
        return $fields;
236 7
    }
237 7
238
    /**
239
     * Returns tags field.
240
     *
241 7
     * @return array
242 7
     */
243 7
    protected function fieldResolutionTags()
244 7
    {
245 7
        $tags    = $this->getTags('resolution');
246
        $options = [
247
            trans('tinyissue.none') => [
248 7
                'name'      => 'tag_resolution',
249
                'value'     => 0,
250
                'data-tags' => 0,
251
                '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 6
                'name'      => 'tag_resolution',
257
                'value'     => $tag->id,
258 6
                'data-tags' => $tag->id,
259
                'color'     => $tag->bgcolor,
260 6
            ];
261
        }
262
263 6
        $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 6
            'check'  => $this->getIssueTagId('resolution'),
268
        ];
269
270
        return $fields;
271
    }
272 6
273
    /**
274 6
     * Returns assigned to field.
275 6
     *
276 6
     * @return array
277 6
     */
278 6
    protected function fieldAssignedTo()
279 6
    {
280
        return [
281
            'assigned_to' => [
282
                'type'    => 'select',
283 6
                'label'   => 'assigned_to',
284 6
                'options' => [0 => ''] + $this->project->usersCanFixIssue()->get()->lists('fullname', 'id')->all(),
285 6
                'value'   => (int) $this->project->default_assignee,
286 6
            ],
287 6
        ];
288
    }
289
290 6
    /**
291
     * Returns upload field.
292
     *
293
     * @return array
294
     */
295
    protected function fieldUpload()
296
    {
297
        $user                      = \Auth::guest() ? new Model\User() : \Auth::user();
298 6
        $fields                    = $this->projectUploadFields('upload', $this->project, $user);
299
        $fields['upload']['label'] = 'attachments';
300
301
        return $fields;
302 6
    }
303 6
304 6
    /**
305 6
     * 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 6
                'fields' => [
316
                    'h' => [
317 6
                        'type'          => 'number',
318 6
                        'append'        => trans('tinyissue.hours'),
319 6
                        'value'         => $this->extractQuoteValue('h'),
320
                        'addGroupClass' => 'col-sm-12 col-md-12 col-lg-4',
321 6
                    ],
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 6
                'addClass' => 'row issue-quote',
330
            ],
331
        ];
332
    }
333 6
334 6
    /**
335
     * @return array
336
     */
337 6
    public function rules()
338 6
    {
339 6
        $rules = [
340 6
            'title' => 'required|max:200',
341
            'body'  => 'required',
342
        ];
343 6
344 6
        return $rules;
345 6
    }
346 6
347
    /**
348
     * @return string
349 6
     */
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 7
    }
358
359
    /**
360 7
     * Extract number of hours, or minutes, or seconds from a quote.
361
     *
362
     * @param string $part
363
     *
364 7
     * @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