Completed
Pull Request — master (#3215)
by Hiroyuki
02:22
created

HasMany::useTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
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
        'table'   => 'admin::form.hasmanytable',
58
    ];
59
60
    /**
61
     * Options for template.
62
     *
63
     * @var array
64
     */
65
    protected $options = [
66
        'allowCreate' => true,
67
        'allowDelete' => true,
68
    ];
69
70
    /**
71
     * Create a new HasMany field instance.
72
     *
73
     * @param $relationName
74
     * @param array $arguments
75
     */
76 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...
77
    {
78
        $this->relationName = $relationName;
79
80
        $this->column = $relationName;
81
82
        if (count($arguments) == 1) {
83
            $this->label = $this->formatLabel();
84
            $this->builder = $arguments[0];
85
        }
86
87
        if (count($arguments) == 2) {
88
            list($this->label, $this->builder) = $arguments;
89
        }
90
    }
91
92
    /**
93
     * Get validator for this field.
94
     *
95
     * @param array $input
96
     *
97
     * @return bool|Validator
98
     */
99
    public function getValidator(array $input)
100
    {
101
        if (!array_key_exists($this->column, $input)) {
102
            return false;
103
        }
104
105
        $input = array_only($input, $this->column);
0 ignored issues
show
Deprecated Code introduced by
The function array_only() has been deprecated with message: Arr::only() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
106
107
        foreach ($input[$this->column] as $ikey => $ivalue) {
108
            if (isset($ivalue[NestedForm::REMOVE_FLAG_NAME]) && $ivalue[NestedForm::REMOVE_FLAG_NAME] == 1) {
109
                unset($input[$this->column][$ikey]);
110
            }
111
        }
112
113
        $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...
114
115
        $rules = $attributes = [];
116
117
        /* @var Field $field */
118
        foreach ($form->fields() as $field) {
119
            if (!$fieldRules = $field->getRules()) {
120
                continue;
121
            }
122
123
            $column = $field->column();
124
125
            if (is_array($column)) {
126
                foreach ($column as $key => $name) {
127
                    $rules[$name.$key] = $fieldRules;
128
                }
129
130
                $this->resetInputKey($input, $column);
131
            } else {
132
                $rules[$column] = $fieldRules;
133
            }
134
135
            $attributes = array_merge(
136
                $attributes,
137
                $this->formatValidationAttribute($input, $field->label(), $column)
138
            );
139
        }
140
141
        array_forget($rules, NestedForm::REMOVE_FLAG_NAME);
0 ignored issues
show
Deprecated Code introduced by
The function array_forget() has been deprecated with message: Arr::forget() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
142
143
        if (empty($rules)) {
144
            return false;
145
        }
146
147
        $newRules = [];
148
        $newInput = [];
149
150
        foreach ($rules as $column => $rule) {
151
            foreach (array_keys($input[$this->column]) as $key) {
152
                $newRules["{$this->column}.$key.$column"] = $rule;
153
                if (isset($input[$this->column][$key][$column]) &&
154
                    is_array($input[$this->column][$key][$column])) {
155
                    foreach ($input[$this->column][$key][$column] as $vkey => $value) {
156
                        $newInput["{$this->column}.$key.{$column}$vkey"] = $value;
157
                    }
158
                }
159
            }
160
        }
161
162
        if (empty($newInput)) {
163
            $newInput = $input;
164
        }
165
166
        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...
167
    }
168
169
    /**
170
     * Format validation attributes.
171
     *
172
     * @param array  $input
173
     * @param string $label
174
     * @param string $column
175
     *
176
     * @return array
177
     */
178 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...
179
    {
180
        $new = $attributes = [];
181
182
        if (is_array($column)) {
183
            foreach ($column as $index => $col) {
184
                $new[$col.$index] = $col;
185
            }
186
        }
187
188
        foreach (array_keys(array_dot($input)) as $key) {
0 ignored issues
show
Deprecated Code introduced by
The function array_dot() has been deprecated with message: Arr::dot() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
189
            if (is_string($column)) {
190
                if (Str::endsWith($key, ".$column")) {
191
                    $attributes[$key] = $label;
192
                }
193
            } else {
194
                foreach ($new as $k => $val) {
195
                    if (Str::endsWith($key, ".$k")) {
196
                        $attributes[$key] = $label."[$val]";
197
                    }
198
                }
199
            }
200
        }
201
202
        return $attributes;
203
    }
204
205
    /**
206
     * Reset input key for validation.
207
     *
208
     * @param array $input
209
     * @param array $column $column is the column name array set
210
     *
211
     * @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...
212
     */
213
    protected function resetInputKey(array &$input, array $column)
214
    {
215
        /**
216
         * flip the column name array set.
217
         *
218
         * for example, for the DateRange, the column like as below
219
         *
220
         * ["start" => "created_at", "end" => "updated_at"]
221
         *
222
         * to:
223
         *
224
         * [ "created_at" => "start", "updated_at" => "end" ]
225
         */
226
        $column = array_flip($column);
227
228
        /**
229
         * $this->column is the inputs array's node name, default is the relation name.
230
         *
231
         * So... $input[$this->column] is the data of this column's inputs data
232
         *
233
         * in the HasMany relation, has many data/field set, $set is field set in the below
234
         */
235
        foreach ($input[$this->column] as $index => $set) {
236
237
            /*
238
             * foreach the field set to find the corresponding $column
239
             */
240 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...
241
                /*
242
                 * if doesn't have column name, continue to the next loop
243
                 */
244
                if (!array_key_exists($name, $column)) {
245
                    continue;
246
                }
247
248
                /**
249
                 * example:  $newKey = created_atstart.
250
                 *
251
                 * Σ( ° △ °|||)︴
252
                 *
253
                 * I don't know why a form need range input? Only can imagine is for range search....
254
                 */
255
                $newKey = $name.$column[$name];
256
257
                /*
258
                 * set new key
259
                 */
260
                array_set($input, "{$this->column}.$index.$newKey", $value);
0 ignored issues
show
Deprecated Code introduced by
The function array_set() has been deprecated with message: Arr::set() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
261
                /*
262
                 * forget the old key and value
263
                 */
264
                array_forget($input, "{$this->column}.$index.$name");
0 ignored issues
show
Deprecated Code introduced by
The function array_forget() has been deprecated with message: Arr::forget() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
265
            }
266
        }
267
    }
268
269
    /**
270
     * Prepare input data for insert or update.
271
     *
272
     * @param array $input
273
     *
274
     * @return array
275
     */
276
    public function prepare($input)
277
    {
278
        $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...
279
280
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
281
    }
282
283
    /**
284
     * Build a Nested form.
285
     *
286
     * @param string   $column
287
     * @param \Closure $builder
288
     * @param null     $model
289
     *
290
     * @return NestedForm
291
     */
292
    protected function buildNestedForm($column, \Closure $builder, $model = null)
293
    {
294
        $form = new Form\NestedForm($column, $model);
295
296
        $form->setForm($this->form);
297
298
        call_user_func($builder, $form);
299
300
        $form->hidden($this->getKeyName());
301
302
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
303
304
        return $form;
305
    }
306
307
    /**
308
     * Get the HasMany relation key name.
309
     *
310
     * @return string
311
     */
312
    protected function getKeyName()
313
    {
314
        if (is_null($this->form)) {
315
            return;
316
        }
317
318
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
319
    }
320
321
    /**
322
     * Set view mode.
323
     *
324
     * @param string $mode currently support `tab` mode.
325
     *
326
     * @return $this
327
     *
328
     * @author Edwin Hui
329
     */
330
    public function mode($mode)
331
    {
332
        $this->viewMode = $mode;
333
334
        return $this;
335
    }
336
337
    /**
338
     * Use tab mode to showing hasmany field.
339
     *
340
     * @return HasMany
341
     */
342
    public function useTab()
343
    {
344
        return $this->mode('tab');
345
    }
346
347
    /**
348
     * Use table mode to showing hasmany field.
349
     *
350
     * @return HasMany
351
     */
352
    public function useTable()
353
    {
354
        return $this->mode('table');
355
    }
356
357
    /**
358
     * Build Nested form for related data.
359
     *
360
     * @throws \Exception
361
     *
362
     * @return array
363
     */
364
    protected function buildRelatedForms()
365
    {
366
        if (is_null($this->form)) {
367
            return [];
368
        }
369
370
        $model = $this->form->model();
371
372
        $relation = call_user_func([$model, $this->relationName]);
373
374
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
375
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
376
        }
377
378
        $forms = [];
379
380
        /*
381
         * If redirect from `exception` or `validation error` page.
382
         *
383
         * Then get form data from session flash.
384
         *
385
         * Else get data from database.
386
         */
387
        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...
388
            foreach ($values as $key => $data) {
389
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
390
                    continue;
391
                }
392
393
                $model = $relation->getRelated()->replicate()->forceFill($data);
394
395
                $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $model)
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...
396
                    ->fill($data);
397
            }
398
        } else {
399
            foreach ($this->value as $data) {
400
                $key = array_get($data, $relation->getRelated()->getKeyName());
0 ignored issues
show
Deprecated Code introduced by
The function array_get() has been deprecated with message: Arr::get() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
401
402
                $model = $relation->getRelated()->replicate()->forceFill($data);
403
404
                $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $model)
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...
405
                    ->fill($data);
406
            }
407
        }
408
409
        return $forms;
410
    }
411
412
    /**
413
     * Setup script for this field in different view mode.
414
     *
415
     * @param string $script
416
     *
417
     * @return void
418
     */
419
    protected function setupScript($script)
420
    {
421
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
422
423
        call_user_func([$this, $method], $script);
424
    }
425
426
    /**
427
     * Setup default template script.
428
     *
429
     * @param string $templateScript
430
     *
431
     * @return void
432
     */
433 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...
434
    {
435
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
436
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
437
438
        /**
439
         * When add a new sub form, replace all element key in new sub form.
440
         *
441
         * @example comments[new___key__][title]  => comments[new_{index}][title]
442
         *
443
         * {count} is increment number of current sub form count.
444
         */
445
        $script = <<<EOT
446
var index = 0;
447
$('#has-many-{$this->column}').on('click', '.add', function () {
448
449
    var tpl = $('template.{$this->column}-tpl');
450
451
    index++;
452
453
    var template = tpl.html().replace(/{$defaultKey}/g, index);
454
    $('.has-many-{$this->column}-forms').append(template);
455
    {$templateScript}
456
});
457
458
$('#has-many-{$this->column}').on('click', '.remove', function () {
459
    $(this).closest('.has-many-{$this->column}-form').hide();
460
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
461
});
462
463
EOT;
464
465
        Admin::script($script);
466
    }
467
468
    /**
469
     * Setup tab template script.
470
     *
471
     * @param string $templateScript
472
     *
473
     * @return void
474
     */
475 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...
476
    {
477
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
478
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
479
480
        $script = <<<EOT
481
482
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
483
    var \$navTab = $(this).siblings('a');
484
    var \$pane = $(\$navTab.attr('href'));
485
    if( \$pane.hasClass('new') ){
486
        \$pane.remove();
487
    }else{
488
        \$pane.removeClass('active').find('.$removeClass').val(1);
489
    }
490
    if(\$navTab.closest('li').hasClass('active')){
491
        \$navTab.closest('li').remove();
492
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
493
    }else{
494
        \$navTab.closest('li').remove();
495
    }
496
});
497
498
var index = 0;
499
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
500
    index++;
501
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
502
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
503
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
504
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
505
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
506
    {$templateScript}
507
});
508
509
if ($('.has-error').length) {
510
    $('.has-error').parent('.tab-pane').each(function () {
511
        var tabId = '#'+$(this).attr('id');
512
        $('li a[href="'+tabId+'"] i').removeClass('hide');
513
    });
514
    
515
    var first = $('.has-error:first').parent().attr('id');
516
    $('li a[href="#'+first+'"]').tab('show');
517
}
518
EOT;
519
520
        Admin::script($script);
521
    }
522
523
    /**
524
     * Setup default template script.
525
     *
526
     * @param string $templateScript
527
     *
528
     * @return void
529
     */
530 View Code Duplication
    protected function setupScriptForTableView($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...
531
    {
532
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
533
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
534
535
        /**
536
         * When add a new sub form, replace all element key in new sub form.
537
         *
538
         * @example comments[new___key__][title]  => comments[new_{index}][title]
539
         *
540
         * {count} is increment number of current sub form count.
541
         */
542
        $script = <<<EOT
543
var index = 0;
544
$('#has-many-{$this->column}').on('click', '.add', function () {
545
546
    var tpl = $('template.{$this->column}-tpl');
547
548
    index++;
549
550
    var template = tpl.html().replace(/{$defaultKey}/g, index);
551
    $('.has-many-{$this->column}-forms').append(template);
552
    {$templateScript}
553
});
554
555
$('#has-many-{$this->column}').on('click', '.remove', function () {
556
    $(this).closest('.has-many-{$this->column}-form').hide();
557
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
558
});
559
560
EOT;
561
562
        Admin::script($script);
563
    }
564
565
    /**
566
     * Disable create button.
567
     *
568
     * @return $this
569
     */
570
    public function disableCreate()
571
    {
572
        $this->options['allowCreate'] = false;
573
574
        return $this;
575
    }
576
577
    /**
578
     * Disable delete button.
579
     *
580
     * @return $this
581
     */
582
    public function disableDelete()
583
    {
584
        $this->options['allowDelete'] = false;
585
586
        return $this;
587
    }
588
589
    /**
590
     * Render the `HasMany` field.
591
     *
592
     * @throws \Exception
593
     *
594
     * @return \Illuminate\View\View
595
     */
596
    public function render()
597
    {
598
        if ($this->viewMode == 'table') {
599
            return $this->renderTable();
600
        }
601
602
        // specify a view to render.
603
        $this->view = $this->views[$this->viewMode];
604
605
        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...
606
            ->getTemplateHtmlAndScript();
607
608
        $this->setupScript($script);
609
610
        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...
611
            'forms'        => $this->buildRelatedForms(),
612
            'template'     => $template,
613
            'relationName' => $this->relationName,
614
            'options'      => $this->options,
615
        ]);
616
    }
617
618
    /**
619
     * Render the `HasMany` field for table style.
620
     *
621
     * @throws \Exception
622
     *
623
     * @return mixed
624
     */
625
    protected function renderTable()
626
    {
627
        $headers = [];
628
        $fields = [];
629
        $hidden = [];
630
        $scripts = [];
631
632
        /* @var Field $field */
633
        foreach ($this->buildNestedForm($this->column, $this->builder)->fields() as $field) {
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...
634
            if (is_a($field, Hidden::class)) {
635
                $hidden[] = $field->render();
636
            } else {
637
                /* Hide label and set field width 100% */
638
                $field->setLabelClass(['hidden']);
639
                $field->setWidth(12, 0);
640
                $fields[] = $field->render();
641
                $headers[] = $field->label();
642
            }
643
644
            /*
645
             * Get and remove the last script of Admin::$script stack.
646
             */
647
            if ($field->getScript()) {
648
                $scripts[] = array_pop(Admin::$script);
649
            }
650
        }
651
652
        /* Build row elements */
653
        $template = array_reduce($fields, function ($all, $field) {
654
            $all .= "<td>{$field}</td>";
655
656
            return $all;
657
        }, '');
658
659
        /* Build cell with hidden elements */
660
        $template .= '<td class="hidden">'.implode('', $hidden).'</td>';
661
662
        $this->setupScript(implode("\r\n", $scripts));
663
664
        // specify a view to render.
665
        $this->view = $this->views[$this->viewMode];
666
667
        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...
Comprehensibility Bug introduced by
It seems like you call parent on a different method (render() instead of renderTable()). Are you sure this is correct? If so, you might want to change this to $this->render().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
668
            'headers'      => $headers,
669
            'forms'        => $this->buildRelatedForms(),
670
            'template'     => $template,
671
            'relationName' => $this->relationName,
672
            'options'      => $this->options,
673
        ]);
674
    }
675
}
676