Completed
Push — master ( ba9b56...cc7108 )
by Dmitry
04:48
created

TicketController::actionRenderClientInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
ccs 0
cts 10
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 2
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\SmartCreateAction;
19
use hipanel\actions\SmartPerformAction;
20
use hipanel\actions\SmartUpdateAction;
21
use hipanel\actions\ValidateFormAction;
22
use hipanel\actions\ViewAction;
23
use hipanel\modules\client\models\Client;
24
use hipanel\modules\client\models\stub\ClientRelationFreeStub;
25
use hipanel\modules\ticket\models\Thread;
26
use hipanel\modules\ticket\models\ThreadSearch;
27
use hipanel\modules\ticket\models\TicketSettings;
28
use hiqdev\hiart\ResponseErrorException;
29
use Yii;
30
use yii\base\Event;
31
use yii\filters\PageCache;
32
use yii\helpers\ArrayHelper;
33
use yii\web\NotFoundHttpException;
34
use yii\web\Response;
35
36
/**
37
 * Class TicketController.
38
 */
39
class TicketController extends \hipanel\base\CrudController
40
{
41
    /**
42
     * Used to create newModel.
43
     * @return string
44
     */
45
    public static function modelClassName()
46
    {
47
        return Thread::class;
48
    }
49
50
    public function behaviors()
51
    {
52
        return array_merge(parent::behaviors(), [
53
            [
54
                'class' => PageCache::class,
55
                'only' => ['templates'],
56
                'duration' => 7200, // 2h
57
                'variations' => [
58
                    Yii::$app->user->getId(),
59
                ],
60
            ],
61
        ]);
62
    }
63
64
    public function actions()
65
    {
66
        return [
67
            'index' => [
68
                'class' => IndexAction::class,
69
                'data' => $this->prepareRefs(),
70
            ],
71
            'view' => [
72
                'class' => ViewAction::class,
73
                'findOptions' => $this->getSearchOptions(),
74
                'on beforeSave' => function (Event $event) {
75
                    /** @var PrepareBulkAction $action */
76
                    $action = $event->sender;
77
                    $dataProvider = $action->getDataProvider();
78
                    $dataProvider->query->joinWith('answers');
79
                },
80
                'data' => function ($action) {
81
                    $ticket = $action->model;
82
83
                    $attributes = [
84
                        'id' => $ticket->recipient_id,
85
                        'login' => $ticket->recipient,
86
                        'seller' => $ticket->recipient_seller,
87
                        'seller_id' => $ticket->recipient_seller_id,
88
                    ];
89
90
                    if ($ticket->recipient === 'anonym') {
91
                        $attributes['seller'] = $ticket->anonym_seller;
92
                    }
93
94
                    $client = new ClientRelationFreeStub($attributes);
95
96
                    return array_merge(compact('client'), $this->prepareRefs());
97
                },
98
            ],
99
            'validate-form' => [
100
                'class' => ValidateFormAction::class,
101
            ],
102
            'answer' => [
103
                'class' => SmartUpdateAction::class,
104
                'success' => Yii::t('hipanel:ticket', 'Ticket changed'),
105
            ],
106
            'create' => [
107
                'class' => SmartCreateAction::class,
108
                'success' => Yii::t('hipanel:ticket', 'Ticket posted'),
109
                'data' => function () {
110
                    return $this->prepareRefs();
111
                },
112
            ],
113
            'delete' => [
114
                'class' => SmartPerformAction::class,
115
                'success' => Yii::t('hipanel:ticket', 'Ticket deleted'),
116
            ],
117
            'subscribe' => [
118
                'class' => SmartPerformAction::class,
119
                'scenario' => 'answer',
120
                'success' => Yii::t('hipanel:ticket', 'Subscribed'),
121 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...
122
                    /** @var Action $action */
123
                    $action = $event->sender;
124
                    foreach ($action->collection->models as $model) {
125
                        $model->{$this->_subscribeAction[$action->id]} = Yii::$app->user->identity->username;
126
                    }
127
                },
128
                'POST pjax' => [
129
                    'save' => true,
130
                    'success' => [
131
                        'class' => ViewAction::class,
132
                        'view' => '_subscribeButton',
133
                        'findOptions' => ['with_answers' => 1, 'show_closed' => 1],
134
                    ],
135
                ],
136
            ],
137
            'unsubscribe' => [
138
                'class' => SmartPerformAction::class,
139
                'scenario' => 'answer',
140
                'success' => Yii::t('hipanel:ticket', 'Unsubscribed'),
141 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...
142
                    /** @var Action $action */
143
                    $action = $event->sender;
144
                    foreach ($action->collection->models as $model) {
145
                        $model->{$this->_subscribeAction[$action->id]} = Yii::$app->user->identity->username;
146
                    }
147
                },
148
                'POST pjax' => [
149
                    'save' => true,
150
                    'success' => [
151
                        'class' => ViewAction::class,
152
                        'view' => '_subscribeButton',
153
                        'findOptions' => ['with_answers' => 1, 'show_closed' => 1],
154
                    ],
155
                ],
156
            ],
157
            'close' => [
158
                'class' => SmartPerformAction::class,
159
                'scenario' => 'close',
160
                'success' => Yii::t('hipanel:ticket', 'Ticket closed'),
161 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...
162
                    /** @var Action $action */
163
                    $action = $event->sender;
164
                    foreach ($action->collection->models as $model) {
165
                        $model->{'state'} = Thread::STATE_CLOSE;
166
                    }
167
                },
168
                'POST pjax' => [
169
                    'save' => true,
170
                    'success' => [
171
                        'class' => ProxyAction::class,
172
                        'action' => 'view',
173
                        'params' => function ($action, $model) {
174
                            return ['id' => $model->id];
175
                        },
176
                    ],
177
                ],
178
            ],
179
            'open' => [
180
                'class' => SmartPerformAction::class,
181
                'scenario' => 'open',
182
                'success' => Yii::t('hipanel:ticket', 'Ticket opened'),
183 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...
184
                    /** @var Action $action */
185
                    $action = $event->sender;
186
                    foreach ($action->collection->models as $model) {
187
                        $model->{'state'} = Thread::STATE_OPEN;
188
                    }
189
                },
190
                'POST pjax' => [
191
                    'save' => true,
192
                    'success' => [
193
                        'class' => ProxyAction::class,
194
                        'action' => 'view',
195
                        'params' => function ($action, $model) {
196
                            return ['id' => $model->id];
197
                        },
198
                    ],
199
                ],
200
            ],
201
            'update-answer-modal' => [
202
                'class' => PrepareAjaxViewAction::class,
203
                'on beforeSave' => function (Event $event) {
204
                    /** @var PrepareBulkAction $action */
205
                    $action = $event->sender;
206
                    $dataProvider = $action->getDataProvider();
207
                    $dataProvider->query->joinWith('answers');
208
                },
209
                'data' => function ($action, $data) {
210
                    $answer_id = Yii::$app->request->get('answer_id');
211
                    if (!is_numeric($answer_id)) {
212
                        throw new NotFoundHttpException('Invalid answer_id');
213
                    }
214
215
                    return ArrayHelper::merge($data, [
216
                        'answer_id' => $answer_id,
217
                    ]);
218
                },
219
                'findOptions' => $this->getSearchOptions(),
220
                'scenario' => 'answer-update',
221
                'view' => '_updateAnswerModal',
222
            ],
223
        ];
224
    }
225
226
    /**
227
     * @var array
228
     */
229
    private $_subscribeAction = ['subscribe' => 'add_watchers', 'unsubscribe' => 'del_watchers'];
230
231
    /**
232
     * @return array
233
     */
234 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...
235
    {
236
        return [
237
            'topic_data' => $this->getRefs('topic,ticket', 'hipanel:ticket'),
238
            'state_data' => $this->getClassRefs('state', 'hipanel:ticket'),
239
            'priority_data' => $this->getPriorities(),
240
        ];
241
    }
242
243
    /**
244
     * @return string
245
     */
246
    public function actionSettings()
247
    {
248
        $model = new TicketSettings();
249
        $request = Yii::$app->request;
250
        if ($request->isAjax && $model->load($request->post()) && $model->validate()) {
251
            $model->setFormData();
252
            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...
253
        } else {
254
            $model->getFormData();
255
        }
256
257
        return $this->render('settings', [
258
            'model' => $model,
259
        ]);
260
    }
261
262
    /**
263
     * @param $id
264
     * @return \yii\web\Response
265
     */
266 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...
267
    {
268
        $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...
269
        if ($this->_ticketChange($options)) {
270
            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...
271
                Yii::t('hipanel:ticket', 'Priority has been changed to high'));
272
        } else {
273
            Yii::$app->getSession()->setFlash('error',
274
                Yii::t('hipanel:ticket', 'Some error occurred! Priority has not been changed to high'));
275
        }
276
277
        return $this->redirect(Yii::$app->request->referrer);
278
    }
279
280
    /**
281
     * @param $id
282
     * @return \yii\web\Response
283
     */
284 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...
285
    {
286
        $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...
287
        if ($this->_ticketChange($options)) {
288
            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...
289
                Yii::t('hipanel:ticket', 'Priority has been changed to medium'));
290
        } else {
291
            Yii::$app->getSession()->setFlash('error', Yii::t('hipanel:ticket', 'Something goes wrong!'));
292
        }
293
294
        return $this->redirect(Yii::$app->request->referrer);
295
    }
296
297
    /**
298
     * Numerous ticket changes in one method, like BladeRoot did :).
299
     * @param array $options
300
     * @param string $action
301
     * @param bool $batch
302
     * @return bool
303
     */
304
    private function _ticketChange($options = [], $action = 'answer', $batch = true)
305
    {
306
        try {
307
            Thread::perform($action, $options, ['batch' => $batch]);
308
        } catch (ResponseErrorException $e) {
309
            return false;
310
        }
311
312
        return true;
313
    }
314
315
    /**
316
     * @return string
317
     */
318
    public function actionGetQuotedAnswer()
319
    {
320
        $request = Yii::$app->request;
321
        if ($request->isAjax) {
322
            $id = $request->post('id');
323
            if ($id !== null) {
324
                try {
325
                    $answer = Thread::perform('get-answer', ['id' => $id]);
326
                } catch (ResponseErrorException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
327
                }
328
                if (isset($answer['message'])) {
329
                    return '> ' . str_replace("\n", "\n> ", $answer['message']);
330
                }
331
            }
332
        }
333
        Yii::$app->end();
334
    }
335
336
    /**
337
     * @return mixed|string
338
     */
339
    public function actionPreview()
340
    {
341
        $request = Yii::$app->request;
342
        if ($request->isAjax) {
343
            $text = $request->post('text');
344
            if ($text) {
345
                return Thread::parseMessage($text);
346
            }
347
        }
348
        Yii::$app->end();
349
    }
350
351
    public function actionGetNewAnswers($id, $answer_id)
352
    {
353
        Yii::$app->response->format = Response::FORMAT_JSON;
354
355
        $result = ['id' => $id, 'answer_id' => $answer_id];
356
357
        try {
358
            $data = Thread::perform('get-last-answer-id', ['id' => $id, 'answer_id' => $answer_id]);
359
            $result['answer_id'] = $data['answer_id'];
360
            if ($data['answer_id'] > $answer_id) {
361
                $dataProvider = (new ThreadSearch())->search([]);
362
                $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...
363
                $dataProvider->query->andWhere(['id' => $id]);
364
                $dataProvider->query->andWhere($this->getSearchOptions());
365
                $models = $dataProvider->getModels();
366
367
                $result['html'] = $this->renderPartial('_comments', ['model' => reset($models)]);
368
            }
369
        } catch (ResponseErrorException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
370
        }
371
372
        return $result;
373
    }
374
375
    private function getSearchOptions()
376
    {
377
        return ['with_anonym' => 1, 'with_answers' => 1, 'with_files' => 1, 'show_closed' => 1];
378
    }
379
380
    public function getPriorities()
381
    {
382
        return $this->getRefs('type,priority', 'hipanel:ticket');
383
    }
384
385
    public function actionRenderClientInfo($id)
386
    {
387
        $client = Client::find()
388
            ->where(['id' => $id])
389
            ->joinWith('contact')
390
            ->withDomains()
391
            ->withServers()
392
            ->one();
393
394
        return $this->renderAjax('_clientInfo', ['client' => $client]);
395
    }
396
}
397