Completed
Push — master ( 452da7...e36ccf )
by Dmitry
05:20
created

Combo::getPluginOptions()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 0
cts 19
cp 0
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 18
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * Combo widget for Yii2
5
 *
6
 * @link      https://github.com/hiqdev/yii2-combo
7
 * @package   yii2-combo
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiqdev\combo;
13
14
use Yii;
15
use yii\base\Model;
16
use yii\base\Widget;
17
use yii\helpers\ArrayHelper;
18
use yii\helpers\Html;
19
use yii\helpers\Json;
20
use yii\helpers\Url;
21
use yii\web\JsExpression;
22
use yii\web\View;
23
24
/**
25
 * Widget Combo.
26
 *
27
 * @property mixed $return see [[_return]]
28
 * @property mixed $rename see [[_rename]]
29
 * @property mixed $filter see [[_filter]]
30
 * @property mixed $pluginOptions see [[_pluginOptions]]
31
 * @property mixed $primaryFilter see [[_primaryFilter]]
32
 * @property mixed hasId
33
 */
34
class Combo extends Widget
35
{
36
    /**
37
     * @var Model
38
     */
39
    public $model;
40
41
    /**
42
     * @var string the attribute name
43
     */
44
    public $attribute;
45
46
    /**
47
     * @var array the url that will be passed to [[Url::to()]] method to create the request URL
48
     */
49
    public $url;
50
51
    /**
52
     * @var string the type of the field.
53
     * Usual should be module/comboName.
54
     * For example: client/client, hosting/account, domain/domain.
55
     * In case of the combo overriding with some specific filters,
56
     * the type should represent the filter.
57
     * For example: if the hosting/service combo is extended with filter
58
     * to show only DB services, the type should be hosting/service/db or hosting/dbService.
59
     * The decision of the style depends on overall code style and readability
60
     */
61
    public $type;
62
63
    /**
64
     * @var string the name of the representative field in the model.
65
     * Used by [[getPrimaryFilter]] to create the name of the filtering field
66
     * @see getPrimaryFilter()
67
     */
68
    public $name;
69
70
    /**
71
     * @var string md5 of the configuration.
72
     * Appears only after the combo registration in [[register]]
73
     * @see register()
74
     */
75
    public $configId;
76
77
    /**
78
     * @var array the HTML options for the input element
79
     */
80
    public $inputOptions = [];
81
82
    /**
83
     * @var string the outer element selector, that holds all of related Combos
84
     */
85
    public $formElementSelector = 'form';
86
87
    /**
88
     * @var string the language. Default is application language
89
     */
90
    public $language;
91
92
    /**
93
     * @var bool allow multiple selection
94
     */
95
    public $multiple;
96
97
    /**
98
     * @var array
99
     */
100
    public $current;
101
102
    /**
103
     * @var mixed returning arguments
104
     * Example:
105
     *
106
     * ```
107
     *  ['id', 'password', 'another_column']
108
     * ```
109
     *
110
     * @see getReturn()
111
     * @see setReturn()
112
     */
113
    protected $_return;
114
115
    /**
116
     * @var array renamed arguments
117
     * Example:
118
     *
119
     * ```
120
     *  [
121
     *      'new_col_name' => 'old_col_name',
122
     *      'text' => 'login',
123
     *      'deep' => 'array.subarray.value' // can extract some value from an array
124
     *  ]
125
     * ```
126
     *
127
     * @see getName()
128
     * @see setName()
129
     */
130
    protected $_rename;
131
132
    /**
133
     * @var array the static filters
134
     * Example:
135
     *
136
     * ```
137
     * [
138
     *      'someStaticValue' => ['format' => 'the_value'],
139
     *      'type'            => ['format' => 'seller'],
140
     *      'is_active'       => [
141
     *          'field'  => 'server',
142
     *          'format' => new JsExpression('function (id, text, field) {
143
     *              if (field.isSet()) {
144
     *                  return 1;
145
     *              }
146
     *          }'),
147
     *      ]
148
     * ]
149
     * @see setFilter()
150
     * @see getFilter()
151
     */
152
    protected $_filter = [];
153
154
    /**
155
     * @var string the name of the primary filter. Default: [[name]]_like
156
     * @see getPrimaryFilter
157
     * @see setPrimaryFilter
158
     */
159
    protected $_primaryFilter;
160
161
    /**
162
     * @var boolean|string whether the combo has a primary key
163
     *   null (default) - decision will be taken automatically.
164
     *                    In case when [[attribute]] has the `_id` postfix, this property will be treated as `true`
165
     *            false - the combo does not have an id. Meaning the value of the attribute will be used as the ID
166
     *           string - the explicit name of the ID attribute
167
     */
168
    public $_hasId;
169
170
    /**
171
     * Options that will be passed to the plugin.
172
     *
173
     * @var array
174
     * @see getPluginOptions()
175
     */
176
    public $_pluginOptions = [];
177
178
    /** {@inheritdoc} */
179 2
    public function init()
180
    {
181 2
        parent::init();
182
183
        // Set language
184 2
        if ($this->language === null && ($language = Yii::$app->language) !== 'en-US') {
185 2
            $this->language = substr($language, 0, 2);
186 2
        }
187 2
        if (!$this->_return) {
188 2
            $this->return = ['id'];
189 2
        }
190 2
        if (!$this->rename) {
191 2
            $this->rename = ['text' => $this->name];
192 2
        }
193 2
        if (!$this->inputOptions['id']) {
194
            $this->inputOptions['id'] = Html::getInputId($this->model, $this->attribute);
195
        }
196 2
        if ($this->multiple) {
197
            $this->inputOptions['multiple'] = true;
198
        }
199 2
        if ($this->inputOptions['readonly']) {
200
            $this->inputOptions['disabled'] = true;
201
        }
202 2
        if (!$this->inputOptions['data-combo-field']) {
203 2
            $this->inputOptions['data-combo-field'] = $this->name;
204 2
        }
205 2
        if (!isset($this->inputOptions['unselect'])) {
206 2
            $this->inputOptions['unselect'] = null;
207 2
        }
208 2
    }
209
210
    public function run()
211
    {
212
        $this->registerClientConfig();
213
        $this->registerClientScript();
214
        return $this->renderInput();
215
    }
216
217
    /**
218
     * Renders text input that will be used by the plugin.
219
     * Must apply [[inputOptions]] to the HTML element.
220
     *
221
     * @return string
222
     */
223
    protected function renderInput()
224
    {
225
        $html = [];
226
        if ($this->inputOptions['readonly']) {
227
            $html[] = Html::activeHiddenInput($this->model, $this->attribute, [
228
                'id' => $this->inputOptions['id'] . '-hidden',
229
            ]);
230
        }
231
        $html[] = Html::activeDropDownList($this->model, $this->attribute, $this->getCurrentOptions(), $this->inputOptions);
232
233
        return implode('', $html);
234
    }
235
236
    public function registerClientConfig()
237
    {
238
        $view = $this->view;
239
        ComboAsset::register($view);
240
241
        $pluginOptions = Json::encode($this->pluginOptions);
242
        $this->configId = md5($this->type . $pluginOptions);
243
        $view->registerJs("$.comboConfig().add('{$this->configId}', $pluginOptions);", View::POS_READY, 'combo_' . $this->configId);
244
    }
245
246
    public function registerClientScript()
247
    {
248
        $selector = $this->inputOptions['id'];
249
        $js = "$('#$selector').closest('{$this->formElementSelector}').combo().register('#$selector', '$this->configId');";
250
251
        $this->view->registerJs($js);
252
    }
253
254
    public function getReturn()
255
    {
256
        return $this->_return;
257
    }
258
259
    /**
260
     * @return mixed
261
     */
262 2
    public function getRename()
263
    {
264 2
        return $this->_rename;
265
    }
266
267
    /**
268
     * @return mixed
269
     */
270
    public function getFilter()
271
    {
272
        return $this->_filter;
273
    }
274
275
    /**
276
     * @param mixed $filter
277
     */
278
    public function setFilter($filter)
279
    {
280
        $this->_filter = $filter;
0 ignored issues
show
Documentation Bug introduced by
It seems like $filter of type * is incompatible with the declared type array of property $_filter.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
281
    }
282
283
    /**
284
     * @param mixed $rename
285
     */
286 2
    public function setRename($rename)
287
    {
288 2
        $this->_rename = $rename;
0 ignored issues
show
Documentation Bug introduced by
It seems like $rename of type * is incompatible with the declared type array of property $_rename.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
289 2
    }
290
291
    /**
292
     * @param mixed $return
293
     */
294 2
    public function setReturn($return)
295
    {
296 2
        $this->_return = $return;
297 2
    }
298
299
    /**
300
     * @return string
301
     * @see _primaryFilter
302
     */
303
    public function getPrimaryFilter()
304
    {
305
        return $this->_primaryFilter ?: $this->name . '_like';
306
    }
307
308
    /**
309
     * @param $primaryFilter
310
     * @see _primaryFilter
311
     */
312
    public function setPrimaryFilter($primaryFilter)
313
    {
314
        $this->_primaryFilter = $primaryFilter;
315
    }
316
317
    /**
318
     * Returns the config of the Combo, merges with the passed $config.
319
     *
320
     * @param array $options
321
     * @return array
322
     */
323
    public function getPluginOptions($options = [])
324
    {
325
        $defaultOptions = [
326
            'name' => $this->name,
327
            'type' => $this->type,
328
            'hasId' => $this->hasId,
329
            'select2Options' => [
330
                'width'       => '100%',
331
                'placeholder' => '----------',
332
                'minimumInputLength' => '0',
333
                'ajax'        => [
334
                    'url'    => Url::toRoute($this->url),
335
                    'type'   => 'post',
336
                    'return' => $this->return,
337
                    'rename' => $this->rename,
338
                    'filter' => $this->filter,
339
                    'data' => new JsExpression("
340
                        function (event) {
341
                            return $(this).data('field').createFilter($.extend(true, {
342
                                '{$this->primaryFilter}': {format: event.term}
343
                            }, event.filters || {}));
344
                        }
345
                    "),
346
                ],
347
            ],
348
        ];
349
350
        return ArrayHelper::merge($defaultOptions, $this->_pluginOptions, $options);
351
    }
352
353
    public function getFormIsBulk()
354
    {
355
        return preg_match("/^\[.*\].+$/", $this->attribute);
356
    }
357
358
    /**
359
     * @param array $pluginOptions
360
     */
361
    public function setPluginOptions($pluginOptions)
362
    {
363
        $this->_pluginOptions = $pluginOptions;
364
    }
365
366
    /**
367
     * @return bool|string
368
     */
369
    public function getHasId()
370
    {
371
        return $this->_hasId === null ? (substr($this->attribute, -3) === '_id') : $this->_hasId;
372
    }
373
374
    /**
375
     * @param bool|string $hasId
376
     */
377
    public function setHasId($hasId)
378
    {
379
        $this->_hasId = $hasId;
380
    }
381
382
    protected function getCurrentOptions()
383
    {
384
        $value = Html::getAttributeValue($this->model, $this->attribute);
385
386
        if (!isset($value)) {
387
            return [];
388
        }
389
390
        if (!empty($this->current)) {
391
            return $this->current;
392
        }
393
394
        if ($this->getHasId()) {
395
            if (!is_scalar($value)) {
396
                Yii::error('When Combo has ID, property $current must be set manually, or attribute value must be a scalar. Value ' . var_export($value, true) . ' is not a scalar.', __METHOD__);
397
                return [];
398
            }
399
400
            return [$value => $value];
401
        } else {
402
            if (is_array($value)) {
403
                return array_combine(array_values($value), array_values($value));
404
            }
405
406
            return [$value => $value];
407
        }
408
    }
409
}
410