Completed
Push — master ( d123db...236d99 )
by Dmitry
09:19
created

TemplateController::actions()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 94
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 94
ccs 0
cts 83
cp 0
rs 5.4672
cc 8
eloc 62
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
/*
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\IndexAction;
15
use hipanel\actions\OrientationAction;
16
use hipanel\actions\SearchAction;
17
use hipanel\actions\SmartCreateAction;
18
use hipanel\actions\SmartDeleteAction;
19
use hipanel\actions\SmartUpdateAction;
20
use hipanel\actions\ValidateFormAction;
21
use hipanel\actions\ViewAction;
22
use hipanel\modules\ticket\models\Template;
23
use hiqdev\hiart\Collection;
24
use hiqdev\hiart\ErrorResponseException;
25
use hisite\modules\news\models\ArticleData;
26
use Yii;
27
use yii\base\Event;
28
use yii\helpers\ArrayHelper;
29
use yii\web\Response;
30
31
class TemplateController extends \hipanel\base\CrudController
32
{
33
    public function actions()
34
    {
35
        return [
36
            'set-orientation' => [
37
                'class' => OrientationAction::class,
38
                'allowedRoutes' => [
39
                    '/hosting/service/index'
40
                ]
41
            ],
42
            'index' => [
43
                'class' => IndexAction::class,
44
                'on beforePerform' => function (Event $event) {
45
                    $dataProvider = $event->sender->getDataProvider();
46
                    $dataProvider->query->showUnpublished();
47
                }
48
            ],
49
            'search' => [
50
                'class' => SearchAction::class,
51
                'on beforePerform' => function (Event $event) {
52
                    $dataProvider = $event->sender->getDataProvider();
53
                    $dataProvider->query->joinWith('texts');
54
                }
55
            ],
56
            'view' => [
57
                'class' => ViewAction::class,
58
                'on beforeSave' => function (Event $event) {
59
                    /** @var \hipanel\actions\SearchAction $action */
60
                    $action = $event->sender;
61
                    $dataProvider = $action->getDataProvider();
62
                    $dataProvider->query->joinWith('texts')->showUnpublished();
63
                }
64
            ],
65
            'create' => [
66
                'class' => SmartCreateAction::class,
67
                'success' => Yii::t('hipanel/hosting', 'Template was created successfully'),
68
                'error' => Yii::t('hipanel/hosting', 'An error occurred when trying to create a template'),
69
                'data' => function ($action, $data = []) {
70
                    /** @var Template $model */
71
                    foreach ($data['models'] as $model) {
72
                        if (empty($model->getAddedTexts())) {
73
                            if (empty($model->texts)) {
74
                                $langs = $this->getRefs('type,lang', 'hipanel');
75
                                foreach ($langs as $code => $lang) {
76
                                    $model->addText(new ArticleData([
77
                                        'lang' => $code,
78
                                        'scenario' => 'create',
79
                                    ]));
80
                                }
81
                            } else {
82
                                $model->setAddedTexts($model->texts);
83
                            }
84
                        }
85
                    }
86
                },
87
                'collectionLoader' => function ($action, $data) {
0 ignored issues
show
Unused Code introduced by
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...
88
                    $this->collectionLoader($action->scenario, $action->collection);
89
                },
90
            ],
91
            'update' => [
92
                'class' => SmartUpdateAction::class,
93
                'on beforeFetchLoad' => function (Event $event) {
94
                    /** @var \hipanel\actions\SearchAction $action */
95
                    $action = $event->sender;
96
                    $dataProvider = $action->getDataProvider();
97
                    $dataProvider->query->joinWith('texts')->showUnpublished();
98
                },
99
                'data' => function ($action, $data = []) {
100
                    /** @var Template $model */
101
                    foreach ($data['models'] as $model) {
102
                        if (empty($model->getAddedTexts())) {
103
                            if (empty($model->texts)) {
104
                                $model->addText(new ArticleData(['scenario' => 'create']));
105
                            } else {
106
                                $model->setAddedTexts($model->texts);
107
                            }
108
                        }
109
                    }
110
                },
111
                'collectionLoader' => function ($action, $data) {
0 ignored issues
show
Unused Code introduced by
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...
112
                    $this->collectionLoader($action->scenario, $action->collection);
113
                },
114
                'success' => Yii::t('hipanel/hosting', 'Template was updated successfully'),
115
                'error' => Yii::t('hipanel/hosting', 'An error occurred when trying to update a template')
116
            ],
117
            'delete' => [
118
                'class' => SmartDeleteAction::class,
119
                'success' => Yii::t('hipanel/hosting', 'Template was deleted successfully'),
120
                'error' => Yii::t('hipanel/hosting', 'An error occurred when trying to delete a template')
121
            ],
122
            'validate-form' => [
123
                'class' => ValidateFormAction::class,
124
            ]
125
        ];
126
    }
127
128
    public function actionText($id, $lang)
129
    {
130
        Yii::$app->response->format = Response::FORMAT_JSON;
131
132
        $result = [];
133
134
        try {
135
            $template = Template::find()->joinWith('texts')->andWhere(['id' => $id])->one();
136
        } catch (ErrorResponseException $e) {
137
            return [];
138
        }
139
140
        if (isset($template->texts)) {
141
            foreach ($template->texts as $text) {
142
                if ($text->lang === $lang) {
143
                    $result['text'] = $text->text;
144
                }
145
            }
146
        }
147
148
        return $result;
149
    }
150
151
    public function collectionLoader($scenario, Collection $collection)
152
    {
153
        $templateModel = $this->newModel(['scenario' => $scenario]);
154
        $articleDataModel = new ArticleData(['scenario' => $scenario]);
155
156
        $templateModels = [$templateModel];
157
        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...
158
            $templateModels[] = clone $templateModel;
159
        }
160
161
        if (Template::loadMultiple($templateModels, Yii::$app->request->post())) {
162
            /** @var Template $template */
163
            foreach ($templateModels as $i => $template) {
164
                $articleDataModels = [$articleDataModel];
165
                $texts = ArrayHelper::getValue(Yii::$app->request->post($articleDataModel->formName(), []), $i, []);
166
                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...
167
                    $articleDataModels[] = clone $articleDataModel;
168
                }
169
                ArticleData::loadMultiple($articleDataModels, [$articleDataModel->formName() => $texts]);
170
171
                /** @var ArticleData $text */
172
                foreach ($articleDataModels as $text) {
173
                    if ($text->article_id === $template->id && $text->validate()) {
174
                        $template->addText($text);
175
                    }
176
                }
177
            }
178
179
            $collection->set($templateModels);
180
        }
181
    }
182
}
183