Passed
Pull Request — master (#18)
by
unknown
08:11
created

Downloader::downloadFile()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 15
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 21
ccs 0
cts 14
cp 0
crap 20
rs 9.7666
1
<?php
2
3
namespace MadWizard\WebAuthn\Remote;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\RequestException;
7
use MadWizard\WebAuthn\Exception\RemoteException;
8
use Psr\Http\Client\ClientExceptionInterface;
9
use Psr\Log\LoggerAwareInterface;
10
use Psr\Log\LoggerAwareTrait;
11
use Psr\Log\NullLogger;
12
13
class Downloader implements DownloaderInterface, LoggerAwareInterface
14
{
15
    use LoggerAwareTrait;
16
17
    /**
18
     * @var Client
19
     */
20
    private $client;
21
22
    public function __construct(Client $client)     // TODO use clientfactory and ClientInterface
23
    {
24
        $this->client = $client;
25
        $this->logger = new NullLogger();
26
    }
27
28
    public function downloadFile(string $uri): FileContents
29
    {
30
        // TODO: remove token in logging?
31
        try {
32
            $response = $this->client->get($uri);
33
        } catch (RequestException $e) {
34
            $errorResponse = $e->getResponse();
35
            if ($errorResponse) {
36
                $message = sprintf('Error response while downloading URL: %d %s', $errorResponse->getStatusCode(), $errorResponse->getReasonPhrase());
37
            } else {
38
                $message = sprintf('Failed to download URL: %s', $e->getMessage());
39
            }
40
            throw new RemoteException($message, 0, $e);
41
        } catch (ClientExceptionInterface $e) {
42
            throw new RemoteException(sprintf('Failed to download URL: %s', $e->getMessage()), 0, $e);
43
        }
44
45
        $content = $response->getBody()->getContents();
46
        $types = $response->getHeader('Content-Type');
47
        $contentType = $types[0] ?? 'application/octet-stream';
48
        return new FileContents($content, $contentType);
49
    }
50
}
51