Completed
Pull Request — master (#1281)
by
unknown
02:32
created

MultipleFile::render()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 0
dl 19
loc 19
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Form\Field;
6
use Illuminate\Support\Facades\Validator;
7
use Symfony\Component\HttpFoundation\File\UploadedFile;
8
9
class MultipleFile extends Field
10
{
11
    use UploadField;
12
13
    /**
14
     * Css.
15
     *
16
     * @var array
17
     */
18
    protected static $css = [
19
        '/vendor/laravel-admin/bootstrap-fileinput/css/fileinput.min.css?v=4.3.7',
20
    ];
21
22
    /**
23
     * Js.
24
     *
25
     * @var array
26
     */
27
    protected static $js = [
28
        '/vendor/laravel-admin/bootstrap-fileinput/js/plugins/canvas-to-blob.min.js?v=4.3.7',
29
        '/vendor/laravel-admin/bootstrap-fileinput/js/fileinput.min.js?v=4.3.7',
30
    ];
31
32
    /**
33
     * Create a new File instance.
34
     *
35
     * @param string $column
36
     * @param array  $arguments
37
     */
38
    public function __construct($column, $arguments = [])
39
    {
40
        $this->initStorage();
41
42
        parent::__construct($column, $arguments);
43
    }
44
45
    /**
46
     * Default directory for file to upload.
47
     *
48
     * @return mixed
49
     */
50
    public function defaultDirectory()
51
    {
52
        return config('admin.upload.directory.file');
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getValidator(array $input)
59
    {
60
        if (request()->has(static::FILE_DELETE_FLAG)) {
61
            return false;
62
        }
63
64
        if ($this->validator) {
65
            return $this->validator->call($this, $input);
66
        }
67
68
        $attributes = [];
69
70
        if (!$fieldRules = $this->getRules()) {
71
            return false;
72
        }
73
74
        $attributes[$this->column] = $this->label;
75
76
        list($rules, $input) = $this->hydrateFiles(array_get($input, $this->column, []));
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, array_get() 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...
77
78
        return Validator::make($input, $rules, $this->validationMessages, $attributes);
79
    }
80
81
    /**
82
     * Hydrate the files array.
83
     *
84
     * @param array $value
85
     *
86
     * @return array
87
     */
88
    protected function hydrateFiles(array $value)
89
    {
90
        if (empty($value)) {
91
            return [[$this->column => $this->getRules()], []];
92
        }
93
94
        $rules = $input = [];
95
96
        foreach ($value as $key => $file) {
97
            $rules[$this->column.$key] = $this->getRules();
98
            $input[$this->column.$key] = $file;
99
        }
100
101
        return [$rules, $input];
102
    }
103
104
    /**
105
     * Prepare for saving.
106
     *
107
     * @param UploadedFile|array $files
108
     *
109
     * @return mixed|string
110
     */
111
    public function prepare($files)
112
    {
113
        if (request()->has(static::FILE_DELETE_FLAG)) {
114
            return $this->destroy(request(static::FILE_DELETE_FLAG));
115
        }
116
117
        $targets = array_map([$this, 'prepareForeach'], $files);
118
119
        return array_merge($this->original(), $targets);
120
    }
121
122
    /**
123
     * @return array|mixed
124
     */
125
    public function original()
126
    {
127
        if (empty($this->original)) {
128
            return [];
129
        }
130
131
        return $this->original;
132
    }
133
134
    /**
135
     * Prepare for each file.
136
     *
137
     * @param UploadedFile $file
138
     *
139
     * @return mixed|string
140
     */
141 View Code Duplication
    protected function prepareForeach(UploadedFile $file = null)
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...
142
    {
143
        $this->name = $this->getStoreName($file);
0 ignored issues
show
Bug introduced by
It seems like $file defined by parameter $file on line 141 can be null; however, Encore\Admin\Form\Field\...adField::getStoreName() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Documentation Bug introduced by
It seems like $this->getStoreName($file) of type string is incompatible with the declared type null of property $name.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
144
145
        return tap($this->upload($file), function () {
0 ignored issues
show
Bug introduced by
It seems like $file defined by parameter $file on line 141 can be null; however, Encore\Admin\Form\Field\UploadField::upload() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
146
            $this->name = null;
147
        });
148
    }
149
150
    /**
151
     * Preview html for file-upload plugin.
152
     *
153
     * @return array
154
     */
155
    protected function preview()
156
    {
157
        $files = $this->value ?: [];
158
159
        return array_map([$this, 'objectUrl'], $files);
160
    }
161
162
    /**
163
     * Initialize the caption.
164
     *
165
     * @param array $caption
166
     *
167
     * @return string
168
     */
169
    protected function initialCaption($caption)
170
    {
171
        if (empty($caption)) {
172
            return '';
173
        }
174
175
        $caption = array_map('basename', $caption);
176
177
        return implode(',', $caption);
178
    }
179
180
    /**
181
     * @return array
182
     */
183
    protected function initialPreviewConfig()
184
    {
185
        $files = $this->value ?: [];
186
187
        $config = [];
188
189
        foreach ($files as $index => $file) {
190
            $config[] = [
191
                'caption' => basename($file),
192
                'key'     => $index,
193
            ];
194
        }
195
196
        return $config;
197
    }
198
199
    /**
200
     * Render file upload field.
201
     *
202
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
203
     */
204 View Code Duplication
    public function render()
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...
205
    {
206
        $this->attribute('multiple', true);
207
208
        $this->setupDefaultOptions();
209
210
        if (!empty($this->value)) {
211
            $this->options(['initialPreview' =>$this->preview()]);
212
            $this->setupPreviewOptions();
213
        }
214
215
        $options = json_encode($this->options);
216
217
        $this->script = <<<EOT
218
$("input{$this->getElementClassSelector()}").fileinput({$options});
219
EOT;
220
221
        return parent::render();
0 ignored issues
show
Bug Compatibility introduced by
The expression parent::render(); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 221 which is incompatible with the return type declared by the interface Illuminate\Contracts\Support\Renderable::render of type string.
Loading history...
222
    }
223
224
    /**
225
     * Destroy original files.
226
     *
227
     * @return string.
0 ignored issues
show
Documentation introduced by
The doc-type string. could not be parsed: Unknown type name "string." 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...
228
     */
229
    public function destroy($key)
230
    {
231
        $files = $this->original ?: [];
232
233
        $file = array_get($files, $key);
234
235
        if ($this->storage->exists($file)) {
236
            $this->storage->delete($file);
237
        }
238
239
        unset($files[$key]);
240
241
        return array_values($files);
242
    }
243
}
244