-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFile.php
90 lines (82 loc) · 2.42 KB
/
File.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace ArtSkills\Filesystem;
use ArtSkills\Error\InternalException;
use ArtSkills\Lib\Env;
use ArtSkills\Lib\Strings;
class File extends \Cake\Filesystem\File
{
/**
* Зипует файлы
*
* @param string[]|string $files - файлы, которые нужно зипануть
* @param string|null $newFile - полное имя нового файла. если не передать, то будет self::DOWNLOAD_PATH . uniqid()
* @param bool $deleteOld - удалять ли файлы
* @return string Имя файла
* @throws InternalException
*/
public static function zip($files, $newFile = null, $deleteOld = false)
{
$files = (array)$files;
if (empty($newFile)) {
$defaultPath = Env::getDownloadPath();
if (empty($defaultPath)) {
throw new InternalException('Путь не задан явно и нет пути по-умолчанию');
}
Folder::createIfNotExists($defaultPath);
$newFile = $defaultPath . uniqid();
}
if (!preg_match('/\.zip$/i', $newFile)) {
$newFile .= '.zip';
}
$tmpDir = TMP . uniqid();
mkdir($tmpDir);
$zipFiles = [];
$currentDir = getcwd();
chdir($tmpDir);
foreach ($files as $sourceFile) {
$tmpFile = Strings::lastPart(DS, $sourceFile);
$zipFiles[] = $tmpFile;
if ($deleteOld) {
rename($sourceFile, $tmpFile);
} else {
if (is_dir($sourceFile)) {
exec("cp -r $sourceFile $tmpFile");
} else {
copy($sourceFile, $tmpFile);
}
}
}
if (file_exists($newFile)) {
unlink($newFile);
}
exec('zip -r "' . $newFile . '" "' . implode('" "', $zipFiles) . '"');
chdir($currentDir);
exec("rm -rf $tmpDir");
return $newFile;
}
/**
* Распаковать архив
* по умолчанию рядом с архивом
*
* @param string $pathToFile
* @param null|string $unzipFolder
* @throws \Exception
*/
public static function unZip($pathToFile, $unzipFolder = null)
{
$extension = strstr(pathinfo($pathToFile)['basename'], '.');
if (!empty($unzipFolder)) {
!file_exists($unzipFolder) ? mkdir($unzipFolder) : null;
}
switch ($extension) {
case '.tar.gz':
$unpackPath = !empty($unzipFolder) ? $unzipFolder : dirname($pathToFile);
exec('tar -xf ' . $pathToFile . ' -C ' . $unpackPath);
break;
default:
$unpackPath = !empty($unzipFolder) ? $unzipFolder : dirname($pathToFile);
exec('unzip ' . $pathToFile . ' -d ' . $unpackPath);
break;
}
}
}