Completed
Push — master ( c28151...8f7c57 )
by Andrii
05:03
created

IndexPage::renderRepresentations()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 2
b 0
f 0
nc 5
nop 2
dl 0
loc 25
ccs 0
cts 24
cp 0
crap 20
rs 8.5806
1
<?php
2
3
/*
4
 * HiPanel core package
5
 *
6
 * @link      https://hipanel.com/
7
 * @package   hipanel-core
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2014-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\widgets;
13
14
use hipanel\base\OrientationStorage;
15
use Yii;
16
use yii\base\InvalidParamException;
17
use yii\base\Model;
18
use yii\base\Object;
19
use yii\base\Widget;
20
use yii\bootstrap\ButtonDropdown;
21
use yii\data\DataProviderInterface;
22
use yii\helpers\ArrayHelper;
23
use yii\helpers\Html;
24
use yii\helpers\Inflector;
25
use yii\helpers\Json;
26
use yii\helpers\Url;
27
28
class IndexPage extends Widget
29
{
30
    /**
31
     * @var Model the search model
32
     */
33
    public $model;
34
35
    /**
36
     * @var object original view context.
37
     * It is used to render sub-views with the same context, as IndexPage
38
     */
39
    public $originalContext;
40
41
    /**
42
     * @var DataProviderInterface
43
     */
44
    public $dataProvider;
45
46
    /**
47
     * @var array Hash of document blocks, that can be rendered later in the widget's views
48
     * Blocks can be set explicitly on widget initialisation, or by calling [[beginContent]] and
49
     * [[endContent]]
50
     *
51
     * @see beginContent
52
     * @see endContent
53
     */
54
    public $contents = [];
55
56
    /**
57
     * @var string the name of current content block, that is under the render
58
     * @see beginContent
59
     * @see endContent
60
     */
61
    protected $_current = null;
62
63
    /**
64
     * @var array
65
     */
66
    public $searchFormData = [];
67
68
    /**
69
     * @var string the name of view file that contains search fields for the index page. Defaults to `_search`
70
     * @see renderSearchForm()
71
     */
72
    public $searchView = '_search';
73
74
    /** {@inheritdoc} */
75
    public function init()
76
    {
77
        parent::init();
78
        $searchFormId = Json::htmlEncode("#{$this->getBulkFormId()}");
79
        $this->originalContext = Yii::$app->view->context;
80
        $view = $this->getView();
81
        $view->registerJs(<<<JS
82
        // Checkbox
83
        var checkboxes = $('table input[type="checkbox"]');
84
        var bulkcontainer = $('.box-bulk-actions fieldset');
85
        checkboxes.on('ifChecked ifUnchecked', function(event) {
86
            if (event.type == 'ifChecked' && $('input.icheck').filter(':checked').length > 0) {
87
                bulkcontainer.prop('disabled', false);
88
            } else if ($('input.icheck').filter(':checked').length == 0) {
89
                bulkcontainer.prop('disabled', true);
90
            }
91
        });
92
        // On/Off Actions TODO: reduce scope
93
        $(document).on('click', '.box-bulk-actions a', function (event) {
94
            var link = $(this);
95
            var action = link.data('action');
96
            var form = $($searchFormId);
97
            if (action) {
98
                form.attr({'action': action, method: 'POST'}).submit();
99
            }
100
        });
101
JS
102
);
103
    }
104
105
    /**
106
     * Begins output buffer capture to save data in [[contents]] with the $name key.
107
     * Must not be called nested. See [[endContent]] for capture terminating.
108
     * @param string $name
109
     */
110
    public function beginContent($name)
111
    {
112
        if ($this->_current) {
113
            throw new InvalidParamException('Output buffer capture is already running for ' . $this->_current);
114
        }
115
        $this->_current = $name;
116
        ob_start();
117
        ob_implicit_flush(false);
118
    }
119
120
    /**
121
     * Terminates output buffer capture started by [[beginContent()]].
122
     * @see beginContent
123
     */
124
    public function endContent()
125
    {
126
        if (!$this->_current) {
127
            throw new InvalidParamException('Outout buffer capture is not running. Call beginContent() first');
128
        }
129
        $this->contents[$this->_current] = ob_get_contents();
130
        ob_end_clean();
131
        $this->_current = null;
132
    }
133
134
    /**
135
     * Returns content saved in [[content]] by $name.
136
     * @param string $name
137
     * @return string
138
     */
139
    public function renderContent($name)
140
    {
141
        return $this->contents[$name];
142
    }
143
144
    public function run()
145
    {
146
        return $this->render($this->getOrientationStorage());
147
    }
148
149
    public function getOrientationStorage()
150
    {
151
        $os = Yii::$app->get('orientationStorage');
152
        $n = $os->get(Yii::$app->controller->getRoute());
153
        return $n;
154
    }
155
156
    public function setSearchFormData($data = [])
157
    {
158
        $this->searchFormData = $data;
159
    }
160
161
    public function renderSearchForm($advancedSearchOptions = [])
162
    {
163
        ob_start();
164
        ob_implicit_flush(false);
165
        try {
166
            $search = $this->beginSearchForm($advancedSearchOptions);
167
            foreach (['per_page', 'representation'] as $key) {
168
                echo Html::hiddenInput($key, Yii::$app->request->get($key));
169
            }
170
            echo Yii::$app->view->render($this->searchView, array_merge(compact('search'), $this->searchFormData), $this->originalContext);
171
            $search->end();
172
        } catch (\Exception $e) {
173
            ob_end_clean();
174
            throw $e;
175
        }
176
177
        return ob_get_clean();
178
    }
179
180
    public function beginSearchForm($options = [])
181
    {
182
        return AdvancedSearch::begin(array_merge(['model' => $this->model], $options));
183
    }
184
185
    public function renderSearchButton()
186
    {
187
        return AdvancedSearch::renderButton() . "\n";
188
    }
189
190 View Code Duplication
    public function renderPerPage()
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...
191
    {
192
        return ButtonDropdown::widget([
193
            'label' => Yii::t('app', 'Per page') . ': ' . (Yii::$app->request->get('per_page') ?: 25),
194
            'options' => ['class' => 'btn-default btn-sm'],
195
            'dropdown' => [
196
                'items' => [
197
                    ['label' => '25',  'url' => Url::current(['per_page' => null])],
198
                    ['label' => '50',  'url' => Url::current(['per_page' => 50])],
199
                    ['label' => '100', 'url' => Url::current(['per_page' => 100])],
200
                    ['label' => '200', 'url' => Url::current(['per_page' => 200])],
201
                    ['label' => '500', 'url' => Url::current(['per_page' => 500])],
202
                ],
203
            ],
204
        ]);
205
    }
206
207
    /**
208
     * Renders button to choose representation.
209
     * Returns empty string when nothing to choose (less then 2 representations available).
210
     * @param array $grid class
211
     * @param mixed $current selected representation
212
     * @return string rendered HTML
213
     */
214
    public static function renderRepresentations($grid, $current)
215
    {
216
        $representations = $grid::getRepresentations();
217
        if (count($representations)<2) {
218
            return '';
219
        }
220
        if (!isset($representations[$current])) {
221
            $current = key($representations);
222
        }
223
        $items = [];
224
        foreach ($representations as $key => $data) {
225
            $items[] = [
226
                'label' => $data['label'],
227
                'url'   => Url::current(['representation' => $key]),
228
            ];
229
        }
230
231
        return ButtonDropdown::widget([
232
            'label' => Yii::t('synt', 'View') . ': ' . $representations[$current]['label'],
233
            'options' => ['class' => 'btn-default btn-sm'],
234
            'dropdown' => [
235
                'items' => $items,
236
            ],
237
        ]);
238
    }
239
240 View Code Duplication
    public function renderSorter(array $options)
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...
241
    {
242
        return LinkSorter::widget(array_merge([
243
            'show'  => true,
244
            'sort'  => $this->dataProvider->getSort(),
245
            'buttonClass' => 'btn btn-default dropdown-toggle btn-sm',
246
        ], $options));
247
    }
248
249
    public function getViewPath()
250
    {
251
        return parent::getViewPath() . DIRECTORY_SEPARATOR . (new \ReflectionClass($this))->getShortName();
252
    }
253
254
    public function getBulkFormId()
255
    {
256
        return 'bulk-' . Inflector::camel2id($this->model->formName());
257
    }
258
259
    public function beginBulkForm($action = '')
260
    {
261
        echo Html::beginForm($action, 'POST', ['id' => $this->getBulkFormId()]);
262
    }
263
264
    public function endBulkForm()
265
    {
266
        echo Html::endForm();
267
    }
268
269 View Code Duplication
    public function renderBulkButton($text, $action, $color = 'default')
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...
270
    {
271
        return Html::submitButton($text, [
272
            'class'         => "btn btn-$color btn-sm",
273
            'form'          => $this->getBulkFormId(),
274
            'formmethod'    => 'POST',
275
            'formaction'    => $action,
276
        ]);
277
    }
278
}
279