Completed
Push — master ( 9fa50b...106089 )
by Andrii
21:34 queued 06:37
created

src/controllers/TemplateController.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\ComboSearchAction;
14
use hipanel\actions\IndexAction;
15
use hipanel\actions\SmartCreateAction;
16
use hipanel\actions\SmartDeleteAction;
17
use hipanel\actions\SmartUpdateAction;
18
use hipanel\actions\ValidateFormAction;
19
use hipanel\actions\ViewAction;
20
use hipanel\modules\ticket\models\Template;
21
use hipanel\filters\EasyAccessControl;
22
use hiqdev\hiart\Collection;
23
use hiqdev\hiart\ResponseErrorException;
24
use hisite\modules\news\models\ArticleData;
25
use Yii;
26
use yii\base\Event;
27
use yii\helpers\ArrayHelper;
28
use yii\web\Response;
29
30
class TemplateController extends \hipanel\base\CrudController
31
{
32 View Code Duplication
    public function behaviors()
0 ignored issues
show
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...
33
    {
34
        return array_merge(parent::behaviors(), [
35
            [
36
                'class' => EasyAccessControl::class,
37
                'actions' => [
38
                    '*' => 'support',
39
                ],
40
            ],
41
        ]);
42
    }
43
44
    public function actions()
45
    {
46
        return array_merge(parent::actions(), [
47
            'index' => [
48
                'class' => IndexAction::class,
49
                'on beforePerform' => function (Event $event) {
50
                    $dataProvider = $event->sender->getDataProvider();
51
                    $dataProvider->query->showUnpublished();
52
                },
53
            ],
54
            'search' => [
55
                'class' => ComboSearchAction::class,
56
                'on beforePerform' => function (Event $event) {
57
                    $dataProvider = $event->sender->getDataProvider();
58
                    $dataProvider->query->joinWith('texts');
59
                },
60
            ],
61
            'view' => [
62
                'class' => ViewAction::class,
63
                'on beforeSave' => function (Event $event) {
64
                    /** @var \hipanel\actions\SearchAction $action */
65
                    $action = $event->sender;
66
                    $dataProvider = $action->getDataProvider();
67
                    $dataProvider->query->joinWith('texts')->showUnpublished();
68
                },
69
            ],
70
            'create' => [
71
                'class' => SmartCreateAction::class,
72
                'success' => Yii::t('hipanel.ticket.template', 'Template was created successfully'),
73
                'error' => Yii::t('hipanel.ticket.template', 'An error occurred when trying to create a template'),
74
                'data' => function ($action, $data = []) {
75
                    /** @var Template $model */
76
                    foreach ($data['models'] as $model) {
77
                        if (empty($model->getAddedTexts())) {
78
                            if (empty($model->texts)) {
79
                                $langs = $this->getRefs('type,lang', 'hipanel');
80
                                foreach ($langs as $code => $lang) {
81
                                    $model->addText(new ArticleData([
82
                                        'lang' => $code,
83
                                        'scenario' => 'create',
84
                                    ]));
85
                                }
86
                            } else {
87
                                $model->setAddedTexts($model->texts);
88
                            }
89
                        }
90
                    }
91
                },
92
                'collectionLoader' => function ($action, $data) {
0 ignored issues
show
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
93
                    $this->collectionLoader($action->scenario, $action->collection);
94
                },
95
            ],
96
            'update' => [
97
                'class' => SmartUpdateAction::class,
98
                'on beforeFetchLoad' => function (Event $event) {
99
                    /** @var \hipanel\actions\SearchAction $action */
100
                    $action = $event->sender;
101
                    $dataProvider = $action->getDataProvider();
102
                    $dataProvider->query->joinWith('texts')->showUnpublished();
103
                },
104
                'data' => function ($action, $data = []) {
105
                    /** @var Template $model */
106
                    foreach ($data['models'] as $model) {
107
                        if (empty($model->getAddedTexts())) {
108
                            if (empty($model->texts)) {
109
                                $model->addText(new ArticleData(['scenario' => 'create']));
110
                            } else {
111
                                $model->setAddedTexts($model->texts);
112
                            }
113
                        }
114
                    }
115
                },
116
                'collectionLoader' => function ($action, $data) {
0 ignored issues
show
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
117
                    $this->collectionLoader($action->scenario, $action->collection);
118
                },
119
                'success' => Yii::t('hipanel.ticket.template', 'Template was updated successfully'),
120
                'error' => Yii::t('hipanel.ticket.template', 'An error occurred when trying to update a template'),
121
            ],
122
            'delete' => [
123
                'class' => SmartDeleteAction::class,
124
                'success' => Yii::t('hipanel.ticket.template', 'Template was deleted successfully'),
125
                'error' => Yii::t('hipanel.ticket.template', 'An error occurred when trying to delete a template'),
126
            ],
127
            'validate-form' => [
128
                'class' => ValidateFormAction::class,
129
            ],
130
        ]);
131
    }
132
133
    public function actionText($id, $lang)
134
    {
135
        Yii::$app->response->format = Response::FORMAT_JSON;
136
137
        $result = [];
138
139
        try {
140
            $template = Template::find()->joinWith('texts')->andWhere(['id' => $id])->one();
141
        } catch (ResponseErrorException $e) {
142
            return [];
143
        }
144
145
        if (isset($template->texts)) {
146
            foreach ($template->texts as $text) {
147
                if ($text->lang === $lang) {
148
                    $result['text'] = $text->text;
149
                }
150
            }
151
        }
152
153
        return $result;
154
    }
155
156
    public function collectionLoader($scenario, Collection $collection)
157
    {
158
        $templateModel = $this->newModel(['scenario' => $scenario]);
159
        $articleDataModel = new ArticleData(['scenario' => $scenario]);
160
161
        $templateModels = [$templateModel];
162
        for ($i = 1; $i < count(Yii::$app->request->post($templateModel->formName(), [])); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
163
            $templateModels[] = clone $templateModel;
164
        }
165
166
        if (Template::loadMultiple($templateModels, Yii::$app->request->post())) {
167
            /** @var Template $template */
168
            foreach ($templateModels as $i => $template) {
169
                $articleDataModels = [$articleDataModel];
170
                $texts = ArrayHelper::getValue(Yii::$app->request->post($articleDataModel->formName(), []), $i, []);
171
                for ($i = 1; $i < count($texts); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
172
                    $articleDataModels[] = clone $articleDataModel;
173
                }
174
                ArticleData::loadMultiple($articleDataModels, [$articleDataModel->formName() => $texts]);
175
176
                /** @var ArticleData $text */
177
                foreach ($articleDataModels as $text) {
178
                    if ($text->article_id === $template->id && $text->validate()) {
179
                        $template->addText($text);
180
                    }
181
                }
182
            }
183
184
            $collection->set($templateModels);
185
        }
186
    }
187
}
188