FileName::upCountName()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 3
nc 1
nop 1
1
<?php
2
3
namespace yiicod\fileupload\components\common;
4
5
use yii\base\NotSupportedException;
6
use yii\helpers\Inflector;
7
8
/**
9
 * Class FileName
10
 *
11
 * @author Virchenko Maksim <[email protected]>
12
 *
13
 * @package yiicod\fileupload\components\base
14
 */
15
class FileName
16
{
17
    /**
18
     * @var int|null
19
     */
20
    protected $length;
21
22
    /**
23
     * @var string
24
     */
25
    protected $uploadDir;
26
27
    /**
28
     * FileName constructor.
29
     *
30
     * @param string $uploadDir
31
     * @param int|null $length
32
     */
33
    public function __construct(string $uploadDir, ?int $length)
34
    {
35
        $this->uploadDir = $uploadDir;
36
        $this->length = $length;
37
    }
38
39
    /**
40
     * Get file name
41
     *
42
     * @param UploadedFile $uploadedFile
43
     *
44
     * @return mixed
45
     */
46
    public function getFileName(UploadedFile $uploadedFile)
47
    {
48
        $uploadedFile->name = $this->trimFileName($uploadedFile);
49
50
        return $this->getUniqueFileName($uploadedFile);
51
    }
52
53
    /**
54
     * Trim file name
55
     *
56
     * @param UploadedFile $uploadedFile
57
     *
58
     * @return bool|mixed|string
59
     *
60
     * @throws NotSupportedException
61
     */
62
    protected function trimFileName(UploadedFile $uploadedFile)
63
    {
64
        if (!preg_match('/([^.]*)(\.[^.]+)$/', $uploadedFile->name, $matches)) {
65
            throw new NotSupportedException('Unsupported file name');
66
        }
67
        $name = Inflector::slug($matches[1]) . $matches[2];
68
69
        if ($this->length) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->length of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
70
            $name = substr(strrev($name), 0, $this->length);
71
            $name = strrev($name);
72
        }
73
74
        $name = trim($this->getBasename(stripslashes($name)), ".\x00..\x20");
75
        if (!$name) {
76
            $name = str_replace('.', '-', microtime(true));
77
        }
78
79
        return $name;
80
    }
81
82
    /**
83
     * Get unique file name
84
     *
85
     * @param UploadedFile $uploadedFile
86
     *
87
     * @return string
88
     */
89
    protected function getUniqueFileName(UploadedFile $uploadedFile)
90
    {
91
        $name = $uploadedFile->name;
92
93
        while (is_dir($this->getUploadDir($name))) {
94
            $name = $this->upCountName($name);
95
        }
96
97
        $uploadedBytes = (int)$uploadedFile->contentRange[1];
98
        while (is_file($this->getUploadDir($name))) {
99
            if ($uploadedBytes === $this->getFileSize($this->getUploadDir($name))) {
100
                break;
101
            }
102
            $name = $this->upCountName($name);
103
        }
104
105
        return $name;
106
    }
107
108
    /**
109
     * @param $name
110
     *
111
     * @return mixed
112
     */
113
    protected function upCountName($name)
114
    {
115
        return preg_replace_callback('/(?:(?:_([\d]+))?(\.[^.]+))?$/', function ($matches) {
116
            $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
117
            $ext = isset($matches[2]) ? $matches[2] : '';
118
119
            return '_' . $index . $ext;
120
        }, $name, 1);
121
    }
122
123
    /**
124
     * Get file base name
125
     *
126
     * @param string $filePath
127
     * @param null|string $suffix
128
     *
129
     * @return bool|string
130
     */
131
    protected function getBasename(string $filePath, ?string $suffix = null)
132
    {
133
        $splited = preg_split('/\//', rtrim($filePath, '/ '));
134
135
        return substr(basename('X' . $splited[count($splited) - 1], $suffix), 1);
136
    }
137
138
    /**
139
     * Get file size
140
     *
141
     * @param string $filePath
142
     * @param bool $clearStatCache
143
     *
144
     * @return float
145
     */
146
    protected function getFileSize(string $filePath, bool $clearStatCache = false)
147
    {
148
        if ($clearStatCache) {
149
            if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
150
                clearstatcache(true, $filePath);
151
            } else {
152
                clearstatcache();
153
            }
154
        }
155
156
        return filesize($filePath);
157
    }
158
159
    /**
160
     * Get upload path
161
     *
162
     * @param null|string $fileName
163
     * @param null|string $version
164
     *
165
     * @return string
166
     */
167
    protected function getUploadDir(?string $fileName = null, ?string $version = null)
168
    {
169
        $fileName = $fileName ? $fileName : '';
170
        if (empty($version)) {
171
            $versionPath = '';
172
        } else {
173
            $versionPath = $version . '/';
174
        }
175
176
        return $this->uploadDir . $versionPath . $fileName;
177
    }
178
}
179