Passed
Push — master ( a5e8db...945884 )
by Danny
02:33
created

Zip::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 3
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace PressCLI\ThemeInstall;
3
4
use ZipArchive;
5
use PressCLI\Lib\Download;
6
7
class Zip
8
{
9
    /**
10
     * Downloads a theme and unzips it.
11
     *
12
     * @param  string $url       The URL to download the theme.
13
     * @param  string $directory The directory to download the theme to.
14
     * @param  string $name      The theme directory name.
15
     *
16
     * @return string            The path to the downloaded theme on success and an empty string on failure.    .
17
     */
18
    public static function execute($url, $directory, $name)
19
    {
20
        $directory = rtrim($directory, '/');
21
        $zip = Download::execute($url, $directory, 'zip');
22
        if (!$zip) {
23
            return '';
24
        }
25
26
        self::extract($zip, $directory, $name);
27
28
        return "{$directory}/{$name}";
29
    }
30
31
    /**
32
     * Rename the extracted zip file.
33
     *
34
     * @param  string $extracted The extracted zip file location.
35
     * @param  string $directory The extracted zip file directory.
36
     * @param  string $name      The name to rename the extracted zip file.
37
     */
38
    protected static function rename($extracted, $directory, $name)
39
    {
40
        if (file_exists($extracted)) {
41
            rename($extracted, "{$directory}/{$name}");
42
        }
43
    }
44
45
    /**
46
     * Deletes the downloaded zip.
47
     *
48
     * @param  string $zip The path to the zip file.
49
     */
50
    protected static function cleanUp($zip)
51
    {
52
        if (file_exists($zip)) {
53
            unlink($zip);
54
        }
55
    }
56
57
    /**
58
     * Extracts a zip file.
59
     *
60
     * @param  string $zip       The path to the zip file.
61
     * @param  string $directory The extraction directory.
62
     */
63
    public static function extract($zip, $directory, $name)
64
    {
65
        $archive = new ZipArchive;
66
67
        // Open and extract the zip to the specified directory.
68
        $archive->open($zip);
69
        $archive->extractTo($directory);
70
71
        // Rename the theme and close the archive.
72
        $extractedName = $archive->getNameIndex(0);
73
        self::rename("{$directory}/{$extractedName}", $directory, $name);
74
        $archive->close();
75
76
        // Remove the downloaded zip.
77
        self::cleanUp($zip);
78
    }
79
}
80