Completed
Pull Request — master (#1696)
by Flavio
02:45
created

HasMany::buildRelatedForms()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 45
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 22
nc 7
nop 0
dl 0
loc 45
rs 4.909
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\Support\Facades\Validator;
12
use Illuminate\Support\Str;
13
14
/**
15
 * Class HasMany.
16
 */
17
class HasMany extends Field
18
{
19
    /**
20
     * Relation name.
21
     *
22
     * @var string
23
     */
24
    protected $relationName = '';
25
26
    /**
27
     * Form builder.
28
     *
29
     * @var \Closure
30
     */
31
    protected $builder = null;
32
33
    /**
34
     * Form data.
35
     *
36
     * @var array
37
     */
38
    protected $value = [];
39
40
    /**
41
     * View Mode.
42
     *
43
     * Supports `default` and `tab` currently.
44
     *
45
     * @var string
46
     */
47
    protected $viewMode = 'default';
48
49
    /**
50
     * Available views for HasMany field.
51
     *
52
     * @var array
53
     */
54
    protected $views = [
55
        'default' => 'admin::form.hasmany',
56
        'tab'     => 'admin::form.hasmanytab',
57
    ];
58
59
    /**
60
     * Create a new HasMany field instance.
61
     *
62
     * @param $relationName
63
     * @param array $arguments
64
     */
65 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...
66
    {
67
        $this->relationName = $relationName;
68
69
        $this->column = $relationName;
70
71
        if (count($arguments) == 1) {
72
            $this->label = $this->formatLabel();
73
            $this->builder = $arguments[0];
74
        }
75
76
        if (count($arguments) == 2) {
77
            list($this->label, $this->builder) = $arguments;
78
        }
79
    }
80
81
    /**
82
     * Get validator for this field.
83
     *
84
     * @param array $input
85
     *
86
     * @return bool|Validator
87
     */
88
    public function getValidator(array $input)
89
    {
90
        if (!array_key_exists($this->column, $input)) {
91
            return false;
92
        }
93
94
        $input = array_only($input, $this->column);
95
96
        $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...
97
98
        $rules = $attributes = [];
99
100
        /* @var Field $field */
101
        foreach ($form->fields() as $field) {
102
            if (!$fieldRules = $field->getRules()) {
103
                continue;
104
            }
105
106
            $column = $field->column();
107
108
            if (is_array($column)) {
109
                foreach ($column as $key => $name) {
110
                    $rules[$name.$key] = $fieldRules;
111
                }
112
113
                $this->resetInputKey($input, $column);
114
            } else {
115
                $rules[$column] = $fieldRules;
116
            }
117
118
            $attributes = array_merge(
119
                $attributes,
120
                $this->formatValidationAttribute($input, $field->label(), $column)
121
            );
122
        }
123
124
        array_forget($rules, NestedForm::REMOVE_FLAG_NAME);
125
126
        if (empty($rules)) {
127
            return false;
128
        }
129
130
        $newRules = [];
131
132
        foreach ($rules as $column => $rule) {
133
            foreach (array_keys($input[$this->column]) as $key) {
134
                $newRules["{$this->column}.$key.$column"] = $rule;
135
            }
136
        }
137
138
        return Validator::make($input, $newRules, $this->validationMessages, $attributes);
139
    }
140
141
    /**
142
     * Format validation attributes.
143
     *
144
     * @param array  $input
145
     * @param string $label
146
     * @param string $column
147
     *
148
     * @return array
149
     */
150 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...
151
    {
152
        $new = $attributes = [];
153
154
        if (is_array($column)) {
155
            foreach ($column as $index => $col) {
156
                $new[$col.$index] = $col;
157
            }
158
        }
159
160
        foreach (array_keys(array_dot($input)) as $key) {
161
            if (is_string($column)) {
162
                if (Str::endsWith($key, ".$column")) {
163
                    $attributes[$key] = $label;
164
                }
165
            } else {
166
                foreach ($new as $k => $val) {
167
                    if (Str::endsWith($key, ".$k")) {
168
                        $attributes[$key] = $label."[$val]";
169
                    }
170
                }
171
            }
172
        }
173
174
        return $attributes;
175
    }
176
177
    /**
178
     * Reset input key for validation.
179
     *
180
     * @param array $input
181
     * @param array $column $column is the column name array set
182
     *
183
     * @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...
184
     */
185
    protected function resetInputKey(array &$input, array $column)
186
    {
187
        /**
188
         * flip the column name array set.
189
         *
190
         * for example, for the DateRange, the column like as below
191
         *
192
         * ["start" => "created_at", "end" => "updated_at"]
193
         *
194
         * to:
195
         *
196
         * [ "created_at" => "start", "updated_at" => "end" ]
197
         */
198
        $column = array_flip($column);
199
200
        /**
201
         * $this->column is the inputs array's node name, default is the relation name.
202
         *
203
         * So... $input[$this->column] is the data of this column's inputs data
204
         *
205
         * in the HasMany relation, has many data/field set, $set is field set in the below
206
         */
207
        foreach ($input[$this->column] as $index => $set) {
208
209
            /*
210
             * foreach the field set to find the corresponding $column
211
             */
212 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...
213
                /*
214
                 * if doesn't have column name, continue to the next loop
215
                 */
216
                if (!array_key_exists($name, $column)) {
217
                    continue;
218
                }
219
220
                /**
221
                 * example:  $newKey = created_atstart.
222
                 *
223
                 * Σ( ° △ °|||)︴
224
                 *
225
                 * I don't know why a form need range input? Only can imagine is for range search....
226
                 */
227
                $newKey = $name.$column[$name];
228
229
                /*
230
                 * set new key
231
                 */
232
                array_set($input, "{$this->column}.$index.$newKey", $value);
233
                /*
234
                 * forget the old key and value
235
                 */
236
                array_forget($input, "{$this->column}.$index.$name");
237
            }
238
        }
239
    }
240
241
    /**
242
     * Prepare input data for insert or update.
243
     *
244
     * @param array $input
245
     *
246
     * @return array
247
     */
248
    public function prepare($input)
249
    {
250
        $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...
251
252
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
253
    }
254
255
    /**
256
     * Build a Nested form.
257
     *
258
     * @param string   $column
259
     * @param \Closure $builder
260
     * @param null     $key
261
     *
262
     * @return NestedForm
263
     */
264
    protected function buildNestedForm($column, \Closure $builder, $key = null)
265
    {
266
        $form = new Form\NestedForm($column, $key);
267
268
        $form->setForm($this->form);
269
270
        call_user_func($builder, $form);
271
272
        $form->hidden($this->getKeyName());
273
274
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
275
276
        return $form;
277
    }
278
279
    /**
280
     * Get the HasMany relation key name.
281
     *
282
     * @return string
283
     */
284
    protected function getKeyName()
285
    {
286
        if (is_null($this->form)) {
287
            return;
288
        }
289
290
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
291
    }
292
293
    /**
294
     * Set view mode.
295
     *
296
     * @param string $mode currently support `tab` mode.
297
     *
298
     * @return $this
299
     *
300
     * @author Edwin Hui
301
     */
302
    public function mode($mode)
303
    {
304
        $this->viewMode = $mode;
305
306
        return $this;
307
    }
308
309
    /**
310
     * Use tab mode to showing hasmany field.
311
     *
312
     * @return HasMany
313
     */
314
    public function useTab()
315
    {
316
        return $this->mode('tab');
317
    }
318
319
    /**
320
     * Build Nested form for related data.
321
     *
322
     * @throws \Exception
323
     *
324
     * @return array
325
     */
326
    protected function buildRelatedForms()
327
    {
328
        if (is_null($this->form)) {
329
            return [];
330
        }
331
332
        $model = $this->form->model();
333
334
        $relation = call_user_func([$model, $this->relationName]);
335
336
          if (!$relation instanceof Relation
337
            && !$relation instanceof MorphMany
338
            && !$relation instanceof BelongsToMany) {
0 ignored issues
show
Bug introduced by
The class Encore\Admin\Form\Field\BelongsToMany does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
339
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
340
        }
341
342
        $forms = [];
343
344
        /*
345
         * If redirect from `exception` or `validation error` page.
346
         *
347
         * Then get form data from session flash.
348
         *
349
         * Else get data from database.
350
         */
351
        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...
352
            foreach ($values as $key => $data) {
353
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
354
                    continue;
355
                }
356
357
                $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...
358
                    ->fill($data);
359
            }
360
        } else {
361
            foreach ($this->value as $data) {
362
                $key = array_get($data, $relation->getRelated()->getKeyName());
363
364
                $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...
365
                    ->fill($data);
366
            }
367
        }
368
369
        return $forms;
370
    }
371
372
    /**
373
     * Setup script for this field in different view mode.
374
     *
375
     * @param string $script
376
     *
377
     * @return void
378
     */
379
    protected function setupScript($script)
380
    {
381
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
382
383
        call_user_func([$this, $method], $script);
384
    }
385
386
    /**
387
     * Setup default template script.
388
     *
389
     * @param string $templateScript
390
     *
391
     * @return void
392
     */
393 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...
394
    {
395
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
396
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
397
398
        /**
399
         * When add a new sub form, replace all element key in new sub form.
400
         *
401
         * @example comments[new___key__][title]  => comments[new_{index}][title]
402
         *
403
         * {count} is increment number of current sub form count.
404
         */
405
        $script = <<<EOT
406
var index = 0;
407
$('#has-many-{$this->column}').on('click', '.add', function () {
408
409
    var tpl = $('template.{$this->column}-tpl');
410
411
    index++;
412
413
    var template = tpl.html().replace(/{$defaultKey}/g, index);
414
    $('.has-many-{$this->column}-forms').append(template);
415
    {$templateScript}
416
});
417
418
$('#has-many-{$this->column}').on('click', '.remove', function () {
419
    $(this).closest('.has-many-{$this->column}-form').hide();
420
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
421
});
422
423
EOT;
424
425
        Admin::script($script);
426
    }
427
428
    /**
429
     * Setup tab template script.
430
     *
431
     * @param string $templateScript
432
     *
433
     * @return void
434
     */
435 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...
436
    {
437
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
438
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
439
440
        $script = <<<EOT
441
442
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
443
    var \$navTab = $(this).siblings('a');
444
    var \$pane = $(\$navTab.attr('href'));
445
    if( \$pane.hasClass('new') ){
446
        \$pane.remove();
447
    }else{
448
        \$pane.removeClass('active').find('.$removeClass').val(1);
449
    }
450
    if(\$navTab.closest('li').hasClass('active')){
451
        \$navTab.closest('li').remove();
452
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
453
    }else{
454
        \$navTab.closest('li').remove();
455
    }
456
});
457
458
var index = 0;
459
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
460
    index++;
461
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
462
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
463
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
464
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
465
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
466
    {$templateScript}
467
});
468
469
if ($('.has-error').length) {
470
    $('.has-error').parent('.tab-pane').each(function () {
471
        var tabId = '#'+$(this).attr('id');
472
        $('li a[href="'+tabId+'"] i').removeClass('hide');
473
    });
474
    
475
    var first = $('.has-error:first').parent().attr('id');
476
    $('li a[href="#'+first+'"]').tab('show');
477
}
478
EOT;
479
480
        Admin::script($script);
481
    }
482
483
    /**
484
     * Render the `HasMany` field.
485
     *
486
     * @throws \Exception
487
     *
488
     * @return \Illuminate\View\View
489
     */
490
    public function render()
491
    {
492
        // specify a view to render.
493
        $this->view = $this->views[$this->viewMode];
494
495
        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...
496
            ->getTemplateHtmlAndScript();
497
498
        $this->setupScript($script);
499
500
        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...
501
            'forms'        => $this->buildRelatedForms(),
502
            'template'     => $template,
503
            'relationName' => $this->relationName,
504
        ]);
505
    }
506
}
507