5 * .zip file wrapper that works with directories (unzipped files)
10 * Path to .zip file (null when directory)
15 * Directory path with trailing slash (null when zip)
24 public function __construct($path, $readOnly = true)
27 $this->dirPath = rtrim($path, '/') . '/';
29 $this->zipPath = $path;
30 $this->zip = new \ZipArchive();
31 $res = $this->zip->open(
33 $readOnly ? \ZipArchive::RDONLY : 0
37 \ZipArchive::ER_EXISTS => 'File already exists',
38 \ZipArchive::ER_INCONS => 'Zip archive inconsistent',
39 \ZipArchive::ER_INVAL => 'Invalid argument',
40 \ZipArchive::ER_MEMORY => 'Malloc failure',
41 \ZipArchive::ER_NOENT => 'No such file',
42 \ZipArchive::ER_NOZIP => 'Not a zip archive',
43 \ZipArchive::ER_OPEN => 'Can\'t open file',
44 \ZipArchive::ER_READ => 'Read error',
45 \ZipArchive::ER_SEEK => 'Seek error',
48 'Error opening .epub file: ' . $errorMap[$res]
55 * (Over)write content of single file inside the zip archive
57 public function addFromString($filePath, $content): bool
60 return $this->zip->addFromString($filePath, $content);
62 return file_put_contents($this->dirPath . $filePath, $content) !== false;
67 * Write ZIP archive contents
69 public function close(): bool
72 return $this->zip->close();
81 public function deleteName($filePath): bool
84 return $this->zip->deleteName($filePath);
86 return unlink($this->dirPath . $filePath);
91 * Get content of given file path
93 * @return string|false false on error
95 public function getFromName($filePath)
98 return $this->zip->getFromName($filePath);
100 return file_get_contents($this->dirPath . $filePath);
105 * foreach() over all files
107 * @return array|Iterator
109 public function filesIterator()
112 for ($n = 0; $n < $this->zip->numFiles; $n++) {
113 $info = $this->zip->statIndex($n);
117 $it = new \RecursiveIteratorIterator(
118 new \RecursiveDirectoryIterator($this->dirPath)
121 while($it->valid()) {
123 yield substr($it->getPathname(), strlen($this->dirPath));