Completed
Push — master ( 63ab7f...7e002b )
by Dmitry
03:41
created

TicketController::actionTemplateText()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 18
ccs 0
cts 14
cp 0
rs 9.4285
cc 3
eloc 10
nc 3
nop 2
crap 12
1
<?php
2
3
/*
4
 * HiPanel tickets module
5
 *
6
 * @link      https://github.com/hiqdev/hipanel-module-ticket
7
 * @package   hipanel-module-ticket
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\modules\ticket\controllers;
13
14
use hipanel\actions\Action;
15
use hipanel\actions\IndexAction;
16
use hipanel\actions\OrientationAction;
17
use hipanel\actions\PrepareAjaxViewAction;
18
use hipanel\actions\PrepareBulkAction;
19
use hipanel\actions\ProxyAction;
20
use hipanel\actions\SearchAction;
21
use hipanel\actions\SmartCreateAction;
22
use hipanel\actions\SmartPerformAction;
23
use hipanel\actions\SmartUpdateAction;
24
use hipanel\actions\ValidateFormAction;
25
use hipanel\actions\ViewAction;
26
use hipanel\models\File;
27
use hipanel\models\Ref;
28
use hipanel\modules\client\models\Article;
29
use hipanel\modules\client\models\ArticleSearch;
30
use hipanel\modules\client\models\Client;
31
use hipanel\modules\ticket\models\Thread;
32
use hipanel\modules\ticket\models\ThreadSearch;
33
use hipanel\modules\ticket\models\TicketSettings;
34
use hiqdev\hiart\ErrorResponseException;
35
use Yii;
36
use yii\base\Event;
37
use yii\filters\PageCache;
38
use yii\helpers\ArrayHelper;
39
use yii\web\NotFoundHttpException;
40
use yii\web\Response;
41
42
/**
43
 * Class TicketController.
44
 */
45
class TicketController extends \hipanel\base\CrudController
46
{
47
    /**
48
     * Used to create newModel.
49
     *
50
     * @return string
51
     */
52
    public static function modelClassName()
53
    {
54
        return Thread::className();
55
    }
56
57
    public function behaviors()
58
    {
59
        return array_merge(parent::behaviors(), [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge(paren...app->user->getId())))); (array<*,array>) is incompatible with the return type of the parent method hipanel\base\Controller::behaviors of type array<string,array<strin...g,string[]|boolean>[]>>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
60
            [
61
                'class' => PageCache::class,
62
                'only' => ['templates'],
63
                'duration' => 7200, // 2h
64
                'variations' => [
65
                    Yii::$app->user->getId(),
66
                ],
67
            ]
68
        ]);
69
    }
70
71
    public function actions()
72
    {
73
        return [
74
            'set-orientation' => [
75
                'class' => OrientationAction::class,
76
                'allowedRoutes' => [
77
                    '@ticket/index',
78
                ],
79
            ],
80
            'index' => [
81
                'class' => IndexAction::class,
82
                'data' => $this->prepareRefs(),
83
            ],
84
            'view' => [
85
                'class' => ViewAction::class,
86
                'findOptions' => $this->getSearchOptions(),
87
                'on beforeSave' => function (Event $event) {
88
                    /** @var PrepareBulkAction $action */
89
                    $action = $event->sender;
90
                    $dataProvider = $action->getDataProvider();
91
                    $dataProvider->query->joinWith('answers');
92
                },
93
                'data' => function ($action) {
94
                    $client = Client::find()
95
                        ->withDomains()
96
                        ->withServers()
97
                        ->where([
98
                            'id' => $action->model->recipient_id,
99
                            'with_contact' => 1,
100
                        ])->one();
101
102
                    if ($client->login === 'anonym') {
103
                        $client->name = $action->model->anonym_name;
104
                        $client->email = $action->model->anonym_email;
105
                        $client->seller = $action->model->anonym_seller;
106
                    }
107
108
                    return array_merge(compact('client'), $this->prepareRefs());
109
                },
110
            ],
111
            'validate-form' => [
112
                'class' => ValidateFormAction::class,
113
            ],
114
            'answer' => [
115
                'class' => SmartUpdateAction::class,
116
                'success' => Yii::t('hipanel/ticket', 'Ticket changed'),
117
            ],
118
            'create' => [
119
                'class' => SmartCreateAction::class,
120
                'success' => Yii::t('hipanel/ticket', 'Ticket posted'),
121
                'data' => function () {
122
                    return $this->prepareRefs();
123
                },
124
            ],
125
            'delete' => [
126
                'class' => SmartPerformAction::class,
127
                'success' => Yii::t('hipanel/ticket', 'Ticket deleted'),
128
            ],
129
            'subscribe' => [
130
                'class' => SmartPerformAction::class,
131
                'scenario' => 'answer',
132
                'success' => Yii::t('hipanel/ticket', 'Subscribed'),
133 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...
134
                    /** @var Action $action */
135
                    $action = $event->sender;
136
                    foreach ($action->collection->models as $model) {
137
                        $model->{$this->_subscribeAction[$action->id]} = Yii::$app->user->identity->username;
138
                    }
139
                },
140
                'POST pjax' => [
141
                    'save' => true,
142
                    'success' => [
143
                        'class' => ViewAction::class,
144
                        'view' => '_subscribe_button',
145
                        'findOptions' => ['with_answers' => 1, 'show_closed' => 1],
146
                    ],
147
                ],
148
            ],
149
            'unsubscribe' => [
150
                'class' => SmartPerformAction::class,
151
                'scenario' => 'answer',
152
                'success' => Yii::t('hipanel/ticket', 'Unsubscribed'),
153 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...
154
                    /** @var Action $action */
155
                    $action = $event->sender;
156
                    foreach ($action->collection->models as $model) {
157
                        $model->{$this->_subscribeAction[$action->id]} = Yii::$app->user->identity->username;
158
                    }
159
                },
160
                'POST pjax' => [
161
                    'save' => true,
162
                    'success' => [
163
                        'class' => ViewAction::class,
164
                        'view' => '_subscribe_button',
165
                        'findOptions' => ['with_answers' => 1, 'show_closed' => 1],
166
                    ],
167
                ],
168
            ],
169
            'close' => [
170
                'class' => SmartPerformAction::class,
171
                'scenario' => 'close',
172
                'success' => Yii::t('hipanel/ticket', 'Ticket closed'),
173 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...
174
                    /** @var Action $action */
175
                    $action = $event->sender;
176
                    foreach ($action->collection->models as $model) {
177
                        $model->{'state'} = Thread::STATE_CLOSE;
178
                    }
179
                },
180
                'POST pjax' => [
181
                    'save' => true,
182
                    'success' => [
183
                        'class' => ProxyAction::class,
184
                        'action' => 'view',
185
                        'params' => function ($action, $model) {
186
                            return ['id' => $model->id];
187
                        },
188
                    ],
189
                ],
190
            ],
191
            'open' => [
192
                'class' => SmartPerformAction::class,
193
                'scenario' => 'open',
194
                'success' => Yii::t('hipanel/ticket', 'Ticket opened'),
195 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...
196
                    /** @var Action $action */
197
                    $action = $event->sender;
198
                    foreach ($action->collection->models as $model) {
199
                        $model->{'state'} = Thread::STATE_OPEN;
200
                    }
201
                },
202
                'POST pjax' => [
203
                    'save' => true,
204
                    'success' => [
205
                        'class' => ProxyAction::class,
206
                        'action' => 'view',
207
                        'params' => function ($action, $model) {
208
                            return ['id' => $model->id];
209
                        },
210
                    ],
211
                ],
212
            ],
213
            'update-answer-modal' => [
214
                'class' => PrepareAjaxViewAction::class,
215
                'on beforeSave' => function (Event $event) {
216
                    /** @var PrepareBulkAction $action */
217
                    $action = $event->sender;
218
                    $dataProvider = $action->getDataProvider();
219
                    $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, 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...
220
                },
221
                'data' => function ($action, $data) {
222
                    $answer_id = Yii::$app->request->get('answer_id');
223
                    if (!is_numeric($answer_id)) {
224
                        throw new NotFoundHttpException('Invalid answer_id');
225
                    }
226
227
                    return ArrayHelper::merge($data, [
228
                        'answer_id' => $answer_id,
229
                    ]);
230
                },
231
                'findOptions' => $this->getSearchOptions(),
232
                'scenario' => 'answer-update',
233
                'view' => '_updateAnswerModal',
234
            ],
235
            'templates' => [
236
                'class' => SearchAction::class,
237
                'searchModel' => ArticleSearch::class,
238
                'collection' => ['model' => Article::class],
239
                'findOptions' => [
240
                    'realm' => 'ticket_template',
241
                    'with_data' => true,
242
                ]
243
            ],
244
        ];
245
    }
246
247
    /**
248
     * @var array
249
     */
250
    private $_subscribeAction = ['subscribe' => 'add_watchers', 'unsubscribe' => 'del_watchers'];
251
252
    /**
253
     * @return array
254
     */
255 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...
256
    {
257
        return [
258
            'topic_data' => $this->getRefs('topic,ticket', 'hipanel/ticket'),
259
            'state_data' => $this->getClassRefs('state', 'hipanel/ticket'),
260
            'priority_data' => $this->getPriorities(),
261
        ];
262
    }
263
264
    public function actionTemplateText($id, $lang)
265
    {
266
        Yii::$app->response->format = Response::FORMAT_JSON;
267
268
        $result = [];
269
270
        try {
271
            $template = Article::find()->ticketTemplates()->andWhere(['id' => $id])->one();
272
        } catch (ErrorResponseException $e) {
273
            return [];
274
        }
275
276
        if (isset($template->data[$lang])) {
277
            $result['text'] = $template->data[$lang]['text'];
278
        }
279
280
        return $result;
281
    }
282
283
    /**
284
     * @return string
285
     */
286
    public function actionSettings()
287
    {
288
        $model = new TicketSettings();
289
        $request = Yii::$app->request;
290
        if ($request->isAjax && $model->load($request->post()) && $model->validate()) {
291
            $model->setFormData();
292
            \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...
293
        } else {
294
            $model->getFormData();
295
        }
296
297
        return $this->render('settings', [
298
            'model' => $model,
299
        ]);
300
    }
301
302
    /**
303
     * @param $id
304
     *
305
     * @return \yii\web\Response
306
     */
307 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...
308
    {
309
        $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...
310
        if ($this->_ticketChange($options)) {
311
            \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...
312
                \Yii::t('hipanel/ticket', 'Priority has been changed to high'));
313
        } else {
314
            \Yii::$app->getSession()->setFlash('error',
315
                \Yii::t('hipanel/ticket', 'Some error occurred! Priority has not been changed to high'));
316
        }
317
318
        return $this->redirect(Yii::$app->request->referrer);
319
    }
320
321
    /**
322
     * @param $id
323
     *
324
     * @return \yii\web\Response
325
     */
326 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...
327
    {
328
        $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...
329
        if ($this->_ticketChange($options)) {
330
            \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...
331
                \Yii::t('hipanel/ticket', 'Priority has been changed to medium'));
332
        } else {
333
            \Yii::$app->getSession()->setFlash('error', \Yii::t('hipanel/ticket', 'Something goes wrong!'));
334
        }
335
336
        return $this->redirect(Yii::$app->request->referrer);
337
    }
338
339
    /**
340
     * Numerous ticket changes in one method, like BladeRoot did :).
341
     *
342
     * @param array $options
343
     * @param string $apiCall
344
     * @param bool $bulk
345
     *
346
     * @return bool
347
     */
348
    private function _ticketChange($options = [], $apiCall = 'Answer', $bulk = true)
349
    {
350
        try {
351
            Thread::perform($apiCall, $options, $bulk);
352
        } catch (ErrorResponseException $e) {
353
            return false;
354
        }
355
356
        return true;
357
    }
358
359
    /**
360
     * @return string
361
     */
362
    public function actionGetQuotedAnswer()
363
    {
364
        $request = Yii::$app->request;
365
        if ($request->isAjax) {
366
            $id = $request->post('id');
367
            if ($id !== null) {
368
                try {
369
                    $answer = Thread::perform('GetAnswer', ['id' => $id]);
370
                } catch (ErrorResponseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
371
                }
372
                if (isset($answer['message'])) {
373
                    return '> ' . str_replace("\n", "\n> ", $answer['message']);
374
                }
375
            }
376
        }
377
        Yii::$app->end();
378
    }
379
380
    /**
381
     * @return mixed|string
382
     */
383
    public function actionPreview()
384
    {
385
        $request = Yii::$app->request;
386
        if ($request->isAjax) {
387
            $text = $request->post('text');
388
            if ($text) {
389
                return Thread::parseMessage($text);
390
            }
391
        }
392
        Yii::$app->end();
393
    }
394
395
    public function actionGetNewAnswers($id, $answer_id)
396
    {
397
        Yii::$app->response->format = Response::FORMAT_JSON;
398
399
        $result = ['id' => $id, 'answer_id' => $answer_id];
400
401
        try {
402
            $data = Thread::perform('GetLastAnswerId', ['id' => $id, 'answer_id' => $answer_id]);
403
            $result['answer_id'] = $data['answer_id'];
404
            if ($data['answer_id'] > $answer_id) {
405
                $dataProvider = (new ThreadSearch())->search([]);
406
                $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, 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...
407
                $dataProvider->query->andWhere(['id' => $id]);
408
                $dataProvider->query->andWhere($this->getSearchOptions());
409
                $models = $dataProvider->getModels();
410
411
                $result['html'] = $this->renderPartial('_comments', ['model' => reset($models)]);
412
            }
413
        } catch (ErrorResponseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
414
        }
415
416
        return $result;
417
    }
418
419
    /**
420
     * @param $id
421
     * @param $object_id
422
     *
423
     * @return array|bool
424
     */
425
    public function actionFileView($id, $object_id)
426
    {
427
        return File::renderFile($id, $object_id, 'thread', true);
428
    }
429
430
    private function getSearchOptions()
431
    {
432
        return ['with_anonym' => 1, 'with_answers' => 1, 'with_files' => 1, 'show_closed' => 1];
433
    }
434
435
    public function getPriorities()
436
    {
437
        return $this->getRefs('type,priority', 'hipanel/ticket');
438
    }
439
}
440