Completed
Push — master ( 6162b5...7f4a32 )
by wen
12:44
created

BaseFile::setMaxFileSize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 4
nop 1
1
<?php
2
3
namespace Sco\Admin\Form\Elements;
4
5
use Illuminate\Http\UploadedFile;
6
use Sco\Admin\Facades\Admin;
7
use Sco\Admin\Traits\UploadStorageTrait;
8
use Validator;
9
10
abstract class BaseFile extends NamedElement
11
{
12
    use UploadStorageTrait;
13
14
    protected $actionUrl;
15
16
    protected $withCredentials = false;
17
18
    protected $maxFileSize;
19
20
    protected $fileExtensions;
21
22
    protected $uploadValidationRules = [];
23
24
    protected $uploadValidationMessages = [];
25
26
    abstract protected function getDefaultExtensions();
27
28
    public function getValue()
29
    {
30
        $value = $this->getValueFromModel();
31
        if (empty($value)) {
32
            return [];
33
        }
34
35
        return collect(explode(',', $value))->filter(function ($item) {
36
            return $this->existsFile($item);
37
        })->map(function ($item) {
38
            return $this->getFileInfo($item);
39
        });
40
    }
41
42
    public function getActionUrl()
43
    {
44
        if ($this->actionUrl) {
45
            return $this->actionUrl;
46
        }
47
48
        $params = [
49
            'model' => Admin::component()->getName(),
50
            'field' => $this->getName(),
51
        ];
52
        $params['id'] = null;
53
        if ($this->getModel()->exists) {
54
            $params['id'] = $this->getModel()->getKey();
55
        }
56
        $params['_token'] = csrf_token();
57
58
        return route('admin.model.upload.file', $params);
59
    }
60
61
    public function setActionUrl($value)
62
    {
63
        $this->actionUrl = $value;
64
65
        return $this;
66
    }
67
68
    /**
69
     * Indicates whether or not cross-site Access-Control requests
70
     * should be made using credentials
71
     *
72
     * @return $this
73
     */
74
    public function withCredentials()
75
    {
76
        $this->withCredentials = true;
77
78
        return $this;
79
    }
80
81
    /**
82
     * The maximum size of an uploaded file in kilobytes
83
     *
84
     * @return int
85
     */
86
    public function getMaxFileSize()
87
    {
88
        if ($this->maxFileSize) {
89
            return $this->maxFileSize;
90
        }
91
92
        return $this->getDefaultMaxFileSize();
93
    }
94
95
    protected function getDefaultMaxFileSize()
96
    {
97
        return UploadedFile::getMaxFilesize() / 1024;
98
    }
99
100
    /**
101
     * The maximum size allowed for an uploaded file in kilobytes
102
     *
103
     * @param int $value
104
     *
105
     * @return $this
106
     */
107
    public function setMaxFileSize(int $value)
108
    {
109
        $this->maxFileSize = $value;
110
111
        $this->addValidationRule('max:' . $this->maxFileSize);
112
113
        return $this;
114
    }
115
116
    public function getFileExtensions()
117
    {
118
        if ($this->fileExtensions) {
119
            return $this->fileExtensions;
120
        }
121
122
        return $this->getDefaultExtensions();
123
    }
124
125
    /**
126
     * A list of allowable extensions that can be uploaded.
127
     *
128
     * @param string $value
129
     *
130
     * @return $this
131
     */
132
    public function setFileExtensions(string $value)
133
    {
134
        $this->fileExtensions = $value;
135
136
        $this->addValidationRule('mimes:' . $value);
137
138
        return $this;
139
    }
140
141
    public function toArray()
142
    {
143
        return parent::toArray() + [
144
                'action'           => $this->getActionUrl(),
145
                'maxFileSize'      => $this->getMaxFileSize(),
146
                'fileExtensions'   => $this->getFileExtensions(),
147
            ];
148
    }
149
150
    /**
151
     * Save file to storage
152
     *
153
     * @param \Illuminate\Http\UploadedFile $file
154
     *
155
     * @return array
156
     * @throws \Illuminate\Validation\ValidationException
157
     */
158
    public function saveFile(UploadedFile $file)
159
    {
160
        Validator::validate(
161
            [$this->getName() => $file],
162
            $this->getUploadValidationRules(),
163
            $this->getUploadValidationMessages(),
164
            $this->getUploadValidationTitles()
165
        );
166
167
        $path = $file->storeAs(
168
            $this->getUploadPath($file),
169
            $this->getUploadFileName($file),
170
            $this->getDisk()
171
        );
172
173
        return $this->getFileInfo($path);
174
    }
175
176
    protected function prepareValue($value)
177
    {
178
        if (empty($value) || ! is_array($value)) {
179
            return '';
180
        }
181
182
        return collect($value)->implode('path', ',');
183
    }
184
185
    /**
186
     * Get file info(name,path,url)
187
     *
188
     * @param $path
189
     *
190
     * @return array
191
     */
192
    protected function getFileInfo($path)
193
    {
194
        return [
195
            'name' => substr($path, strrpos($path, '/') + 1),
196
            'path' => $path,
197
            'url'  => $this->getFileUrl($path),
198
        ];
199
    }
200
201
    public function addValidationRule($rule, $message = null)
202
    {
203
        $uploadRules = [
204
            'image',
205
            'mimes',
206
            'mimetypes',
207
            'size',
208
            'dimensions',
209
            'max',
210
            'min',
211
            'between',
212
        ];
213
214
        if (in_array($this->getValidationRuleName($rule), $uploadRules)) {
215
            return $this->addUploadValidationRule($rule, $message);
216
        }
217
218
        return parent::addValidationRule($rule, $message);
219
    }
220
221 View Code Duplication
    protected function addUploadValidationRule($rule, $message = 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...
222
    {
223
        $this->uploadValidationRules[$this->getValidationRuleName($rule)] = $rule;
224
225
        if (is_null($message)) {
226
            return $this;
227
        }
228
229
        return $this->addUploadValidationMessage($rule, $message);
230
    }
231
232
    protected function addUploadValidationMessage($rule, $message)
233
    {
234
        $key = $this->getName() . '.' . $this->getValidationRuleName($rule);
235
236
        $this->uploadValidationMessages[$key] = $message;
237
238
        return $this;
239
    }
240
241
    protected function getUploadValidationRules()
242
    {
243
        $rules = array_merge(
244
            $this->getDefaultUploadValidationRules(),
245
            $this->uploadValidationRules
246
        );
247
248
        return [$this->getName() => array_values($rules)];
249
    }
250
251
    /**
252
     * Get default validation rules
253
     *
254
     * @return array
255
     */
256
    protected function getDefaultUploadValidationRules()
257
    {
258
        return [
259
            'bail'  => 'bail',
260
            'file'  => 'file',
261
            'mimes' => 'mimes:' . $this->getDefaultExtensions(),
262
            'max'   => 'max:' . $this->getDefaultMaxFileSize(),
263
        ];
264
    }
265
266
    /**
267
     * Get validation messages
268
     *
269
     * @return array
270
     */
271
    protected function getUploadValidationMessages()
272
    {
273
        return $this->uploadValidationMessages;
274
    }
275
276
    /**
277
     * Get validation custom attributes
278
     *
279
     * @return array
280
     */
281
    protected function getUploadValidationTitles()
282
    {
283
        return $this->getValidationTitles();
284
    }
285
}
286