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
|
|
|
|