This repository has been archived by the owner on Jan 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathZipMaster.php
87 lines (82 loc) · 2.56 KB
/
ZipMaster.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
<?php
namespace ZipMaster;
/**
* Class ZipMaster
* @package ZipMaster
* @author Erhan Kılıç <[email protected]> https://github.com/erhankilic/ZipMaster
* @version 1.0
* @access public
* @param $zip
* @param $folder
* @param $excludes
*/
class ZipMaster
{
private $zip;
private $folder;
private $excludes = [];
/**
* ZipMaster constructor.
* @param string $output
* @param string $folder
* @param array $excludes
* @param bool $replace
* @throws \Exception
*/
public function __construct(string $output, string $folder, array $excludes = [], bool $replace = true)
{
if (empty($output) || empty($folder)) {
throw new \Exception('Output and folder can not be empty string!');
}
$this->folder = $folder;
$this->excludes = $excludes;
$this->zip = new \ZipArchive;
try {
// Replace previously created archive instead of updating it
if ($replace && file_exists($output)) {
unlink($output);
}
$this->zip->open($output, \ZipArchive::CREATE);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}
/**
* Opens the folder and reads all files and directories under the folder.
* If there is directory, it calls itself again.
*
* @param string $folder
* @param string|null $dir
* @access private
*/
private function archiveFolder(string $folder, $dir = null)
{
if ($handle = opendir($folder)) {
// Read all files and directories
while (false !== ($entry = readdir($handle))) {
// If file or directory isn't in excludes
if ($entry != "." && $entry != ".." && !in_array($entry, $this->excludes)) {
if (is_dir($folder . '/' . $entry)) {
// If it's directory, call archiveFolder function again
$this->archiveFolder($folder . '/' . $entry, $dir . '/' . $entry);
} else {
// Add all files inside the directory
$this->zip->addFile($folder . '/' . $entry, $dir . '/' . $entry);
}
}
}
closedir($handle);
}
}
/**
* Archive the folder
*
* @param string|null $rootDirName
* @access public
*/
public function archive($rootDirName = null)
{
$this->archiveFolder($this->folder, $rootDirName);
$this->zip->close();
}
}