Completed
Push — master ( 325e74...452da7 )
by Dmitry
13:50
created

Combo::getPrimaryFilter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 0
crap 6
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 = Yii::$app->getView();
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
        $view = Yii::$app->getView();
252
        $view->registerJs($js);
253
    }
254
255
    public function getReturn()
256
    {
257
        return $this->_return;
258
    }
259
260
    /**
261
     * @return mixed
262
     */
263 2
    public function getRename()
264
    {
265 2
        return $this->_rename;
266
    }
267
268
    /**
269
     * @return mixed
270
     */
271
    public function getFilter()
272
    {
273
        return $this->_filter;
274
    }
275
276
    /**
277
     * @param mixed $filter
278
     */
279
    public function setFilter($filter)
280
    {
281
        $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...
282
    }
283
284
    /**
285
     * @param mixed $rename
286
     */
287 2
    public function setRename($rename)
288
    {
289 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...
290 2
    }
291
292
    /**
293
     * @param mixed $return
294
     */
295 2
    public function setReturn($return)
296
    {
297 2
        $this->_return = $return;
298 2
    }
299
300
    /**
301
     * @return string
302
     * @see _primaryFilter
303
     */
304
    public function getPrimaryFilter()
305
    {
306
        return $this->_primaryFilter ?: $this->name . '_like';
307
    }
308
309
    /**
310
     * @param $primaryFilter
311
     * @see _primaryFilter
312
     */
313
    public function setPrimaryFilter($primaryFilter)
314
    {
315
        $this->_primaryFilter = $primaryFilter;
316
    }
317
318
    /**
319
     * Returns the config of the Combo, merges with the passed $config.
320
     *
321
     * @param array $options
322
     * @return array
323
     */
324
    public function getPluginOptions($options = [])
325
    {
326
        $defaultOptions = [
327
            'name' => $this->name,
328
            'type' => $this->type,
329
            'hasId' => $this->hasId,
330
            'select2Options' => [
331
                'width'       => '100%',
332
                'placeholder' => '----------',
333
                'minimumInputLength' => '0',
334
                'ajax'        => [
335
                    'url'    => Url::toRoute($this->url),
336
                    'type'   => 'post',
337
                    'return' => $this->return,
338
                    'rename' => $this->rename,
339
                    'filter' => $this->filter,
340
                    'data' => new JsExpression("
341
                        function (event) {
342
                            return $(this).data('field').createFilter($.extend(true, {
343
                                '{$this->primaryFilter}': {format: event.term}
344
                            }, event.filters || {}));
345
                        }
346
                    "),
347
                ],
348
            ],
349
        ];
350
351
        return ArrayHelper::merge($defaultOptions, $this->_pluginOptions, $options);
352
    }
353
354
    public function getFormIsBulk()
355
    {
356
        return preg_match("/^\[.*\].+$/", $this->attribute);
357
    }
358
359
    /**
360
     * @param array $pluginOptions
361
     */
362
    public function setPluginOptions($pluginOptions)
363
    {
364
        $this->_pluginOptions = $pluginOptions;
365
    }
366
367
    /**
368
     * @return bool|string
369
     */
370
    public function getHasId()
371
    {
372
        return $this->_hasId === null ? (substr($this->attribute, -3) === '_id') : $this->_hasId;
373
    }
374
375
    /**
376
     * @param bool|string $hasId
377
     */
378
    public function setHasId($hasId)
379
    {
380
        $this->_hasId = $hasId;
381
    }
382
383
    protected function getCurrentOptions()
384
    {
385
        $value = Html::getAttributeValue($this->model, $this->attribute);
386
387
        if (!isset($value)) {
388
            return [];
389
        }
390
391
        if (!empty($this->current)) {
392
            return $this->current;
393
        }
394
395
        if ($this->getHasId()) {
396
            if (!is_scalar($value)) {
397
                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__);
398
                return [];
399
            }
400
401
            return [$value => $value];
402
        } else {
403
            if (is_array($value)) {
404
                return array_combine(array_values($value), array_values($value));
405
            }
406
407
            return [$value => $value];
408
        }
409
    }
410
}
411