1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Eclipxe\XmlResourceRetriever\Downloader; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
use RuntimeException; |
10
|
|
|
|
11
|
|
|
class PhpDownloader implements DownloaderInterface |
12
|
|
|
{ |
13
|
|
|
/** @var resource */ |
14
|
|
|
private $context; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* PhpDownloader constructor. |
18
|
|
|
* @param resource|null $context A valid context created with stream_context_create |
19
|
|
|
*/ |
20
|
23 |
|
public function __construct($context = null) |
21
|
|
|
{ |
22
|
23 |
|
if (null === $context) { |
23
|
22 |
|
$context = $this->createContext(); |
24
|
|
|
} |
25
|
23 |
|
$this->setContext($context); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** @return resource */ |
29
|
13 |
|
public function getContext() |
30
|
|
|
{ |
31
|
13 |
|
return $this->context; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Set the context (created with stream_context_create) that will be used when try to download |
36
|
|
|
* @param resource|mixed $context |
37
|
|
|
* @see https://php.net/stream-context-create |
38
|
|
|
*/ |
39
|
23 |
|
public function setContext($context): void |
40
|
|
|
{ |
41
|
23 |
|
if (! is_resource($context)) { |
42
|
1 |
|
throw new InvalidArgumentException('Provided context is not a resource'); |
43
|
|
|
} |
44
|
23 |
|
if ('stream-context' !== get_resource_type($context)) { |
45
|
1 |
|
throw new InvalidArgumentException( |
46
|
1 |
|
sprintf('Provided context is not a stream-context resource, given: %s', get_resource_type($context)) |
47
|
1 |
|
); |
48
|
|
|
} |
49
|
23 |
|
$this->context = $context; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** @return resource */ |
53
|
22 |
|
public function createContext() |
54
|
|
|
{ |
55
|
22 |
|
return stream_context_get_default(); |
56
|
|
|
} |
57
|
|
|
|
58
|
11 |
|
public function downloadTo(string $source, string $destination): void |
59
|
|
|
{ |
60
|
|
|
/** @noinspection PhpUsageOfSilenceOperatorInspection */ |
61
|
11 |
|
if (! @copy($source, $destination, $this->getContext())) { |
62
|
1 |
|
$previousException = null; |
63
|
1 |
|
if (null !== $lastError = error_get_last()) { |
64
|
1 |
|
$previousException = new Exception($lastError['message']); |
65
|
|
|
} |
66
|
1 |
|
throw new RuntimeException("Unable to download $source to $destination", 0, $previousException); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|