Completed
Pull Request — master (#2622)
by
unknown
02:40
created

HasMany::getFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
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
        $newInput = [];
132
133
        foreach ($rules as $column => $rule) {
134
            foreach (array_keys($input[$this->column]) as $key) {
135
                $newRules["{$this->column}.$key.$column"] = $rule;
136
                if (isset($input[$this->column][$key][$column])) {
137
                    foreach ($input[$this->column][$key][$column] as $vkey => $value) {
138
                        $newInput["{$this->column}.$key.{$column}$vkey"] = $value;
139
                    }
140
                }
141
            }
142
        }
143
144
        return Validator::make($newInput, $newRules, $this->validationMessages, $attributes);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Illuminate\Suppo...Messages, $attributes); (Illuminate\Contracts\Validation\Validator) is incompatible with the return type of the parent method Encore\Admin\Form\Field::getValidator of type boolean|Illuminate\Support\Facades\Validator.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
145
    }
146
147
    /**
148
     * Format validation attributes.
149
     *
150
     * @param array  $input
151
     * @param string $label
152
     * @param string $column
153
     *
154
     * @return array
155
     */
156 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...
157
    {
158
        $new = $attributes = [];
159
160
        if (is_array($column)) {
161
            foreach ($column as $index => $col) {
162
                $new[$col.$index] = $col;
163
            }
164
        }
165
166
        foreach (array_keys(array_dot($input)) as $key) {
167
            if (is_string($column)) {
168
                if (Str::endsWith($key, ".$column")) {
169
                    $attributes[$key] = $label;
170
                }
171
            } else {
172
                foreach ($new as $k => $val) {
173
                    if (Str::endsWith($key, ".$k")) {
174
                        $attributes[$key] = $label."[$val]";
175
                    }
176
                }
177
            }
178
        }
179
180
        return $attributes;
181
    }
182
183
    /**
184
     * Reset input key for validation.
185
     *
186
     * @param array $input
187
     * @param array $column $column is the column name array set
188
     *
189
     * @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...
190
     */
191
    protected function resetInputKey(array &$input, array $column)
192
    {
193
        /**
194
         * flip the column name array set.
195
         *
196
         * for example, for the DateRange, the column like as below
197
         *
198
         * ["start" => "created_at", "end" => "updated_at"]
199
         *
200
         * to:
201
         *
202
         * [ "created_at" => "start", "updated_at" => "end" ]
203
         */
204
        $column = array_flip($column);
205
206
        /**
207
         * $this->column is the inputs array's node name, default is the relation name.
208
         *
209
         * So... $input[$this->column] is the data of this column's inputs data
210
         *
211
         * in the HasMany relation, has many data/field set, $set is field set in the below
212
         */
213
        foreach ($input[$this->column] as $index => $set) {
214
215
            /*
216
             * foreach the field set to find the corresponding $column
217
             */
218 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...
219
                /*
220
                 * if doesn't have column name, continue to the next loop
221
                 */
222
                if (!array_key_exists($name, $column)) {
223
                    continue;
224
                }
225
226
                /**
227
                 * example:  $newKey = created_atstart.
228
                 *
229
                 * Σ( ° △ °|||)︴
230
                 *
231
                 * I don't know why a form need range input? Only can imagine is for range search....
232
                 */
233
                $newKey = $name.$column[$name];
234
235
                /*
236
                 * set new key
237
                 */
238
                array_set($input, "{$this->column}.$index.$newKey", $value);
239
                /*
240
                 * forget the old key and value
241
                 */
242
                array_forget($input, "{$this->column}.$index.$name");
243
            }
244
        }
245
    }
246
247
    /**
248
     * Prepare input data for insert or update.
249
     *
250
     * @param array $input
251
     *
252
     * @return array
253
     */
254
    public function prepare($input)
255
    {
256
        $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...
257
258
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
259
    }
260
        
261
    /**
262
     * Get fields for Nested form.
263
     * @return Collection
264
     */
265
    public function getFields(){
266
        return $this->buildNestedForm($this->column, $this->builder)->fields();
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...
267
    }
268
269
270
    /**
271
     * Build a Nested form.
272
     *
273
     * @param string   $column
274
     * @param \Closure $builder
275
     * @param null     $key
276
     *
277
     * @return NestedForm
278
     */
279
    protected function buildNestedForm($column, \Closure $builder, $key = null)
280
    {
281
        $form = new Form\NestedForm($column, $key);
282
283
        $form->setForm($this->form);
284
285
        call_user_func($builder, $form);
286
287
        $form->hidden($this->getKeyName());
288
289
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
290
291
        return $form;
292
    }
293
294
    /**
295
     * Get the HasMany relation key name.
296
     *
297
     * @return string
298
     */
299
    protected function getKeyName()
300
    {
301
        if (is_null($this->form)) {
302
            return;
303
        }
304
305
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
306
    }
307
308
    /**
309
     * Set view mode.
310
     *
311
     * @param string $mode currently support `tab` mode.
312
     *
313
     * @return $this
314
     *
315
     * @author Edwin Hui
316
     */
317
    public function mode($mode)
318
    {
319
        $this->viewMode = $mode;
320
321
        return $this;
322
    }
323
324
    /**
325
     * Use tab mode to showing hasmany field.
326
     *
327
     * @return HasMany
328
     */
329
    public function useTab()
330
    {
331
        return $this->mode('tab');
332
    }
333
334
    /**
335
     * Build Nested form for related data.
336
     *
337
     * @throws \Exception
338
     *
339
     * @return array
340
     */
341
    protected function buildRelatedForms()
342
    {
343
        if (is_null($this->form)) {
344
            return [];
345
        }
346
347
        $model = $this->form->model();
348
349
        $relation = call_user_func([$model, $this->relationName]);
350
351
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
352
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
353
        }
354
355
        $forms = [];
356
357
        /*
358
         * If redirect from `exception` or `validation error` page.
359
         *
360
         * Then get form data from session flash.
361
         *
362
         * Else get data from database.
363
         */
364
        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...
365
            foreach ($values as $key => $data) {
366
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
367
                    continue;
368
                }
369
370
                $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...
371
                    ->fill($data);
372
            }
373
        } else {
374
            foreach ($this->value as $data) {
375
                $key = array_get($data, $relation->getRelated()->getKeyName());
376
377
                $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...
378
                    ->fill($data);
379
            }
380
        }
381
382
        return $forms;
383
    }
384
385
    /**
386
     * Setup script for this field in different view mode.
387
     *
388
     * @param string $script
389
     *
390
     * @return void
391
     */
392
    protected function setupScript($script)
393
    {
394
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
395
396
        call_user_func([$this, $method], $script);
397
    }
398
399
    /**
400
     * Setup default template script.
401
     *
402
     * @param string $templateScript
403
     *
404
     * @return void
405
     */
406 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...
407
    {
408
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
409
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
410
411
        /**
412
         * When add a new sub form, replace all element key in new sub form.
413
         *
414
         * @example comments[new___key__][title]  => comments[new_{index}][title]
415
         *
416
         * {count} is increment number of current sub form count.
417
         */
418
        $script = <<<EOT
419
var index = 0;
420
$('#has-many-{$this->column}').on('click', '.add', function () {
421
422
    var tpl = $('template.{$this->column}-tpl');
423
424
    index++;
425
426
    var template = tpl.html().replace(/{$defaultKey}/g, index);
427
    $('.has-many-{$this->column}-forms').append(template);
428
    {$templateScript}
429
});
430
431
$('#has-many-{$this->column}').on('click', '.remove', function () {
432
    $(this).closest('.has-many-{$this->column}-form').hide();
433
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
434
});
435
436
EOT;
437
438
        Admin::script($script);
439
    }
440
441
    /**
442
     * Setup tab template script.
443
     *
444
     * @param string $templateScript
445
     *
446
     * @return void
447
     */
448 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...
449
    {
450
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
451
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
452
453
        $script = <<<EOT
454
455
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
456
    var \$navTab = $(this).siblings('a');
457
    var \$pane = $(\$navTab.attr('href'));
458
    if( \$pane.hasClass('new') ){
459
        \$pane.remove();
460
    }else{
461
        \$pane.removeClass('active').find('.$removeClass').val(1);
462
    }
463
    if(\$navTab.closest('li').hasClass('active')){
464
        \$navTab.closest('li').remove();
465
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
466
    }else{
467
        \$navTab.closest('li').remove();
468
    }
469
});
470
471
var index = 0;
472
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
473
    index++;
474
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
475
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
476
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
477
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
478
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
479
    {$templateScript}
480
});
481
482
if ($('.has-error').length) {
483
    $('.has-error').parent('.tab-pane').each(function () {
484
        var tabId = '#'+$(this).attr('id');
485
        $('li a[href="'+tabId+'"] i').removeClass('hide');
486
    });
487
    
488
    var first = $('.has-error:first').parent().attr('id');
489
    $('li a[href="#'+first+'"]').tab('show');
490
}
491
EOT;
492
493
        Admin::script($script);
494
    }
495
496
    /**
497
     * Render the `HasMany` field.
498
     *
499
     * @throws \Exception
500
     *
501
     * @return \Illuminate\View\View
502
     */
503
    public function render()
504
    {
505
        // specify a view to render.
506
        $this->view = $this->views[$this->viewMode];
507
508
        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...
509
            ->getTemplateHtmlAndScript();
510
511
        $this->setupScript($script);
512
513
        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...
514
            'forms'        => $this->buildRelatedForms(),
515
            'template'     => $template,
516
            'relationName' => $this->relationName,
517
        ]);
518
    }
519
}
520