Passed
Branch dev (152e5d)
by compolom
02:01
created

ZipHelper::generateRandomNameOfArchive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Compolomus\FSHelper;
6
7
use ZipArchive;
8
9
class ZipHelper
10
{
11
    /**
12
     * Return string with default name of archive
13
     *
14
     * @return string
15
     */
16
    public static function generateRandomNameOfArchive(): string
17
    {
18
        $suffix = '-Archive.zip';
19
        $str    = uniqid($suffix, true);
20
21
        return str_replace('.', '', substr($str, 12, -4)) . $suffix;
22
    }
23
24
    /**
25
     * Add files from directory to archive
26
     *
27
     * @param string      $directoryPath Absolute or relative path
28
     * @param null|string $name          Name of archive, if empty the will be generated
29
     *
30
     * @return string Name with path to file
31
     */
32
    public static function createArchiveFromDirectory(string $directoryPath, string $name = null): string
33
    {
34
        if (empty($name)) {
35
            $name = self::generateRandomNameOfArchive();
36
        }
37
38
        $zip = new ZipArchive();
39
        $zip->open($name, ZipArchive::CREATE);
40
41
        $fixer = new PathFixer($directoryPath);
42
43
        foreach (FSHelper::getDirectories($directoryPath) as $dir) {
44
            $zip->addEmptyDir($fixer->fix($dir->getPathname()));
45
        }
46
47
        foreach (FSHelper::getFiles($directoryPath) as $file) {
48
            $zip->addFile($file->getPathname(), $fixer->fix($file->getPathname()));
49
        }
50
51
        $zip->close();
52
53
        return $name;
54
    }
55
}
56