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

Downloader   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 20
c 3
b 0
f 0
dl 0
loc 36
ccs 0
cts 18
cp 0
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A downloadFile() 0 21 4
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