Completed
Push — master ( 02776d...cd56b1 )
by wen
04:19
created

File::setDisk()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Sco\Admin\Form\Elements;
4
5
use Illuminate\Http\UploadedFile;
6
use Illuminate\Support\Str;
7
use Storage;
8
use Validator;
9
10
class File extends NamedElement
11
{
12
    protected $type = 'file';
13
14
    protected $actionUrl;
15
16
    protected $multiSelect = false;
17
18
    protected $multiFile = true;
19
20
    protected $showFileList = true;
21
22
    protected $withCredentials = false;
23
24
    protected $maxFileSize;
25
26
    protected $fileUploadsLimit = 0;
27
28
    protected $fileExtensions;
29
30
    protected $listType = 'text';
31
32
    protected $disk;
33
34
    /**
35
     * @var string|\Closure|null
36
     */
37
    protected $uploadPath;
38
39
    /**
40
     * @var \Closure|null
41
     */
42
    protected $uploadFileNameRule;
43
44
    public function getValue()
45
    {
46
        $value = parent::getValue();
47
        if (empty($value)) {
48
            return [];
49
        }
50
        return collect(explode(',', $value))->filter(function ($item) {
51
            return $this->existsFile($item);
52
        })->map(function ($item) {
53
            return $this->getFileInfo($item);
54
        });
55
    }
56
57
    public function getActionUrl()
58
    {
59
        if ($this->actionUrl) {
60
            return $this->actionUrl;
61
        }
62
        $model = app('admin.components')->get(get_class($this->getModel()));
63
64
        $params       = [
65
            'model' => $model->getName(),
66
            'field' => $this->getName(),
67
        ];
68
        $params['id'] = null;
69
        if ($this->getModel()->exists) {
70
            $params['id'] = $this->getModel()->getKey();
71
        }
72
        $params['_token'] = csrf_token();
73
74
        return route('admin.model.upload.file', $params);
75
    }
76
77
    public function setActionUrl($value)
78
    {
79
        $this->actionUrl = $value;
80
81
        return $this;
82
    }
83
84
    public function isMultiSelect()
85
    {
86
        return $this->multiSelect;
87
    }
88
89
    public function enableMultiSelect()
90
    {
91
        $this->multiSelect = true;
92
93
        return $this;
94
    }
95
96
    /**
97
     * Show file list
98
     *
99
     * @return $this
100
     */
101
    public function disableFileList()
102
    {
103
        $this->showFileList = false;
104
105
        return $this;
106
    }
107
108
    /**
109
     * Indicates whether or not cross-site Access-Control requests
110
     * should be made using credentials
111
     *
112
     * @return $this
113
     */
114
    public function withCredentials()
115
    {
116
        $this->withCredentials = true;
117
118
        return $this;
119
    }
120
121
    /**
122
     * The maximum size of an uploaded file in bytes
123
     * If didn't set maximum size, return maximum size as configured in php.ini.
124
     *
125
     * @return int
126
     */
127
    public function getMaxFileSize()
128
    {
129
        if ($this->maxFileSize) {
130
            return $this->maxFileSize;
131
        }
132
        return UploadedFile::getMaxFilesize();
133
    }
134
135
    /**
136
     * The maximum size allowed for an uploaded file in bytes
137
     *
138
     * @param int $value
139
     *
140
     * @return $this
141
     */
142
    public function setMaxFileSize($value)
143
    {
144
        $this->maxFileSize = intval($value);
145
146
        return $this;
147
    }
148
149
    public function getFileExtensions()
150
    {
151
        if ($this->fileExtensions) {
152
            return $this->fileExtensions;
153
        }
154
155
        return $this->getDefaultExtensions();
156
    }
157
158
    /**
159
     * A list of allowable extensions that can be uploaded.
160
     *
161
     * @param string $value
162
     *
163
     * @return $this
164
     */
165
    public function setFileExtensions($value)
166
    {
167
        $this->fileExtensions = $value;
168
169
        return $this;
170
    }
171
172
    protected function getDefaultExtensions()
173
    {
174
        return config('admin.upload.extensions.file');
175
    }
176
177
    public function getFileUploadsLimit()
178
    {
179
        return $this->fileUploadsLimit;
180
    }
181
182
    /**
183
     * The maximum number of files that can be uploaded.
184
     *
185
     * @param int $value
186
     *
187
     * @return $this
188
     */
189
    public function setFileUploadsLimit($value)
190
    {
191
        $this->fileUploadsLimit = intval($value);
192
193
        return $this;
194
    }
195
196
    public function getListType()
197
    {
198
        return $this->listType;
199
    }
200
201
    public function toArray()
202
    {
203
        return parent::toArray() + [
204
                'action'           => $this->getActionUrl(),
205
                'showFileList'     => $this->showFileList,
206
                'multiSelect'      => $this->isMultiSelect(),
207
                'maxFileSize'      => $this->getMaxFileSize(),
208
                'fileUploadsLimit' => $this->getFileUploadsLimit(),
209
                'fileExtensions'   => $this->getFileExtensions(),
210
                'listType'         => $this->getListType(),
211
            ];
212
    }
213
214
    public function getDisk()
215
    {
216
        if ($this->disk) {
217
            return $this->disk;
218
        }
219
220
        return config('admin.upload.disk', 'public');
221
    }
222
223
    public function setDisk($value)
224
    {
225
        $this->disk = $value;
226
227
        return $this;
228
    }
229
230
    protected function getDefaultUploadPath(UploadedFile $file)
0 ignored issues
show
Unused Code introduced by
The parameter $file is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
231
    {
232
        return config('admin.upload.directory', 'admin/uploads');
233
    }
234
235
    public function getUploadPath(UploadedFile $file)
236
    {
237
        if (!($path = $this->uploadPath)) {
238
            $path = $this->getDefaultUploadPath($file);
239
        }
240
        if (is_callable($path)) {
241
            return call_user_func($path, $file);
242
        }
243
244
        return $path;
245
    }
246
247
    /**
248
     * The path of file save
249
     *
250
     * @param string|\Closure $value
251
     *
252
     * @return $this
253
     */
254
    public function setUploadPath($value)
255
    {
256
        $this->uploadPath = $value;
257
258
        return $this;
259
    }
260
261
    public function getUploadFileName(UploadedFile $file)
262
    {
263
        if (is_callable($this->uploadFileNameRule)) {
264
            return call_user_func($this->uploadFileNameRule, $file);
265
        }
266
267
        return $this->getDefaultFileName($file);
268
    }
269
270
    protected function getDefaultFileName(UploadedFile $file)
271
    {
272
        $hash = Str::random(40);
273
        return $hash . '.' . $file->guessExtension();
274
    }
275
276
    public function setUploadFileNameRule(\Closure $value)
277
    {
278
        $this->uploadFileNameRule = $value;
279
280
        return $this;
281
    }
282
283
    public function saveFile(UploadedFile $file)
284
    {
285
        Validator::validate(
286
            [$this->getName() => $file],
287
            $this->getValidationRules(),
288
            $this->getValidationMessages(),
289
            $this->getValidationTitles()
290
        );
291
292
        $path = $file->storeAs(
293
            $this->getUploadPath($file),
294
            $this->getUploadFileName($file),
295
            $this->getDisk()
296
        );
297
298
        return $this->getFileInfo($path);
299
    }
300
301
    protected function prepareValue($value)
302
    {
303
        if (empty($value) || !is_array($value)) {
304
            return '';
305
        }
306
        return collect($value)->implode('path', ',');
307
    }
308
309
    protected function existsFile($path)
310
    {
311
        return Storage::disk($this->getDisk())->exists($path);
312
    }
313
314
    protected function getFileUrl($path)
315
    {
316
        return Storage::disk($this->getDisk())->url($path);
317
    }
318
319
    protected function getFileInfo($path)
320
    {
321
        return [
322
            'name' => substr($path, strrpos($path, '/') + 1),
323
            'path' => $path,
324
            'url' => $this->getFileUrl($path),
325
        ];
326
    }
327
}
328