|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the core-library package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 2018 WEBEWEB |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace WBW\Library\Core\Archive; |
|
13
|
|
|
|
|
14
|
|
|
use InvalidArgumentException; |
|
15
|
|
|
use RecursiveDirectoryIterator; |
|
16
|
|
|
use RecursiveIteratorIterator; |
|
17
|
|
|
use ZipArchive; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Archive helper. |
|
21
|
|
|
* |
|
22
|
|
|
* @author webeweb <https://github.com/webeweb/> |
|
23
|
|
|
* @package WBW\Library\Core\Archive |
|
24
|
|
|
*/ |
|
25
|
|
|
class ArchiveHelper { |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Create a ZIP archive. |
|
29
|
|
|
* |
|
30
|
|
|
* @param string $src The source. |
|
31
|
|
|
* @param string $dst The destination. |
|
32
|
|
|
* @return bool Returns true in case of success, false otherwise. |
|
33
|
|
|
* @throws InvalidArgumentException Throws a file not found exception if the source filename is not found. |
|
34
|
|
|
*/ |
|
35
|
|
|
public static function zip($src, $dst) { |
|
36
|
|
|
|
|
37
|
|
|
if (false === file_exists($src)) { |
|
38
|
|
|
throw new InvalidArgumentException(sprintf("The file \"%s\" was not found", $src)); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
$zipArch = new ZipArchive(); |
|
42
|
|
|
$zipArch->open($dst, ZipArchive::CREATE); |
|
43
|
|
|
|
|
44
|
|
|
$srcPath = str_replace("\\\\", "/", realpath($src)); |
|
45
|
|
|
|
|
46
|
|
|
if (true === is_file($srcPath)) { |
|
47
|
|
|
$zipArch->addFromString(basename($srcPath), file_get_contents($srcPath)); |
|
48
|
|
|
return $zipArch->close(); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
// Handle the files list. |
|
52
|
|
|
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($srcPath), RecursiveIteratorIterator::SELF_FIRST); |
|
53
|
|
|
foreach ($files as $current) { |
|
54
|
|
|
|
|
55
|
|
|
$curPath = str_replace("\\\\", "/", realpath($current)); |
|
56
|
|
|
$zipPath = preg_replace("/^" . str_replace("/", "\/", $srcPath . "/") . "/", "", $curPath); |
|
57
|
|
|
|
|
58
|
|
|
if (true === is_file($curPath)) { |
|
59
|
|
|
$zipArch->addFromString($zipPath, file_get_contents($curPath)); |
|
60
|
|
|
continue; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$zipArch->addEmptyDir($zipPath); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|