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

Download::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 3
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace PressCLI\Lib;
3
4
use GuzzleHttp\Client;
5
6
class Download
7
{
8
    /**
9
     * Downloads a file.
10
     *
11
     * @param  string $url       The URL to download the file.
12
     * @param  string $directory The directory to download the file to.
13
     * @param  string $type      The file type (zip|tar) to save the downloaded file as.
14
     *
15
     * @return string            The path to the downloaded file on success and an empty string on failure.    .
16
     */
17
    public static function execute($url, $directory, $type)
18
    {
19
        // Download the file.
20
        $client = new Client();
21
        $response = $client->get($url);
22
        if (200 !== $response->getStatusCode()) {
23
            return '';
24
        }
25
26
        // Store the temporary file.
27
        $tempFile = self::makeTempName($directory, $type);
28
        file_put_contents($tempFile, $response->getBody());
29
30
        return $tempFile;
31
    }
32
33
    /**
34
     * Makes the downloaded files temporary name.
35
     *
36
     * @param  string $directory The directory the file is downloaded to.
37
     * @param  string $type      The file type (zip|tar) to save the downloaded file as.
38
     *
39
     * @return string            The temporary file name.
40
     */
41
    protected static function makeTempName($directory, $type)
42
    {
43
        return $directory . '/' . md5(time().uniqid()) . ".{$type}";
44
    }
45
}
46