Completed
Pull Request — master (#1697)
by Flavio
03:16
created

HasMany::setupScriptForDefaultView()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 34
Code Lines 15

Duplication

Lines 34
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 1
dl 34
loc 34
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Admin;
6
use Encore\Admin\Form;
7
use Encore\Admin\Form\Field;
8
use Encore\Admin\Form\NestedForm;
9
use Illuminate\Database\Eloquent\Relations\HasMany as Relation;
10
use Illuminate\Database\Eloquent\Relations\MorphMany;
11
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
12
use Illuminate\Support\Facades\Validator;
13
use Illuminate\Support\Str;
14
15
/**
16
 * Class HasMany.
17
 */
18
class HasMany extends Field
19
{
20
    /**
21
     * Relation name.
22
     *
23
     * @var string
24
     */
25
    protected $relationName = '';
26
27
    /**
28
     * Form builder.
29
     *
30
     * @var \Closure
31
     */
32
    protected $builder = null;
33
34
    /**
35
     * Form data.
36
     *
37
     * @var array
38
     */
39
    protected $value = [];
40
41
    /**
42
     * View Mode.
43
     *
44
     * Supports `default` and `tab` currently.
45
     *
46
     * @var string
47
     */
48
    protected $viewMode = 'default';
49
50
    /**
51
     * Available views for HasMany field.
52
     *
53
     * @var array
54
     */
55
    protected $views = [
56
        'default' => 'admin::form.hasmany',
57
        'tab'     => 'admin::form.hasmanytab',
58
    ];
59
60
    /**
61
     * Create a new HasMany field instance.
62
     *
63
     * @param $relationName
64
     * @param array $arguments
65
     */
66 View Code Duplication
    public function __construct($relationName, $arguments = [])
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...
67
    {
68
        $this->relationName = $relationName;
69
70
        $this->column = $relationName;
71
72
        if (count($arguments) == 1) {
73
            $this->label = $this->formatLabel();
74
            $this->builder = $arguments[0];
75
        }
76
77
        if (count($arguments) == 2) {
78
            list($this->label, $this->builder) = $arguments;
79
        }
80
    }
81
82
    /**
83
     * Get validator for this field.
84
     *
85
     * @param array $input
86
     *
87
     * @return bool|Validator
88
     */
89
    public function getValidator(array $input)
90
    {
91
        if (!array_key_exists($this->column, $input)) {
92
            return false;
93
        }
94
95
        $input = array_only($input, $this->column);
96
97
        $form = $this->buildNestedForm($this->column, $this->builder);
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
98
99
        $rules = $attributes = [];
100
101
        /* @var Field $field */
102
        foreach ($form->fields() as $field) {
103
            if (!$fieldRules = $field->getRules()) {
104
                continue;
105
            }
106
107
            $column = $field->column();
108
109
            if (is_array($column)) {
110
                foreach ($column as $key => $name) {
111
                    $rules[$name.$key] = $fieldRules;
112
                }
113
114
                $this->resetInputKey($input, $column);
115
            } else {
116
                $rules[$column] = $fieldRules;
117
            }
118
119
            $attributes = array_merge(
120
                $attributes,
121
                $this->formatValidationAttribute($input, $field->label(), $column)
122
            );
123
        }
124
125
        array_forget($rules, NestedForm::REMOVE_FLAG_NAME);
126
127
        if (empty($rules)) {
128
            return false;
129
        }
130
131
        $newRules = [];
132
133
        foreach ($rules as $column => $rule) {
134
            foreach (array_keys($input[$this->column]) as $key) {
135
                $newRules["{$this->column}.$key.$column"] = $rule;
136
            }
137
        }
138
139
        return Validator::make($input, $newRules, $this->validationMessages, $attributes);
140
    }
141
142
    /**
143
     * Format validation attributes.
144
     *
145
     * @param array  $input
146
     * @param string $label
147
     * @param string $column
148
     *
149
     * @return array
150
     */
151 View Code Duplication
    protected function formatValidationAttribute($input, $label, $column)
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...
152
    {
153
        $new = $attributes = [];
154
155
        if (is_array($column)) {
156
            foreach ($column as $index => $col) {
157
                $new[$col.$index] = $col;
158
            }
159
        }
160
161
        foreach (array_keys(array_dot($input)) as $key) {
162
            if (is_string($column)) {
163
                if (Str::endsWith($key, ".$column")) {
164
                    $attributes[$key] = $label;
165
                }
166
            } else {
167
                foreach ($new as $k => $val) {
168
                    if (Str::endsWith($key, ".$k")) {
169
                        $attributes[$key] = $label."[$val]";
170
                    }
171
                }
172
            }
173
        }
174
175
        return $attributes;
176
    }
177
178
    /**
179
     * Reset input key for validation.
180
     *
181
     * @param array $input
182
     * @param array $column $column is the column name array set
183
     *
184
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
185
     */
186
    protected function resetInputKey(array &$input, array $column)
187
    {
188
        /**
189
         * flip the column name array set.
190
         *
191
         * for example, for the DateRange, the column like as below
192
         *
193
         * ["start" => "created_at", "end" => "updated_at"]
194
         *
195
         * to:
196
         *
197
         * [ "created_at" => "start", "updated_at" => "end" ]
198
         */
199
        $column = array_flip($column);
200
201
        /**
202
         * $this->column is the inputs array's node name, default is the relation name.
203
         *
204
         * So... $input[$this->column] is the data of this column's inputs data
205
         *
206
         * in the HasMany relation, has many data/field set, $set is field set in the below
207
         */
208
        foreach ($input[$this->column] as $index => $set) {
209
210
            /*
211
             * foreach the field set to find the corresponding $column
212
             */
213 View Code Duplication
            foreach ($set as $name => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
214
                /*
215
                 * if doesn't have column name, continue to the next loop
216
                 */
217
                if (!array_key_exists($name, $column)) {
218
                    continue;
219
                }
220
221
                /**
222
                 * example:  $newKey = created_atstart.
223
                 *
224
                 * Σ( ° △ °|||)︴
225
                 *
226
                 * I don't know why a form need range input? Only can imagine is for range search....
227
                 */
228
                $newKey = $name.$column[$name];
229
230
                /*
231
                 * set new key
232
                 */
233
                array_set($input, "{$this->column}.$index.$newKey", $value);
234
                /*
235
                 * forget the old key and value
236
                 */
237
                array_forget($input, "{$this->column}.$index.$name");
238
            }
239
        }
240
    }
241
242
    /**
243
     * Prepare input data for insert or update.
244
     *
245
     * @param array $input
246
     *
247
     * @return array
248
     */
249
    public function prepare($input)
250
    {
251
        $form = $this->buildNestedForm($this->column, $this->builder);
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
252
253
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
254
    }
255
256
    /**
257
     * Build a Nested form.
258
     *
259
     * @param string   $column
260
     * @param \Closure $builder
261
     * @param null     $key
262
     *
263
     * @return NestedForm
264
     */
265
    protected function buildNestedForm($column, \Closure $builder, $key = null)
266
    {
267
        $form = new Form\NestedForm($column, $key);
268
269
        $form->setForm($this->form);
270
271
        call_user_func($builder, $form);
272
273
        $form->hidden($this->getKeyName());
274
275
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
276
277
        return $form;
278
    }
279
280
    /**
281
     * Get the HasMany relation key name.
282
     *
283
     * @return string
284
     */
285
    protected function getKeyName()
286
    {
287
        if (is_null($this->form)) {
288
            return;
289
        }
290
291
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
292
    }
293
294
    /**
295
     * Set view mode.
296
     *
297
     * @param string $mode currently support `tab` mode.
298
     *
299
     * @return $this
300
     *
301
     * @author Edwin Hui
302
     */
303
    public function mode($mode)
304
    {
305
        $this->viewMode = $mode;
306
307
        return $this;
308
    }
309
310
    /**
311
     * Use tab mode to showing hasmany field.
312
     *
313
     * @return HasMany
314
     */
315
    public function useTab()
316
    {
317
        return $this->mode('tab');
318
    }
319
320
    /**
321
     * Build Nested form for related data.
322
     *
323
     * @throws \Exception
324
     *
325
     * @return array
326
     */
327
    protected function buildRelatedForms()
328
    {
329
        if (is_null($this->form)) {
330
            return [];
331
        }
332
333
        $model = $this->form->model();
334
335
        $relation = call_user_func([$model, $this->relationName]);
336
337
          if (!$relation instanceof Relation
338
            && !$relation instanceof MorphMany
339
            && !$relation instanceof BelongsToMany) {
340
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
341
        }
342
343
        $forms = [];
344
345
        /*
346
         * If redirect from `exception` or `validation error` page.
347
         *
348
         * Then get form data from session flash.
349
         *
350
         * Else get data from database.
351
         */
352
        if ($values = old($this->column)) {
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, old() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
353
            foreach ($values as $key => $data) {
354
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
355
                    continue;
356
                }
357
358
                $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key)
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
359
                    ->fill($data);
360
            }
361
        } else {
362
            foreach ($this->value as $data) {
363
                $key = array_get($data, $relation->getRelated()->getKeyName());
364
365
                $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key)
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
366
                    ->fill($data);
367
            }
368
        }
369
370
        return $forms;
371
    }
372
373
    /**
374
     * Setup script for this field in different view mode.
375
     *
376
     * @param string $script
377
     *
378
     * @return void
379
     */
380
    protected function setupScript($script)
381
    {
382
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
383
384
        call_user_func([$this, $method], $script);
385
    }
386
387
    /**
388
     * Setup default template script.
389
     *
390
     * @param string $templateScript
391
     *
392
     * @return void
393
     */
394 View Code Duplication
    protected function setupScriptForDefaultView($templateScript)
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...
395
    {
396
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
397
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
398
399
        /**
400
         * When add a new sub form, replace all element key in new sub form.
401
         *
402
         * @example comments[new___key__][title]  => comments[new_{index}][title]
403
         *
404
         * {count} is increment number of current sub form count.
405
         */
406
        $script = <<<EOT
407
var index = 0;
408
$('#has-many-{$this->column}').on('click', '.add', function () {
409
410
    var tpl = $('template.{$this->column}-tpl');
411
412
    index++;
413
414
    var template = tpl.html().replace(/{$defaultKey}/g, index);
415
    $('.has-many-{$this->column}-forms').append(template);
416
    {$templateScript}
417
});
418
419
$('#has-many-{$this->column}').on('click', '.remove', function () {
420
    $(this).closest('.has-many-{$this->column}-form').hide();
421
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
422
});
423
424
EOT;
425
426
        Admin::script($script);
427
    }
428
429
    /**
430
     * Setup tab template script.
431
     *
432
     * @param string $templateScript
433
     *
434
     * @return void
435
     */
436 View Code Duplication
    protected function setupScriptForTabView($templateScript)
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...
437
    {
438
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
439
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
440
441
        $script = <<<EOT
442
443
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
444
    var \$navTab = $(this).siblings('a');
445
    var \$pane = $(\$navTab.attr('href'));
446
    if( \$pane.hasClass('new') ){
447
        \$pane.remove();
448
    }else{
449
        \$pane.removeClass('active').find('.$removeClass').val(1);
450
    }
451
    if(\$navTab.closest('li').hasClass('active')){
452
        \$navTab.closest('li').remove();
453
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
454
    }else{
455
        \$navTab.closest('li').remove();
456
    }
457
});
458
459
var index = 0;
460
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
461
    index++;
462
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
463
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
464
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
465
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
466
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
467
    {$templateScript}
468
});
469
470
if ($('.has-error').length) {
471
    $('.has-error').parent('.tab-pane').each(function () {
472
        var tabId = '#'+$(this).attr('id');
473
        $('li a[href="'+tabId+'"] i').removeClass('hide');
474
    });
475
    
476
    var first = $('.has-error:first').parent().attr('id');
477
    $('li a[href="#'+first+'"]').tab('show');
478
}
479
EOT;
480
481
        Admin::script($script);
482
    }
483
484
    /**
485
     * Render the `HasMany` field.
486
     *
487
     * @throws \Exception
488
     *
489
     * @return \Illuminate\View\View
490
     */
491
    public function render()
492
    {
493
        // specify a view to render.
494
        $this->view = $this->views[$this->viewMode];
495
496
        list($template, $script) = $this->buildNestedForm($this->column, $this->builder)
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
497
            ->getTemplateHtmlAndScript();
498
499
        $this->setupScript($script);
500
501
        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...
502
            'forms'        => $this->buildRelatedForms(),
503
            'template'     => $template,
504
            'relationName' => $this->relationName,
505
        ]);
506
    }
507
}
508