Skip to content

Commit e0c1242

Browse files
committed
support for adding empty directories. resolves #62
1 parent d635333 commit e0c1242

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/Builder.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ class Builder implements Responsable
3737

3838
protected Closure $afterProcessing;
3939

40+
protected array $directories = [];
41+
4042
public function __construct(array $files = [])
4143
{
4244
$this->queue = new Queue();
@@ -88,6 +90,13 @@ public function addRaw($content, string $zipPath): self
8890
return $this->add(new TempFile($content, $zipPath));
8991
}
9092

93+
public function addDirectory(string $name): self
94+
{
95+
$this->directories[] = $name;
96+
97+
return $this;
98+
}
99+
91100
public function setMeta(array $meta): self
92101
{
93102
$this->meta = collect($meta);
@@ -243,6 +252,10 @@ protected function prepare(): ZipStream
243252

244253
$this->queue->each->prepare($zip);
245254

255+
foreach($this->directories as $directory) {
256+
$zip->addDirectory($directory);
257+
}
258+
246259
return $zip;
247260
}
248261

tests/ZipTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,4 +136,32 @@ public function testSaveToDisk()
136136
$this->assertTrue(file_exists("/tmp/my-prefix/$folder/test.zip"));
137137
unlink("/tmp/my-prefix/$folder/test.zip");
138138
}
139+
140+
public function testEmptyDirectory()
141+
{
142+
$testrun = microtime();
143+
file_put_contents("/tmp/test1.txt", "this is the first test file for test run $testrun");
144+
145+
/** @var Builder $zip */
146+
$zip = Zip::create("test.zip", ["/tmp/test1.txt"])->addDirectory($directory = Str::random());
147+
148+
// Create a random folder path that doesn't exist, so we know it was created
149+
$dir = "/tmp/" . Str::random();
150+
$zip->saveTo($dir);
151+
152+
$this->assertTrue(file_exists("$dir/test.zip"));
153+
154+
$z = new ZipArchive();
155+
$z->open("$dir/test.zip");
156+
$this->assertEquals(2, $z->numFiles);
157+
$this->assertNotFalse($z->getFromName($directory . "/"));
158+
159+
$z->extractTo($dir . "/extracted");
160+
$this->assertTrue(file_exists("$dir/extracted/$directory/"));
161+
$this->assertTrue(is_dir("$dir/extracted/$directory/"));
162+
163+
rmdir("$dir/extracted/$directory/");
164+
unlink("$dir/extracted/test1.txt");
165+
unlink("$dir/test.zip");
166+
}
139167
}

0 commit comments

Comments
 (0)