Completed
Push — master ( 0bd31b...383548 )
by Carlos C
03:30
created

PhpDownloader::setContext()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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