Completed
Push — master ( 052e15...9d61d3 )
by Andrii
03:16
created

TicketController::actions()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 175

Duplication

Lines 28
Ratio 16 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 28
loc 175
ccs 0
cts 164
cp 0
rs 6.7555
c 0
b 0
f 0
cc 8
nc 1
nop 0
crap 72

How to fix   Long Method   

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
 * HiPanel tickets module
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-ticket
6
 * @package   hipanel-module-ticket
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\ticket\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\IndexAction;
15
use hipanel\actions\PrepareAjaxViewAction;
16
use hipanel\actions\PrepareBulkAction;
17
use hipanel\actions\ProxyAction;
18
use hipanel\actions\RedirectAction;
19
use hipanel\actions\SmartCreateAction;
20
use hipanel\actions\SmartPerformAction;
21
use hipanel\actions\SmartUpdateAction;
22
use hipanel\actions\ValidateFormAction;
23
use hipanel\actions\ViewAction;
24
use hipanel\filters\EasyAccessControl;
25
use hipanel\modules\client\models\Client;
26
use hipanel\modules\client\models\stub\ClientRelationFreeStub;
27
use hipanel\modules\ticket\models\Thread;
28
use hipanel\modules\ticket\models\ThreadSearch;
29
use hipanel\modules\ticket\models\TicketSettings;
30
use hiqdev\hiart\ResponseErrorException;
31
use Yii;
32
use yii\base\Event;
33
use yii\filters\PageCache;
34
use yii\helpers\ArrayHelper;
35
use yii\web\NotFoundHttpException;
36
use yii\web\Response;
37
38
/**
39
 * Class TicketController.
40
 */
41
class TicketController extends \hipanel\base\CrudController
42
{
43
    /**
44
     * Used to create newModel.
45
     * @return string
46
     */
47
    public static function modelClassName()
48
    {
49
        return Thread::class;
50
    }
51
52
    public function behaviors()
53
    {
54
        return array_merge(parent::behaviors(), [
55
            [
56
                'class' => PageCache::class,
57
                'only' => ['templates'],
58
                'duration' => 7200, // 2h
59
                'variations' => [
60
                    Yii::$app->user->getId(),
61
                ],
62
            ],
63
            [
64
                'class' => EasyAccessControl::class,
65
                'actions' => [
66
                    'create'    => 'ticket.create',
67
                    'answer'    => 'ticket.answer',
68
                    'delete'    => 'ticket.delete',
69
                    '*'         => 'ticket.read',
70
                ],
71
            ],
72
        ]);
73
    }
74
75
    public function actions()
76
    {
77
        return array_merge(parent::actions(), [
78
            'index' => [
79
                'class' => IndexAction::class,
80
                'data' => $this->prepareRefs(),
81
            ],
82
            'view' => [
83
                'class' => ViewAction::class,
84
                'findOptions' => $this->getSearchOptions(),
85
                'on beforeSave' => function (Event $event) {
86
                    /** @var PrepareBulkAction $action */
87
                    $action = $event->sender;
88
                    $dataProvider = $action->getDataProvider();
89
                    $dataProvider->query->joinWith('answers');
90
                },
91
                'data' => function ($action) {
92
                    $ticket = $action->model;
93
94
                    $attributes = [
95
                        'id' => $ticket->recipient_id,
96
                        'login' => $ticket->recipient,
97
                        'seller' => $ticket->recipient_seller,
98
                        'seller_id' => $ticket->recipient_seller_id,
99
                    ];
100
101
                    if ($ticket->recipient === 'anonym') {
102
                        $attributes['seller'] = $ticket->anonym_seller;
103
                    }
104
105
                    $client = new ClientRelationFreeStub($attributes);
106
107
                    return array_merge(compact('client'), $this->prepareRefs());
108
                },
109
            ],
110
            'validate-form' => [
111
                'class' => ValidateFormAction::class,
112
            ],
113
            'answer' => [
114
                'class' => SmartUpdateAction::class,
115
                'success' => Yii::t('hipanel:ticket', 'Ticket changed'),
116
                'POST html' => [
117
                    'save' => true,
118
                    'success' => [
119
                        'class' => RedirectAction::class,
120
                        'url'   => function ($action) {
121
                            return $action->collection->count() > 1
122
                                ? $action->controller->getSearchUrl()
123
                                : $action->controller->getActionUrl('view', ['id' => $action->collection->first->id]);
124
                        },
125
                    ],
126
                    'error' => [
127
                        'class' => RedirectAction::class,
128
                    ]
129
                ],
130
            ],
131
            'create' => [
132
                'class' => SmartCreateAction::class,
133
                'success' => Yii::t('hipanel:ticket', 'Ticket posted'),
134
                'data' => function () {
135
                    return $this->prepareRefs();
136
                },
137
            ],
138
            'delete' => [
139
                'class' => SmartPerformAction::class,
140
                'success' => Yii::t('hipanel:ticket', 'Ticket deleted'),
141
            ],
142
            'subscribe' => [
143
                'class' => SmartPerformAction::class,
144
                'scenario' => 'answer',
145
                'success' => Yii::t('hipanel:ticket', 'Subscribed'),
146 View Code Duplication
                'on beforeSave' => function (Event $event) {
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...
147
                    /** @var Action $action */
148
                    $action = $event->sender;
149
                    foreach ($action->collection->models as $model) {
150
                        $model->{$this->_subscribeAction[$action->id]} = Yii::$app->user->identity->username;
151
                    }
152
                },
153
                'POST pjax' => [
154
                    'save' => true,
155
                    'success' => [
156
                        'class' => ViewAction::class,
157
                        'view' => '_subscribeButton',
158
                        'findOptions' => ['with_answers' => 1, 'show_closed' => 1],
159
                    ],
160
                ],
161
            ],
162
            'unsubscribe' => [
163
                'class' => SmartPerformAction::class,
164
                'scenario' => 'answer',
165
                'success' => Yii::t('hipanel:ticket', 'Unsubscribed'),
166 View Code Duplication
                'on beforeSave' => function (Event $event) {
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...
167
                    /** @var Action $action */
168
                    $action = $event->sender;
169
                    foreach ($action->collection->models as $model) {
170
                        $model->{$this->_subscribeAction[$action->id]} = Yii::$app->user->identity->username;
171
                    }
172
                },
173
                'POST pjax' => [
174
                    'save' => true,
175
                    'success' => [
176
                        'class' => ViewAction::class,
177
                        'view' => '_subscribeButton',
178
                        'findOptions' => ['with_answers' => 1, 'show_closed' => 1],
179
                    ],
180
                ],
181
            ],
182
            'close' => [
183
                'class' => SmartPerformAction::class,
184
                'scenario' => 'close',
185
                'success' => Yii::t('hipanel:ticket', 'Ticket closed'),
186 View Code Duplication
                'on beforeSave' => function (Event $event) {
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...
187
                    /** @var Action $action */
188
                    $action = $event->sender;
189
                    foreach ($action->collection->models as $model) {
190
                        $model->{'state'} = Thread::STATE_CLOSE;
191
                    }
192
                },
193
                'POST pjax' => [
194
                    'save' => true,
195
                    'success' => [
196
                        'class' => ProxyAction::class,
197
                        'action' => 'view',
198
                        'params' => function ($action, $model) {
199
                            return ['id' => $model->id];
200
                        },
201
                    ],
202
                ],
203
            ],
204
            'open' => [
205
                'class' => SmartPerformAction::class,
206
                'scenario' => 'open',
207
                'success' => Yii::t('hipanel:ticket', 'Ticket opened'),
208 View Code Duplication
                'on beforeSave' => function (Event $event) {
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...
209
                    /** @var Action $action */
210
                    $action = $event->sender;
211
                    foreach ($action->collection->models as $model) {
212
                        $model->{'state'} = Thread::STATE_OPEN;
213
                    }
214
                },
215
                'POST pjax' => [
216
                    'save' => true,
217
                    'success' => [
218
                        'class' => ProxyAction::class,
219
                        'action' => 'view',
220
                        'params' => function ($action, $model) {
221
                            return ['id' => $model->id];
222
                        },
223
                    ],
224
                ],
225
            ],
226
            'update-answer-modal' => [
227
                'class' => PrepareAjaxViewAction::class,
228
                'on beforeSave' => function (Event $event) {
229
                    /** @var PrepareBulkAction $action */
230
                    $action = $event->sender;
231
                    $dataProvider = $action->getDataProvider();
232
                    $dataProvider->query->joinWith('answers');
233
                },
234
                'data' => function ($action, $data) {
235
                    $answer_id = Yii::$app->request->get('answer_id');
236
                    if (!is_numeric($answer_id)) {
237
                        throw new NotFoundHttpException('Invalid answer_id');
238
                    }
239
240
                    return ArrayHelper::merge($data, [
241
                        'answer_id' => $answer_id,
242
                    ]);
243
                },
244
                'findOptions' => $this->getSearchOptions(),
245
                'scenario' => 'answer-update',
246
                'view' => '_updateAnswerModal',
247
            ],
248
        ]);
249
    }
250
251
    /**
252
     * @var array
253
     */
254
    private $_subscribeAction = ['subscribe' => 'add_watchers', 'unsubscribe' => 'del_watchers'];
255
256
    /**
257
     * @return array
258
     */
259 View Code Duplication
    protected function prepareRefs()
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...
260
    {
261
        return [
262
            'topic_data' => $this->getRefs('topic,ticket', 'hipanel:ticket'),
263
            'state_data' => $this->getClassRefs('state', 'hipanel:ticket'),
264
            'priority_data' => $this->getPriorities(),
265
        ];
266
    }
267
268
    /**
269
     * @return string
270
     */
271
    public function actionSettings()
272
    {
273
        $model = new TicketSettings();
274
        $request = Yii::$app->request;
275
        if ($request->isAjax && $model->load($request->post()) && $model->validate()) {
276
            $model->setFormData();
277
            Yii::$app->getSession()->setFlash('success', Yii::t('hipanel:ticket', 'Ticket settings saved'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
278
        } else {
279
            $model->getFormData();
280
        }
281
282
        return $this->render('settings', [
283
            'model' => $model,
284
        ]);
285
    }
286
287
    /**
288
     * @param $id
289
     * @return \yii\web\Response
290
     */
291 View Code Duplication
    public function actionPriorityUp($id)
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...
292
    {
293
        $options[$id] = ['id' => $id, 'priority' => 'high'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = 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...
294
        if ($this->_ticketChange($options)) {
295
            Yii::$app->getSession()->setFlash('success',
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
296
                Yii::t('hipanel:ticket', 'Priority has been changed to high'));
297
        } else {
298
            Yii::$app->getSession()->setFlash('error',
299
                Yii::t('hipanel:ticket', 'Some error occurred! Priority has not been changed to high'));
300
        }
301
302
        return $this->redirect(Yii::$app->request->referrer);
303
    }
304
305
    /**
306
     * @param $id
307
     * @return \yii\web\Response
308
     */
309 View Code Duplication
    public function actionPriorityDown($id)
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...
310
    {
311
        $options[$id] = ['id' => $id, 'priority' => 'medium'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = 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...
312
        if ($this->_ticketChange($options)) {
313
            Yii::$app->getSession()->setFlash('success',
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
314
                Yii::t('hipanel:ticket', 'Priority has been changed to medium'));
315
        } else {
316
            Yii::$app->getSession()->setFlash('error', Yii::t('hipanel:ticket', 'Something goes wrong!'));
317
        }
318
319
        return $this->redirect(Yii::$app->request->referrer);
320
    }
321
322
    /**
323
     * Numerous ticket changes in one method, like BladeRoot did :).
324
     * @param array $options
325
     * @param string $action
326
     * @param bool $batch
327
     * @return bool
328
     */
329
    private function _ticketChange($options = [], $action = 'answer', $batch = true)
330
    {
331
        try {
332
            Thread::perform($action, $options, ['batch' => $batch]);
333
        } catch (ResponseErrorException $e) {
334
            return false;
335
        }
336
337
        return true;
338
    }
339
340
    /**
341
     * @return string
342
     */
343
    public function actionGetQuotedAnswer()
344
    {
345
        $request = Yii::$app->request;
346
        if ($request->isAjax) {
347
            $id = $request->post('id');
348
            if ($id !== null) {
349
                try {
350
                    $answer = Thread::perform('get-answer', ['id' => $id]);
351
                } catch (ResponseErrorException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
352
                }
353
                if (isset($answer['message'])) {
354
                    return '> ' . str_replace("\n", "\n> ", $answer['message']);
355
                }
356
            }
357
        }
358
        Yii::$app->end();
359
    }
360
361
    /**
362
     * @return mixed|string
363
     */
364
    public function actionPreview()
365
    {
366
        $request = Yii::$app->request;
367
        if ($request->isAjax) {
368
            $text = $request->post('text');
369
            if ($text) {
370
                return Thread::parseMessage($text);
371
            }
372
        }
373
        Yii::$app->end();
374
    }
375
376
    public function actionGetNewAnswers($id, $answer_id)
377
    {
378
        Yii::$app->response->format = Response::FORMAT_JSON;
379
380
        $result = ['id' => $id, 'answer_id' => $answer_id];
381
382
        try {
383
            $data = Thread::perform('get-last-answer-id', ['id' => $id, 'answer_id' => $answer_id]);
384
            $result['answer_id'] = $data['answer_id'];
385
            if ($data['answer_id'] > $answer_id) {
386
                $dataProvider = (new ThreadSearch())->search([]);
387
                $dataProvider->query->joinWith('answers');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\QueryInterface as the method joinWith() does only exist in the following implementations of said interface: hipanel\modules\client\models\query\ArticleQuery, hipanel\modules\client\models\query\ClientQuery, hipanel\modules\client\models\query\ContactQuery, hiqdev\hiart\ActiveQuery, yii\db\ActiveQuery.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
388
                $dataProvider->query->andWhere(['id' => $id]);
389
                $dataProvider->query->andWhere($this->getSearchOptions());
390
                $models = $dataProvider->getModels();
391
392
                $result['html'] = $this->renderPartial('_answers', ['model' => reset($models)]);
393
            }
394
        } catch (ResponseErrorException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
395
        }
396
397
        return $result;
398
    }
399
400
    private function getSearchOptions()
401
    {
402
        return ['with_anonym' => 1, 'with_answers' => 1, 'with_files' => 1, 'show_closed' => 1];
403
    }
404
405
    public function getPriorities()
406
    {
407
        return $this->getRefs('type,priority', 'hipanel:ticket');
408
    }
409
410
    public function actionRenderClientInfo($id)
411
    {
412
        $client = Client::find()
413
            ->where(['id' => $id])
414
            ->joinWith('contact')
415
            ->withDomains()
416
            ->withServers()
417
            ->one();
418
419
        return $this->renderAjax('_clientInfo', ['client' => $client]);
420
    }
421
}
422