Completed
Push — master ( 6fbb52...2e9214 )
by Carlos C
06:52
created

CurlDownloader::download()   C

Complexity

Conditions 7
Paths 18

Size

Total Lines 32
Code Lines 25

Duplication

Lines 3
Ratio 9.38 %

Importance

Changes 0
Metric Value
dl 3
loc 32
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 25
nc 18
nop 2
1
<?php
2
namespace XmlSchemaValidator\Downloader;
3
4
class CurlDownloader implements DownloaderInterface
5
{
6
    public function download($url, $timeout)
7
    {
8 View Code Duplication
        if (false === $tempname = tempnam(null, null)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
9
            throw new \RuntimeException('Cannot create a temporary file');
10
        }
11
        if (false === $fileHandler = fopen($tempname, 'w+')) {
12
            throw new \RuntimeException("Cannot create file $tempname");
13
        }
14
        try {
15
            $ch = curl_init();
16
            curl_setopt($ch, CURLOPT_URL, $url);
17
            curl_setopt($ch, CURLOPT_VERBOSE, false);
18
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
19
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
20
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
21
            curl_setopt($ch, CURLOPT_FILE, $fileHandler);
22
            if (! curl_exec($ch)) {
23
                $curlError = ('' !== $curlError = curl_error($ch)) ? ' ' . $curlError : '';
24
                throw new \RuntimeException("Download fail for url $url" . $curlError);
25
            }
26
            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
27
            if (200 !== $statusCode) {
28
                throw new \RuntimeException("Download fail for url $url Status code was not 200 - OK");
29
            }
30
            fclose($fileHandler);
31
            return $tempname;
32
        } catch (\Exception $ex) {
33
            fclose($fileHandler);
34
            unlink($tempname);
35
            throw $ex;
36
        }
37
    }
38
}
39