Completed
Pull Request — master (#1350)
by
unknown
03:06
created

Select   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 310
Duplicated Lines 13.87 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 43
loc 310
rs 10
c 0
b 0
f 0
wmc 15
lcom 1
cbo 4

8 Methods

Rating   Name   Duplication   Size   Complexity  
A options() 0 19 4
A groups() 0 6 1
B load() 0 36 2
A loadRemoteOptions() 0 22 1
B ajax() 43 43 1
A config() 0 6 1
B addButton() 0 27 1
B render() 0 31 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Facades\Admin;
6
use Encore\Admin\Form\Field;
7
use Illuminate\Contracts\Support\Arrayable;
8
use Illuminate\Support\Str;
9
10
class Select extends Field
11
{
12
    /**
13
     * @var array
14
     */
15
    protected static $css = [
16
        '/vendor/laravel-admin/AdminLTE/plugins/select2/select2.min.css',
17
    ];
18
19
    /**
20
     * @var array
21
     */
22
    protected static $js = [
23
        '/vendor/laravel-admin/AdminLTE/plugins/select2/select2.full.min.js',
24
    ];
25
26
    /**
27
     * @var array
28
     */
29
    protected $groups = [];
30
31
    /**
32
     * @var array
33
     */
34
    protected $config = [];
35
36
    /**
37
     * @var array
38
     */
39
    protected $button = null;
40
41
    /**
42
     * Set options.
43
     *
44
     * @param array|callable|string $options
45
     *
46
     * @return $this|mixed
47
     */
48
    public function options($options = [])
49
    {
50
        // remote options
51
        if (is_string($options)) {
52
            return $this->loadRemoteOptions(...func_get_args());
0 ignored issues
show
Documentation introduced by
func_get_args() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
53
        }
54
55
        if ($options instanceof Arrayable) {
56
            $options = $options->toArray();
57
        }
58
59
        if (is_callable($options)) {
60
            $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
It seems like $options of type callable is incompatible with the declared type array of property $options.

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...
61
        } else {
62
            $this->options = (array) $options;
63
        }
64
65
        return $this;
66
    }
67
68
    /**
69
     * @param array $groups
70
     */
71
72
    /**
73
     * Set option groups.
74
     *
75
     * eg: $group = [
76
     *        [
77
     *        'label' => 'xxxx',
78
     *        'options' => [
79
     *            1 => 'foo',
80
     *            2 => 'bar',
81
     *            ...
82
     *        ],
83
     *        ...
84
     *     ]
85
     *
86
     * @param array $groups
87
     *
88
     * @return $this
89
     */
90
    public function groups(array $groups)
91
    {
92
        $this->groups = $groups;
93
94
        return $this;
95
    }
96
97
    /**
98
     * Load options for other select on change.
99
     *
100
     * @param string $field
101
     * @param string $sourceUrl
102
     * @param string $idField
103
     * @param string $textField
104
     *
105
     * @return $this
106
     */
107
    public function load($field, $sourceUrl, $idField = 'id', $textField = 'text')
108
    {
109
        if (Str::contains($field, '.')) {
110
            $field = $this->formatName($field);
111
            $class = str_replace(['[', ']'], '_', $field);
112
        } else {
113
            $class = $field;
114
        }
115
116
        $script = <<<EOT
117
$(document).off('change', "{$this->getElementClassSelector()}");
118
$(document).on('change', "{$this->getElementClassSelector()}", function () {
119
120
    var target = $(this).closest('.fields-group').find(".$class");
121
     $(target).prop("disabled", true);
122
    $.get("$sourceUrl?q="+this.value, function (data) {
123
        target.find("option").remove();
124
        $(target).select2({
125
            dir: "$this->direction",
126
            language : "$this->local",
127
            data: $.map(data, function (d) {
128
                d.id = d.$idField;
129
                d.text = d.$textField;
130
                return d;
131
            })
132
        }).trigger('change');
133
        $(target).prop("disabled", false);
134
135
    });
136
});
137
EOT;
138
139
        Admin::script($script);
140
141
        return $this;
142
    }
143
144
    /**
145
     * Load options from remote.
146
     *
147
     * @param string $url
148
     * @param array  $parameters
149
     * @param array  $options
150
     *
151
     * @return $this
152
     */
153
    protected function loadRemoteOptions($url, $parameters = [], $options = [])
154
    {
155
        $ajaxOptions = [
156
            'url' => $url.'?'.http_build_query($parameters),
157
        ];
158
159
        $ajaxOptions = json_encode(array_merge($ajaxOptions, $options));
160
161
        $this->script = <<<EOT
162
163
$.ajax($ajaxOptions).done(function(data) {
164
  $("{$this->getElementClassSelector()}").select2({
165
     dir: "$this->direction",
166
     language : "$this->local",
167
     data: data
168
  });
169
});
170
171
EOT;
172
173
        return $this;
174
    }
175
176
    /**
177
     * Load options from ajax results.
178
     *
179
     * @param string $url
180
     * @param $idField
181
     * @param $textField
182
     *
183
     * @return $this
184
     */
185 View Code Duplication
    public function ajax($url, $idField = 'id', $textField = 'text')
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...
186
    {
187
        $this->script = <<<EOT
188
189
$("{$this->getElementClassSelector()}").select2({
190
  ajax: {
191
    url: "$url",
192
    dataType: 'json',
193
    delay: 250,
194
    data: function (params) {
195
      return {
196
        q: params.term,
197
        page: params.page
198
      };
199
    },
200
    processResults: function (data, params) {
201
      params.page = params.page || 1;
202
203
      return {
204
        results: $.map(data.data, function (d) {
205
                   d.id = d.$idField;
206
                   d.text = d.$textField;
207
                   return d;
208
                }),
209
        pagination: {
210
          more: data.next_page_url
211
        }
212
      };
213
    },
214
    cache: true
215
  },
216
  minimumInputLength: 1,
217
  escapeMarkup: function (markup) {
218
      return markup;
219
  },
220
  dir: "$this->direction",
221
  language : "$this->local",
222
});
223
224
EOT;
225
226
        return $this;
227
    }
228
229
    /**
230
     * Set config for select2.
231
     *
232
     * all configurations see https://select2.org/configuration/options-api
233
     *
234
     * @param string $key
235
     * @param mixed  $val
236
     *
237
     * @return $this
238
     */
239
    public function config($key, $val)
240
    {
241
        $this->config[$key] = $val;
242
243
        return $this;
244
    }
245
246
    /**
247
     * add btn group for select2.
248
     *
249
     * @param $text
250
     * @param $btn_url
251
     * @param $ajax_url
252
     * @return $this
253
     * @internal param string $key
254
     * @internal param mixed $val
255
     *
256
     */
257
    public function addButton($text, $btn_url ,$ajax_url)
258
    {
259
        $this->button['text'] = $text;
260
        $this->button['class'] = $this->getElementClassString() . "_btn";
261
        $this->button['script'] = <<<EOT
262
        $(".{$this->button['class']}").on("click",function(){
263
            window.open("{$btn_url}")
264
    });
265
    //instagram
266
        $('{$this->getElementClassSelector()}').change(function(){
267
            $.ajax({
268
        method: 'post',
269
        url: '{$ajax_url}',
270
        data: {
271
                _token: LA.token,
272
            id: $(this).val()
273
        },
274
        success: function (data) {
275
//            $.pjax.reload('#pjax-container');
276
                toastr.success(data.message);
277
            }
278
    });
279
    
280
    });
281
EOT;
282
        return $this;
283
    }
284
285
    /**
286
     * {@inheritdoc}
287
     */
288
    public function render()
289
    {
290
        $configs = array_merge([
291
            'allowClear'  => true,
292
            'placeholder' => $this->label,
293
            'dir'=> "$this->direction",
294
            'language' => "$this->local"
295
        ], $this->config);
296
297
        $configs = json_encode($configs);
298
299
        if (empty($this->script)) {
300
            $this->script = "$(\"{$this->getElementClassSelector()}\").select2($configs);" . $this->button['script'];
301
        }
302
303
        if ($this->options instanceof \Closure) {
304
            if ($this->form) {
305
                $this->options = $this->options->bindTo($this->form->model());
306
            }
307
308
            $this->options(call_user_func($this->options, $this->value));
309
        }
310
311
        $this->options = array_filter($this->options);
312
313
        return parent::render()->with([
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
314
            'options' => $this->options,
315
            'groups'  => $this->groups,
316
            'add_button'  => $this->button,
317
        ]);
318
    }
319
}