Completed
Push — 6.0 ( cd08ae...fced77 )
by liu
04:01 queued 10s
created

File::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use SplFileObject;
16
17
class File extends SplFileObject
1 ignored issue
show
Coding Style introduced by
Missing doc comment for class File
Loading history...
18
{
19
    /**
20
     * 错误信息
21
     * @var string|array
22
     */
23
    private $error = '';
0 ignored issues
show
Coding Style introduced by
Private member variable "error" must be prefixed with an underscore
Loading history...
24
25
    /**
26
     * 当前完整文件名
27
     * @var string
28
     */
29
    protected $filename;
30
31
    /**
32
     * 上传文件名
33
     * @var string
34
     */
35
    protected $saveName;
36
37
    /**
38
     * 上传文件命名规则
39
     * @var string|\Closure
40
     */
41
    protected $rule = 'date';
42
43
    /**
44
     * 上传文件验证规则
45
     * @var array
46
     */
47
    protected $validate = [];
48
49
    /**
50
     * 是否单元测试
51
     * @var bool
52
     */
53
    protected $isTest;
54
55
    /**
56
     * 上传文件信息
57
     * @var array
58
     */
59
    protected $info = [];
60
61
    /**
62
     * 文件hash规则
63
     * @var array
64
     */
65
    protected $hash = [];
66
67
    public function __construct(string $filename, string $mode = 'r')
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
68
    {
69
        parent::__construct($filename, $mode);
70
71
        $this->filename = $this->getRealPath() ?: $this->getPathname();
72
    }
73
74
    /**
75
     * 是否测试
76
     * @access public
77
     * @param  bool   $test 是否测试
78
     * @return $this
79
     */
80
    public function isTest(bool $test = false)
81
    {
82
        $this->isTest = $test;
83
84
        return $this;
85
    }
86
87
    /**
88
     * 设置上传信息
89
     * @access public
90
     * @param  array   $info 上传文件信息
91
     * @return $this
92
     */
93
    public function setUploadInfo(array $info)
94
    {
95
        $this->info = $info;
96
97
        return $this;
98
    }
99
100
    /**
101
     * 获取上传文件的信息
102
     * @access public
103
     * @param  string   $name
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Superfluous parameter comment
Loading history...
104
     * @return array
105
     */
106
    public function getInfo(): array
107
    {
108
        return $this->info;
109
    }
110
111
    /**
112
     * 获取上传文件的name
113
     * @access public
114
     * @return string
115
     */
116
    public function getName(): string
117
    {
118
        return $this->info['name'] ?? '';
119
    }
120
121
    /**
122
     * 获取上传文件的文件名
123
     * @access public
124
     * @return string
125
     */
126
    public function getSaveName(): string
127
    {
128
        return $this->saveName;
129
    }
130
131
    /**
132
     * 设置上传文件的保存文件名
133
     * @access public
134
     * @param  string   $saveName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
135
     * @return $this
136
     */
137
    public function setSaveName(string $saveName)
138
    {
139
        $this->saveName = $saveName;
140
141
        return $this;
142
    }
143
144
    /**
145
     * 获取文件的哈希散列值
146
     * @access public
147
     * @param  string $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
148
     * @return string
149
     */
150
    public function hash(string $type = 'sha1'): string
151
    {
152
        if (!isset($this->hash[$type])) {
153
            $this->hash[$type] = hash_file($type, $this->filename);
154
        }
155
156
        return $this->hash[$type];
157
    }
158
159
    /**
160
     * 检查目录是否可写
161
     * @access protected
162
     * @param  string   $path    目录
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
163
     * @return bool
164
     */
165
    protected function checkPath(string $path): bool
166
    {
167
        if (is_dir($path)) {
168
            return true;
169
        }
170
171
        try {
172
            $result = mkdir($path, 0755, true);
173
        } catch (\Exception $e) {
174
            // 创建失败
175
            $result = false;
176
        }
177
178
        if ($result) {
179
            return true;
180
        }
181
182
        $this->error = ['directory {:path} creation failed', ['path' => $path]];
183
        return false;
184
    }
185
186
    /**
187
     * 获取文件类型信息
188
     * @access public
189
     * @return string
190
     */
191
    public function getMime(): string
192
    {
193
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
194
195
        return finfo_file($finfo, $this->filename);
196
    }
197
198
    /**
199
     * 设置文件的命名规则
200
     * @access public
201
     * @param  mixed   $rule    文件命名规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
202
     * @return $this
203
     */
204
    public function rule($rule)
205
    {
206
        $this->rule = $rule;
207
208
        return $this;
209
    }
210
211
    /**
212
     * 设置上传文件的验证规则
213
     * @access public
214
     * @param  array   $rule    验证规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
215
     * @return $this
216
     */
217
    public function validate(array $rule = [])
218
    {
219
        $this->validate = $rule;
220
221
        return $this;
222
    }
223
224
    /**
225
     * 检测是否合法的上传文件
226
     * @access public
227
     * @return bool
228
     */
229
    public function isValid(): bool
230
    {
231
        if ($this->isTest) {
232
            return is_file($this->filename);
233
        }
234
235
        return is_uploaded_file($this->filename);
236
    }
237
238
    /**
239
     * 检测上传文件
240
     * @access public
241
     * @param  array   $rule    验证规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
242
     * @return bool
243
     */
244
    public function check(array $rule = []): bool
245
    {
246
        $rule = $rule ?: $this->validate;
247
248
        if ((isset($rule['size']) && !$this->checkSize($rule['size']))
249
            || (isset($rule['type']) && !$this->checkMime($rule['type']))
250
            || (isset($rule['ext']) && !$this->checkExt($rule['ext']))
251
            || !$this->checkImg()) {
0 ignored issues
show
Coding Style introduced by
Closing parenthesis of a multi-line IF statement must be on a new line
Loading history...
252
            return false;
253
        }
254
255
        return true;
256
    }
257
258
    /**
259
     * 检测上传文件后缀
260
     * @access public
261
     * @param  array|string   $ext    允许后缀
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
262
     * @return bool
263
     */
264
    public function checkExt($ext): bool
265
    {
266
        if (is_string($ext)) {
267
            $ext = explode(',', $ext);
268
        }
269
270
        $extension = strtolower(pathinfo($this->getName(), PATHINFO_EXTENSION));
271
272
        if (!in_array($extension, $ext)) {
273
            $this->error = 'extensions to upload is not allowed';
274
            return false;
275
        }
276
277
        return true;
278
    }
279
280
    /**
281
     * 检测图像文件
282
     * @access public
283
     * @return bool
284
     */
285
    public function checkImg(): bool
286
    {
287
        $extension = strtolower(pathinfo($this->getName(), PATHINFO_EXTENSION));
288
289
        /* 对图像文件进行严格检测 */
290
        if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6, 13])) {
291
            $this->error = 'illegal image files';
292
            return false;
293
        }
294
295
        return true;
296
    }
297
298
    // 判断图像类型
299
    protected function getImageType(string $image)
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
300
    {
301
        if (function_exists('exif_imagetype')) {
302
            return exif_imagetype($image);
303
        }
304
305
        try {
306
            $info = getimagesize($image);
307
            return $info ? $info[2] : false;
308
        } catch (\Exception $e) {
309
            return false;
310
        }
311
    }
312
313
    /**
314
     * 检测上传文件大小
315
     * @access public
316
     * @param  integer   $size    最大大小
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
317
     * @return bool
318
     */
319
    public function checkSize(int $size): bool
320
    {
321
        if ($this->getSize() > $size) {
322
            $this->error = 'filesize not match';
323
            return false;
324
        }
325
326
        return true;
327
    }
328
329
    /**
330
     * 检测上传文件类型
331
     * @access public
332
     * @param  array|string   $mime    允许类型
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
333
     * @return bool
334
     */
335
    public function checkMime($mime): bool
336
    {
337
        if (is_string($mime)) {
338
            $mime = explode(',', $mime);
339
        }
340
341
        if (!in_array(strtolower($this->getMime()), $mime)) {
342
            $this->error = 'mimetype to upload is not allowed';
343
            return false;
344
        }
345
346
        return true;
347
    }
348
349
    /**
350
     * 移动文件
351
     * @access public
352
     * @param  string           $path    保存路径
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 4 found
Loading history...
353
     * @param  string|bool      $savename    保存的文件名 默认自动生成
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
354
     * @param  boolean          $replace 同名文件是否覆盖
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
355
     * @return false|File       false-失败 否则返回File实例
356
     */
357
    public function move(string $path, $savename = true, bool $replace = true)
358
    {
359
        // 文件上传失败,捕获错误代码
360
        if (!empty($this->info['error'])) {
361
            $this->error($this->info['error']);
362
            return false;
363
        }
364
365
        // 检测合法性
366
        if (!$this->isValid()) {
367
            $this->error = 'upload illegal files';
368
            return false;
369
        }
370
371
        // 验证上传
372
        if (!$this->check()) {
373
            return false;
374
        }
375
376
        $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
377
        // 文件保存命名规则
378
        $saveName = $this->buildSaveName($savename);
379
        $filename = $path . $saveName;
380
381
        // 检测目录
382
        if (false === $this->checkPath(dirname($filename))) {
383
            return false;
384
        }
385
386
        /* 不覆盖同名文件 */
387
        if (!$replace && is_file($filename)) {
388
            $this->error = ['has the same filename: {:filename}', ['filename' => $filename]];
389
            return false;
390
        }
391
392
        /* 移动文件 */
393
        if ($this->isTest) {
394
            rename($this->filename, $filename);
395
        } elseif (!move_uploaded_file($this->filename, $filename)) {
396
            $this->error = 'upload write error';
397
            return false;
398
        }
399
400
        // 返回 File对象实例
401
        $file = new self($filename);
402
        $file->setSaveName($saveName);
403
        $file->setUploadInfo($this->info);
404
405
        return $file;
406
    }
407
408
    /**
409
     * 获取保存文件名
410
     * @access protected
411
     * @param  string|bool   $savename    保存的文件名 默认自动生成
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
412
     * @return string
413
     */
414
    protected function buildSaveName($savename): string
415
    {
416
        if (true === $savename) {
417
            // 自动生成文件名
418
            $savename = $this->autoBuildName();
419
        } elseif ('' === $savename || false === $savename) {
420
            // 保留原文件名
421
            $savename = $this->getName();
422
        }
423
424
        if (!strpos($savename, '.')) {
425
            $savename .= '.' . pathinfo($this->getName(), PATHINFO_EXTENSION);
426
        }
427
428
        return $savename;
429
    }
430
431
    /**
432
     * 自动生成文件名
433
     * @access protected
434
     * @return string
435
     */
436
    protected function autoBuildName(): string
437
    {
438
        if ($this->rule instanceof \Closure) {
439
            $savename = call_user_func_array($this->rule, [$this]);
440
        } else {
441
            switch ($this->rule) {
442
                case 'date':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
443
                    $savename = date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true));
444
                    break;
445
                default:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
446
                    if (in_array($this->rule, hash_algos())) {
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
447
                        $hash     = $this->hash($this->rule);
448
                        $savename = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2);
449
                    } elseif (is_callable($this->rule)) {
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
450
                        $savename = call_user_func($this->rule);
451
                    } else {
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
452
                        $savename = date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true));
453
                    }
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
454
            }
455
        }
456
457
        return $savename;
458
    }
459
460
    /**
461
     * 获取错误代码信息
462
     * @access private
463
     * @param  int $errorNo  错误号
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
464
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
465
    private function error(int $errorNo): void
0 ignored issues
show
Coding Style introduced by
Private method name "File::error" must be prefixed with an underscore
Loading history...
466
    {
467
        switch ($errorNo) {
468
            case 1:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
469
            case 2:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
470
                $this->error = 'upload File size exceeds the maximum value';
471
                break;
472
            case 3:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
473
                $this->error = 'only the portion of file is uploaded';
474
                break;
475
            case 4:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
476
                $this->error = 'no file to uploaded';
477
                break;
478
            case 6:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
479
                $this->error = 'upload temp dir not found';
480
                break;
481
            case 7:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
482
                $this->error = 'file write error';
483
                break;
484
            default:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
485
                $this->error = 'unknown upload error';
486
        }
487
    }
488
489
    /**
490
     * 获取错误信息(支持多语言)
491
     * @access public
492
     * @return string
493
     */
494
    public function getError(): string
495
    {
496
        $lang = Container::pull('lang');
497
498
        if (is_array($this->error)) {
499
            list($msg, $vars) = $this->error;
500
        } else {
501
            $msg  = $this->error;
502
            $vars = [];
503
        }
504
505
        return $lang->has($msg) ? $lang->get($msg, $vars) : $msg;
506
    }
507
508
    public function __call($method, $args)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __call()
Loading history...
509
    {
510
        return $this->hash($method);
511
    }
512
}
513