ZipHelper   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 15
c 2
b 0
f 1
dl 0
loc 41
ccs 16
cts 16
cp 1
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generateRandomNameOfArchive() 0 6 1
A createArchiveFromDirectory() 0 22 4
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 2
    public static function generateRandomNameOfArchive(): string
15
    {
16 2
        $suffix = '-Archive.zip';
17 2
        $str    = uniqid($suffix, true);
18
19 2
        return str_replace('.', '', substr($str, 12, -4)) . $suffix;
20
    }
21
22
    /**
23
     * Add files from directory to archive
24
     *
25
     * @param string      $directoryPath Absolute or relative path
26
     * @param null|string $name          Name of archive, if empty the will be generated
27
     */
28 2
    public static function createArchiveFromDirectory(string $directoryPath, ?string $name = null): string
29
    {
30 2
        if (empty($name)) {
31 1
            $name = self::generateRandomNameOfArchive();
32
        }
33
34 2
        $zip = new ZipArchive();
35 2
        $zip->open($name, ZipArchive::CREATE);
36
37 2
        $fixer = new PathFixer($directoryPath);
38
39 2
        foreach (FSHelper::getDirectories($directoryPath) as $dir) {
40 2
            $zip->addEmptyDir($fixer->fix($dir->getPathname()));
41
        }
42
43 2
        foreach (FSHelper::getFiles($directoryPath) as $file) {
44 2
            $zip->addFile($file->getPathname(), $fixer->fix($file->getPathname()));
45
        }
46
47 2
        $zip->close();
48
49 2
        return $name;
50
    }
51
}
52