Completed
Push — master ( 3cd595...855c14 )
by Andrii
04:32
created

IndexPage::renderRepresentations()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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