Completed
Pull Request — master (#145)
by Klochok
19:56 queued 04:54
created

IndexAction::getDataProvider()   C

Complexity

Conditions 12
Paths 161

Size

Total Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 50
ccs 0
cts 17
cp 0
rs 6.4583
cc 12
nc 161
nop 0
crap 156

How to fix   Complexity   

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 core package
4
 *
5
 * @link      https://hipanel.com/
6
 * @package   hipanel-core
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2014-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\actions;
12
13
use hipanel\base\FilterStorage;
14
use hipanel\grid\RepresentationCollectionFinder;
15
use hipanel\widgets\SynchronousCountEnabler;
16
use hiqdev\higrid\representations\RepresentationCollection;
17
use hiqdev\higrid\representations\RepresentationCollectionInterface;
18
use Yii;
19
use yii\grid\GridView;
20
use yii\helpers\ArrayHelper;
21
use yii\helpers\Inflector;
22
use yii\web\Controller;
23
24
/**
25
 * Class IndexAction.
26
 */
27
class IndexAction extends SearchAction
28
{
29
    public const VARIANT_PAGER_RESPONSE = 'pager';
30
31
    public const VARIANT_SUMMARY_RESPONSE = 'summary';
32
33
    /**
34
     * @var string view to render
35
     */
36
    protected $_view;
37
38
    public array $responseVariants = [];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_ARRAY, expecting T_FUNCTION or T_CONST
Loading history...
39
40
    /**
41
     * @var RepresentationCollectionFinder
42
     */
43
    private $representationCollectionFinder;
44
45
    public function setView($value)
46
    {
47
        $this->_view = $value;
48
    }
49
50
    public function getView()
51
    {
52
        if ($this->_view === null) {
53
            $this->_view = lcfirst(Inflector::id2camel($this->id));
54
        }
55
56
        return $this->_view;
57
    }
58
59
    public function __construct(string $id, Controller $controller, RepresentationCollectionFinder $representationCollectionFinder, array $config = [])
60
    {
61
        parent::__construct($id, $controller, $config);
62
        $this->representationCollectionFinder = $representationCollectionFinder;
63
    }
64
65
    /**
66
     * @var array The map of filters for the [[hipanel\base\FilterStorage|FilterStorage]]
67
     */
68
    public $filterStorageMap = [];
69
70
    protected function getDefaultRules()
71
    {
72
        return ArrayHelper::merge([
73
            'html | pjax' => [
74
                'save' => false,
75
                'flash' => false,
76
                'success' => [
77
                    'class' => RenderAction::class,
78
                    'view' => $this->getView(),
79
                    'data' => $this->data,
80
                    'params' => function () {
81
                        return [
82
                            'model' => $this->getSearchModel(),
83
                            'dataProvider' => $this->getDataProvider(),
84
                            'representationCollection' => $this->ensureRepresentationCollection(),
85
                            'uiModel' => $this->getUiModel(),
86
                        ];
87
                    },
88
                ],
89
            ],
90
            'GET ajax' => [
91
                'class' => VariantsAction::class,
92
                'variants' => array_merge([
93
                    self::VARIANT_PAGER_RESPONSE => fn(VariantsAction $action): string => SynchronousCountEnabler::widget([
94
                        'dataProvider' => $action->parent->getDataProvider(),
95
                        'content' => fn(GridView $grid): string => $grid->renderPager(),
96
                    ]),
97
                    self::VARIANT_SUMMARY_RESPONSE => fn(VariantsAction $action): string => SynchronousCountEnabler::widget([
98
                        'dataProvider' => $action->parent->getDataProvider(),
99
                        'content' => fn(GridView $grid): string => $grid->renderSummary(),
100
                    ]),
101
                ], $this->responseVariants),
102
            ],
103
        ], parent::getDefaultRules());
104
    }
105
106
    public function getUiModel()
107
    {
108
        return $this->controller->indexPageUiOptionsModel;
109
    }
110
111
    /**
112
     * Method tries to guess representation collection class name and create object
113
     * Creates empty collection when no specific representation exists.
114
     *
115
     * @return RepresentationCollection|RepresentationCollectionInterface
116
     */
117
    protected function ensureRepresentationCollection()
118
    {
119
        return $this->representationCollectionFinder->findOrFallback();
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function getDataProvider()
126
    {
127
        if ($this->dataProvider === null) {
128
            $request = Yii::$app->request;
129
130
            $formName = $this->getSearchModel()->formName();
131
            $requestFilters = $request->get($formName) ?: $request->get() ?: $request->post();
132
133
            // Don't save filters for ajax requests, because
134
            // the request is probably triggered with select2 or smt similar
135
            if ($request->getIsPjax() || !$request->getIsAjax()) {
136
                $filterStorage = new FilterStorage(['map' => $this->filterStorageMap]);
137
138
                if ($request->getIsPost() && $request->post('clear-filters')) {
139
                    $filterStorage->clearFilters();
140
                }
141
142
                $filterStorage->set($requestFilters);
143
144
                // Apply filters from storage only when request does not contain any data
145
                if (empty($requestFilters)) {
146
                    $requestFilters = $filterStorage->get();
147
                }
148
            }
149
150
            $search = ArrayHelper::merge($this->findOptions, $requestFilters);
151
152
            $this->returnOptions[$this->controller->modelClassName()] = ArrayHelper::merge(
153
                ArrayHelper::remove($search, 'return', []),
154
                ArrayHelper::remove($search, 'rename', [])
155
            );
156
157
            if ($formName !== '') {
158
                $search = [$formName => $search];
159
            }
160
            $this->dataProvider = $this->getSearchModel()->search($search, $this->dataProviderOptions);
161
162
            // Set sort
163
            if ($this->getUiModel()->sort) {
164
                $this->dataProvider->setSort(['defaultOrder' => [$this->getUiModel()->sortAttribute => $this->getUiModel()->sortDirection]]);
165
            }
166
167
            // Set pageSize
168
            if ($this->getUiModel()->per_page) {
169
                $this->dataProvider->setPagination(['pageSize' => $this->getUiModel()->per_page]);
170
            }
171
        }
172
173
        return $this->dataProvider;
174
    }
175
}
176