Completed
Push — master ( efa9b4...b05f68 )
by wen
05:55
created

BaseFile::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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