Completed
Push — master ( b4d6a5...352f6d )
by Basil
02:42
created

ZipHelper::folderToZip()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.0111
c 0
b 0
f 0
cc 6
nc 5
nop 3
1
<?php
2
3
namespace luya\helpers;
4
5
use ZipArchive;
6
7
/**
8
 * Helper methods when dealing with ZIP Archives.
9
 *
10
 * @author Basil Suter <[email protected]>
11
 * @since 1.0.0
12
 */
13
class ZipHelper
14
{
15
    /**
16
     * Add files and sub-directories in a folder to zip file.
17
     *
18
     * @param string $folder
19
     * @param \ZipArchive $zipFile
20
     * @param integer $exclusiveLength Number of text to be exclusived from the file path.
21
     */
22
    private static function folderToZip($folder, &$zipFile, $exclusiveLength)
23
    {
24
        $handle = opendir($folder);
25
        while (false !== $f = readdir($handle)) {
26
            if ($f != '.' && $f != '..') {
27
                $filePath = "$folder/$f";
28
                // Remove prefix from file path before add to zip.
29
                $localPath = substr($filePath, $exclusiveLength);
30
                if (is_file($filePath)) {
31
                    $zipFile->addFile($filePath, $localPath);
32
                } elseif (is_dir($filePath)) {
33
                    // Add sub-directory.
34
                    $zipFile->addEmptyDir($localPath);
35
                    self::folderToZip($filePath, $zipFile, $exclusiveLength);
36
                }
37
            }
38
        }
39
        closedir($handle);
40
    }
41
42
    /**
43
     * Zip a folder (include itself).
44
     *
45
     * ```php
46
     * \luya\helper\Zip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
47
     * ```
48
     *
49
     * @param string $sourcePath Path of directory to be zip.
50
     * @param string $outZipPath Path of output zip file.
51
     */
52
    public static function dir($sourcePath, $outZipPath)
53
    {
54
        $pathInfo = pathInfo($sourcePath);
55
        $parentPath = $pathInfo['dirname'];
56
        $dirName = $pathInfo['basename'];
57
58
        $z = new ZipArchive();
59
        $z->open($outZipPath, ZIPARCHIVE::CREATE);
60
        $z->addEmptyDir($dirName);
61
        self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
62
        $z->close();
63
        
64
        return true;
65
    }
66
}
67