Completed
Push — 6.0 ( c6d21a...a43f83 )
by yun
15:10 queued 11:06
created

File::hashName()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 5
nop 1
dl 0
loc 22
ccs 0
cts 14
cp 0
crap 30
rs 9.4222
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
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 SplFileInfo;
16
use think\exception\FileException;
17
18
/**
19
 * 文件上传类
20
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
21
class File extends SplFileInfo
22
{
23
24
    /**
25
     * 文件hash规则
26
     * @var array
27
     */
28
    protected $hash = [];
29
30
    protected $hashName;
31
32
    public function __construct(string $path, bool $checkPath = true)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
33
    {
34
        if ($checkPath && !is_file($path)) {
35
            throw new FileException(sprintf('The file "%s" does not exist', $path));
36
        }
37
38
        parent::__construct($path);
39
    }
40
41
    /**
42
     * 获取文件的哈希散列值
43
     * @access public
44
     * @param string $type
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
45
     * @return string
46
     */
47
    public function hash(string $type = 'sha1'): string
48
    {
49
        if (!isset($this->hash[$type])) {
50
            $this->hash[$type] = hash_file($type, $this->getPathname());
51
        }
52
53
        return $this->hash[$type];
54
    }
55
56
    public function md5()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function md5()
Loading history...
57
    {
58
        return $this->hash('md5');
59
    }
60
61
    public function sha1()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function sha1()
Loading history...
62
    {
63
        return $this->hash('sha1');
64
    }
65
66
    /**
67
     * 获取文件类型信息
68
     * @access public
69
     * @return string
70
     */
71
    public function getMime(): string
72
    {
73
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
74
75
        return finfo_file($finfo, $this->getPathname());
76
    }
77
78
    /**
79
     * 移动文件
80
     * @access public
81
     * @param string      $directory 保存路径
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
82
     * @param string|bool $name      保存的文件名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
83
     * @return File
84
     */
85
    public function move(string $directory, $name = null)
86
    {
87
        $target = $this->getTargetFile($directory, $name);
88
89
        set_error_handler(function ($type, $msg) use (&$error) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
90
            $error = $msg;
91
        });
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
92
        $renamed = rename($this->getPathname(), $target);
93
        restore_error_handler();
94
        if (!$renamed) {
95
            throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error)));
96
        }
97
98
        @chmod($target, 0666 & ~umask());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

98
        /** @scrutinizer ignore-unhandled */ @chmod($target, 0666 & ~umask());

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
99
100
        return $target;
101
    }
102
103
    /**
104
     * 实例化一个新文件
105
     * @param string      $directory
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
106
     * @param null|string $name
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
107
     * @return File
108
     */
109
    protected function getTargetFile($directory, $name = null)
110
    {
111
        if (!is_dir($directory)) {
112
            if (false === @mkdir($directory, 0777, true) && !is_dir($directory)) {
113
                throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
114
            }
115
        } elseif (!is_writable($directory)) {
116
            throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
117
        }
118
119
        $target = rtrim($directory, '/\\') . \DIRECTORY_SEPARATOR . (null === $name ? $this->getBasename() : $this->getName($name));
120
121
        return new self($target, false);
122
    }
123
124
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $name should have a doc-comment as per coding-style.
Loading history...
125
     * 获取文件名
126
     * @param $name
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
127
     * @return bool|mixed|string
128
     */
129
    protected function getName($name)
130
    {
131
        $originalName = str_replace('\\', '/', $name);
132
        $pos          = strrpos($originalName, '/');
133
        $originalName = false === $pos ? $originalName : substr($originalName, $pos + 1);
134
135
        return $originalName;
136
    }
137
138
    /**
139
     * 文件扩展名
140
     * @return string
141
     */
142
    public function extension()
143
    {
144
        return $this->getExtension();
145
    }
146
147
    /**
148
     * 自动生成文件名
149
     * @access protected
150
     * @param string|\Closure $rule
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
151
     * @return string
152
     */
153
    public function hashName($rule = 'date'): string
154
    {
155
        if (!$this->hashName) {
156
            if ($rule instanceof \Closure) {
157
                $this->hashName = call_user_func_array($rule, [$this]);
158
            } else {
159
                switch (true) {
160
                    case in_array($rule, hash_algos()):
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
161
                        $hash           = $this->hash($rule);
162
                        $this->hashName = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2);
163
                        break;
164
                    case is_callable($rule):
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
165
                        $this->hashName = call_user_func($rule);
166
                        break;
167
                    default:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
168
                        $this->hashName = date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true));
169
                        break;
170
                }
171
            }
172
        }
173
174
        return $this->hashName . '.' . $this->extension();
175
    }
176
}
177