|
| 1 | +<?php declare (strict_types = 1); |
| 2 | + |
| 3 | +namespace Wavevision\Utils\Zip; |
| 4 | + |
| 5 | +use Nette\FileNotFoundException; |
| 6 | +use Nette\SmartObject; |
| 7 | +use Wavevision\Utils\FileInfo; |
| 8 | +use Wavevision\Utils\Path; |
| 9 | +use ZipArchive as Zip; |
| 10 | + |
| 11 | +class ZipArchive |
| 12 | +{ |
| 13 | + |
| 14 | + use SmartObject; |
| 15 | + |
| 16 | + /** |
| 17 | + * @var ZipArchiveFile[] |
| 18 | + */ |
| 19 | + private array $files; |
| 20 | + |
| 21 | + private string $path; |
| 22 | + |
| 23 | + private Zip $zip; |
| 24 | + |
| 25 | + public function __construct(string $path, ZipArchiveFile ...$files) |
| 26 | + { |
| 27 | + $this->files = $files; |
| 28 | + $this->path = $path; |
| 29 | + $this->zip = new Zip(); |
| 30 | + } |
| 31 | + |
| 32 | + public function addFile(ZipArchiveFile $file): self |
| 33 | + { |
| 34 | + $this->files[] = $file; |
| 35 | + return $this; |
| 36 | + } |
| 37 | + |
| 38 | + public function close(): self |
| 39 | + { |
| 40 | + $this->zip->close(); |
| 41 | + return $this; |
| 42 | + } |
| 43 | + |
| 44 | + public function compress(): self |
| 45 | + { |
| 46 | + foreach ($this->files as $file) { |
| 47 | + $this->zip->addFile($this->getFilePath($file), $file->getName()); |
| 48 | + } |
| 49 | + return $this->close(); |
| 50 | + } |
| 51 | + |
| 52 | + public function extract(?string $dir = null): self |
| 53 | + { |
| 54 | + $this->zip->extractTo($dir ?? $this->getExtractDir()); |
| 55 | + return $this; |
| 56 | + } |
| 57 | + |
| 58 | + public function getName(): string |
| 59 | + { |
| 60 | + return basename($this->getPath()); |
| 61 | + } |
| 62 | + |
| 63 | + public function getPath(): string |
| 64 | + { |
| 65 | + return $this->path; |
| 66 | + } |
| 67 | + |
| 68 | + public function read(): self |
| 69 | + { |
| 70 | + $this->zip->open($this->getPath()); |
| 71 | + return $this; |
| 72 | + } |
| 73 | + |
| 74 | + public function write(): self |
| 75 | + { |
| 76 | + $flag = is_file($this->getPath()) ? Zip::OVERWRITE : Zip::CREATE; |
| 77 | + $this->zip->open($this->getPath(), $flag); |
| 78 | + return $this; |
| 79 | + } |
| 80 | + |
| 81 | + private function getExtractDir(): string |
| 82 | + { |
| 83 | + $fileInfo = new FileInfo($this->getPath()); |
| 84 | + return Path::join($fileInfo->getDirName(), $fileInfo->getBaseName(true)); |
| 85 | + } |
| 86 | + |
| 87 | + private function getFilePath(ZipArchiveFile $file): string |
| 88 | + { |
| 89 | + $path = $file->getPath(); |
| 90 | + if (!file_exists($path)) { |
| 91 | + throw new FileNotFoundException("Zip archive file '$path' not found."); |
| 92 | + } |
| 93 | + return $path; |
| 94 | + } |
| 95 | + |
| 96 | +} |
0 commit comments