|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace hipanel\helpers; |
|
4
|
|
|
|
|
5
|
|
|
use Yii; |
|
6
|
|
|
use yii\base\InvalidParamException; |
|
7
|
|
|
|
|
8
|
|
|
class FileHelper extends \yii\helpers\FileHelper |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Returns the MIME-type of content in string |
|
12
|
|
|
* @param string $content |
|
13
|
|
|
* @return string Content mime-type |
|
14
|
|
|
*/ |
|
15
|
|
|
public static function getContentMimeType($content) |
|
16
|
|
|
{ |
|
17
|
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE); |
|
18
|
|
|
$mimeType = finfo_buffer($finfo, $content); |
|
19
|
|
|
finfo_close($finfo); |
|
20
|
|
|
|
|
21
|
|
|
return $mimeType; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Builds path to the file $filename under the $directory with additional sub-directories. |
|
26
|
|
|
* For example, the $directory is `/var/log/yii`, the $filename is `f0527.jpg`. |
|
27
|
|
|
* Calling this method without passing optional parameters, will generate the following path: |
|
28
|
|
|
* `/var/log/yii/f0/f0527.jpg`. |
|
29
|
|
|
* Setting $nests to `2`, the path will look like `/var/log/yii/f0/52/f0527.jpg` |
|
30
|
|
|
* Setting $nests to `3` and $length to `1` you will get `/var/log/yii/f/0/5/f0527.jpg`. |
|
31
|
|
|
* |
|
32
|
|
|
* It is strongly recommended to pass only hashes as $filename in order be sure that length is enough. |
|
33
|
|
|
* |
|
34
|
|
|
* @param string $directory Path to the base directory |
|
35
|
|
|
* @param string $filename The file name |
|
36
|
|
|
* @param int $nests Number of nested directories |
|
37
|
|
|
* @param int $length Length of the nested directory name |
|
38
|
|
|
* @return string |
|
39
|
|
|
* @throws InvalidParamException filename does not contain enough characters for directory nesting |
|
40
|
|
|
*/ |
|
41
|
|
|
public static function getPrefixedPath($directory, $filename, $nests = 1, $length = 2) |
|
42
|
|
|
{ |
|
43
|
|
|
if (strlen(basename($filename)) < $nests * $length) { |
|
44
|
|
|
throw new InvalidParamException('Filename does not contain enough characters for directory nesting'); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
for ($start = 0; $start < $nests * $length; $start += $length) { |
|
48
|
|
|
$level = substr($filename, $start, $length); |
|
49
|
|
|
$directory .= DIRECTORY_SEPARATOR . $level; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$directory .= DIRECTORY_SEPARATOR . $filename; |
|
53
|
|
|
|
|
54
|
|
|
return Yii::getAlias($directory); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|