Completed
Pull Request — master (#4487)
by rust17
02:29
created

MultipleFile::prepare()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 1
dl 0
loc 14
rs 9.7998
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\Arr;
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.5.2',
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',
29
        '/vendor/laravel-admin/bootstrap-fileinput/js/fileinput.min.js?v=4.5.2',
30
        '/vendor/laravel-admin/bootstrap-fileinput/js/plugins/sortable.min.js?v=4.5.2',
31
    ];
32
33
    /**
34
     * Create a new File instance.
35
     *
36
     * @param string $column
37
     * @param array  $arguments
38
     */
39
    public function __construct($column, $arguments = [])
40
    {
41
        $this->initStorage();
42
43
        parent::__construct($column, $arguments);
44
    }
45
46
    /**
47
     * Default directory for file to upload.
48
     *
49
     * @return mixed
50
     */
51
    public function defaultDirectory()
52
    {
53
        return config('admin.upload.directory.file');
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getValidator(array $input)
60
    {
61
        if (request()->has(static::FILE_DELETE_FLAG)) {
62
            return false;
63
        }
64
65
        if (
66
            request()->has(static::FILE_SORT_FLAG) &&
67
            array_filter(request()->input(static::FILE_SORT_FLAG))
68
        ) {
69
            return false;
70
        }
71
72
        if ($this->validator) {
73
            return $this->validator->call($this, $input);
74
        }
75
76
        $attributes = [];
77
78
        if (!$fieldRules = $this->getRules()) {
79
            return false;
80
        }
81
82
        $attributes[$this->column] = $this->label;
83
84
        list($rules, $input) = $this->hydrateFiles(Arr::get($input, $this->column, []));
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Illuminate\Support\Arr::get() does only seem to accept string|integer|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...
85
86
        return \validator($input, $rules, $this->getValidationMessages(), $attributes);
87
    }
88
89
    /**
90
     * Hydrate the files array.
91
     *
92
     * @param array $value
93
     *
94
     * @return array
95
     */
96
    protected function hydrateFiles(array $value)
97
    {
98
        if (empty($value)) {
99
            return [[$this->column => $this->getRules()], []];
100
        }
101
102
        $rules = $input = [];
103
104
        foreach ($value as $key => $file) {
105
            $rules[$this->column.$key] = $this->getRules();
106
            $input[$this->column.$key] = $file;
107
        }
108
109
        return [$rules, $input];
110
    }
111
112
    /**
113
     * Sort files.
114
     *
115
     * @param string $order
116
     *
117
     * @return array
118
     */
119
    protected function sortFiles($order)
120
    {
121
        $order = explode(',', $order);
122
123
        $new = [];
124
        $original = $this->original();
125
126
        foreach ($order as $item) {
127
            $new[] = Arr::get($original, $item);
128
        }
129
130
        return $new;
131
    }
132
133
    /**
134
     * Prepare for saving.
135
     *
136
     * @param UploadedFile|array $files
137
     *
138
     * @return mixed|string
139
     */
140
    public function prepare($files)
141
    {
142
        if (request()->has(static::FILE_DELETE_FLAG)) {
143
            return $this->destroy(request(static::FILE_DELETE_FLAG));
144
        }
145
146
        if (is_string($files) && request()->has(static::FILE_SORT_FLAG)) {
147
            return $this->sortFiles($files);
148
        }
149
150
        $targets = array_map([$this, 'prepareForeach'], $files);
151
152
        return array_merge($this->original(), $targets);
153
    }
154
155
    /**
156
     * @return array|mixed
157
     */
158
    public function original()
159
    {
160
        if (empty($this->original)) {
161
            return [];
162
        }
163
164
        return $this->original;
165
    }
166
167
    /**
168
     * Prepare for each file.
169
     *
170
     * @param UploadedFile $file
171
     *
172
     * @return mixed|string
173
     */
174 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...
175
    {
176
        $this->name = $this->getStoreName($file);
0 ignored issues
show
Bug introduced by
It seems like $file defined by parameter $file on line 174 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...
177
178
        return tap($this->upload($file), function () {
0 ignored issues
show
Bug introduced by
It seems like $file defined by parameter $file on line 174 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...
179
            $this->name = null;
180
        });
181
    }
182
183
    /**
184
     * Preview html for file-upload plugin.
185
     *
186
     * @return array
187
     */
188
    protected function preview()
189
    {
190
        $files = $this->value ?: [];
191
192
        return array_values(array_map([$this, 'objectUrl'], $files));
193
    }
194
195
    /**
196
     * Initialize the caption.
197
     *
198
     * @param array $caption
199
     *
200
     * @return string
201
     */
202
    protected function initialCaption($caption)
203
    {
204
        if (empty($caption)) {
205
            return '';
206
        }
207
208
        $caption = array_map('basename', $caption);
209
210
        return implode(',', $caption);
211
    }
212
213
    /**
214
     * @return array
215
     */
216
    protected function initialPreviewConfig()
217
    {
218
        $files = $this->value ?: [];
219
220
        $config = [];
221
222
        foreach ($files as $index => $file) {
223
            $preview = array_merge([
224
                'caption' => basename($file),
225
                'key'     => $index,
226
            ], $this->guessPreviewType($file));
227
228
            $config[] = $preview;
229
        }
230
231
        return $config;
232
    }
233
234
    /**
235
     * Allow to sort files.
236
     *
237
     * @return $this
238
     */
239
    public function sortable()
240
    {
241
        $this->fileActionSettings['showDrag'] = true;
242
243
        return $this;
244
    }
245
246
    /**
247
     * @param string $options
248
     */
249
    protected function setupScripts($options)
250
    {
251
        $this->script = <<<EOT
252
$("input{$this->getElementClassSelector()}").fileinput({$options});
253
EOT;
254
255 View Code Duplication
        if ($this->fileActionSettings['showRemove']) {
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...
256
            $text = [
257
                'title'   => trans('admin.delete_confirm'),
258
                'confirm' => trans('admin.confirm'),
259
                'cancel'  => trans('admin.cancel'),
260
            ];
261
262
            $this->script .= <<<EOT
263
$("input{$this->getElementClassSelector()}").on('filebeforedelete', function() {
264
265
    return new Promise(function(resolve, reject) {
266
267
        var remove = resolve;
268
269
        swal({
270
            title: "{$text['title']}",
271
            type: "warning",
272
            showCancelButton: true,
273
            confirmButtonColor: "#DD6B55",
274
            confirmButtonText: "{$text['confirm']}",
275
            showLoaderOnConfirm: true,
276
            cancelButtonText: "{$text['cancel']}",
277
            preConfirm: function() {
278
                return new Promise(function(resolve) {
279
                    resolve(remove());
280
                });
281
            }
282
        });
283
    });
284
});
285
EOT;
286
        }
287
288
        if ($this->fileActionSettings['showDrag']) {
289
            $this->addVariables([
290
                'sortable'  => true,
291
                'sort_flag' => static::FILE_SORT_FLAG,
292
            ]);
293
294
            $this->script .= <<<EOT
295
$("input{$this->getElementClassSelector()}").on('filesorted', function(event, params) {
296
297
    var order = [];
298
299
    params.stack.forEach(function (item) {
300
        order.push(item.key);
301
    });
302
303
    $("input{$this->getElementClassSelector()}_sort").val(order);
304
});
305
EOT;
306
        }
307
    }
308
309
    /**
310
     * Render file upload field.
311
     *
312
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
313
     */
314
    public function render()
315
    {
316
        $this->attribute('multiple', true);
317
318
        $this->setupDefaultOptions();
319
320
        if (!empty($this->value)) {
321
            $this->options(['initialPreview' => $this->preview()]);
322
            $this->setupPreviewOptions();
323
        }
324
325
        $options = json_encode($this->options);
326
327
        $this->setupScripts($options);
328
329
        return parent::render();
0 ignored issues
show
Bug Compatibility introduced by
The expression parent::render(); of type string|Illuminate\View\V...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 329 which is incompatible with the return type declared by the interface Illuminate\Contracts\Support\Renderable::render of type string.
Loading history...
330
    }
331
332
    /**
333
     * Destroy original files.
334
     *
335
     * @param string $key
336
     *
337
     * @return array
338
     */
339
    public function destroy($key)
340
    {
341
        $files = $this->original ?: [];
342
343
        $file = Arr::get($files, $key);
344
345
        if (!$this->retainable && $this->storage->exists($file)) {
346
            $this->storage->delete($file);
347
        }
348
349
        unset($files[$key]);
350
351
        return $files;
352
    }
353
}
354