Created
February 21, 2019 09:45
-
-
Save dawidgora-old-account/02357c68496a049e1b99c3c6e2d33fc9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helper; | |
/** | |
* @author Dawid Góra <[email protected]> | |
*/ | |
class ZipHelper | |
{ | |
/** | |
* @param string $inputPath | |
* @param string $outputPath | |
* @throws \Exception | |
*/ | |
public function zipDirectory(string $inputPath, string $outputPath): void | |
{ | |
$zip = new \ZipArchive(); | |
if ($zip->open($outputPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) { | |
throw new \Exception('Unable to open zip archive'); | |
} | |
$inputPath = rtrim($inputPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; | |
$this->addToZip($inputPath, null, $zip); | |
$zip->close(); | |
} | |
/** | |
* @param string $basePath | |
* @param string|null $relativePath | |
* @param \ZipArchive $zip | |
*/ | |
private function addToZip(string $basePath, ?string $relativePath, \ZipArchive $zip): void | |
{ | |
$path = $basePath . $relativePath; | |
foreach (scandir($path) as $file) { | |
if (in_array($file, ['.', '..'])) { | |
continue; | |
} | |
$filePath = $path . $file; | |
$relativeFilePath = $relativePath . $file; | |
if (is_dir($filePath)) { | |
$zip->addEmptyDir($relativeFilePath); | |
$this->addToZip($basePath, $relativePath . $file . DIRECTORY_SEPARATOR, $zip); | |
} else { | |
$zip->addFile($filePath, $relativeFilePath); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment