1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace luya\helpers; |
4
|
|
|
|
5
|
|
|
use ZipArchive; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Helper methods when dealing with ZIP Archives. |
9
|
|
|
* |
10
|
|
|
* @author Basil Suter <[email protected]> |
11
|
|
|
* @since 1.0.0 |
12
|
|
|
*/ |
13
|
|
|
class ZipHelper |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Add files and sub-directories in a folder to zip file. |
17
|
|
|
* |
18
|
|
|
* @param string $folder |
19
|
|
|
* @param \ZipArchive $zipFile |
20
|
|
|
* @param integer $exclusiveLength Number of text to be exclusived from the file path. |
21
|
|
|
*/ |
22
|
|
|
private static function folderToZip($folder, &$zipFile, $exclusiveLength) |
23
|
|
|
{ |
24
|
|
|
$handle = opendir($folder); |
25
|
|
|
while (false !== $f = readdir($handle)) { |
26
|
|
|
if ($f != '.' && $f != '..') { |
27
|
|
|
$filePath = "$folder/$f"; |
28
|
|
|
// Remove prefix from file path before add to zip. |
29
|
|
|
$localPath = substr($filePath, $exclusiveLength); |
30
|
|
|
if (is_file($filePath)) { |
31
|
|
|
$zipFile->addFile($filePath, $localPath); |
32
|
|
|
} elseif (is_dir($filePath)) { |
33
|
|
|
// Add sub-directory. |
34
|
|
|
$zipFile->addEmptyDir($localPath); |
35
|
|
|
self::folderToZip($filePath, $zipFile, $exclusiveLength); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
closedir($handle); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Zip a folder (include itself). |
44
|
|
|
* |
45
|
|
|
* ```php |
46
|
|
|
* \luya\helper\Zip::zipDir('/path/to/sourceDir', '/path/to/out.zip'); |
47
|
|
|
* ``` |
48
|
|
|
* |
49
|
|
|
* @param string $sourcePath Path of directory to be zip. |
50
|
|
|
* @param string $outZipPath Path of output zip file. |
51
|
|
|
*/ |
52
|
|
|
public static function dir($sourcePath, $outZipPath) |
53
|
|
|
{ |
54
|
|
|
$pathInfo = pathInfo($sourcePath); |
55
|
|
|
$parentPath = $pathInfo['dirname']; |
56
|
|
|
$dirName = $pathInfo['basename']; |
57
|
|
|
|
58
|
|
|
$z = new ZipArchive(); |
59
|
|
|
$z->open($outZipPath, ZIPARCHIVE::CREATE); |
60
|
|
|
$z->addEmptyDir($dirName); |
61
|
|
|
self::folderToZip($sourcePath, $z, strlen("$parentPath/")); |
62
|
|
|
$z->close(); |
63
|
|
|
|
64
|
|
|
return true; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|