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

Download   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 3
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 15 2
A makeTempName() 0 4 1
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