/** * Zip files * * @param string $targetDir Target dir path * @param array $files Files to zip * * @throws \Exception */ private function zipFiles($targetDir, $files) { $zip = new \ZipArchive(); $zipName = pathinfo($files[0], PATHINFO_FILENAME); $zipPath = FileSystem::getUniquePath($targetDir . DIRECTORY_SEPARATOR . $zipName . ".zip"); if ($zip->open($zipPath, \ZipArchive::CREATE)) { foreach ($files as $file) { $path = $targetDir . DIRECTORY_SEPARATOR . $file; if (is_dir($path)) { $zip->addEmptyDir($file); foreach (Finder::find("*")->from($path) as $item) { $name = $file . DIRECTORY_SEPARATOR . substr_replace($item->getPathname(), "", 0, strlen($path) + 1); if ($item->isDir()) { $zip->addEmptyDir($name); } else { $zip->addFile($item->getRealPath(), $name); } } } else { $zip->addFile($path, $file); } } $zip->close(); } else { throw new \Exception("Can not create ZIP archive '{$zipPath}' from '{$targetDir}'."); } }