AssetDownloader::to()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Koine\AssetDownloader;
4
5
use GuzzleHttp\Client;
6
use League\Flysystem\Adapter\Local;
7
use League\Flysystem\Filesystem;
8
use Psr\Http\Message\UriInterface;
9
10
class AssetDownloader
11
{
12
    /**
13
     * @var string
14
     */
15
    private $from;
16
17
    /**
18
     * @var Filesystem
19
     */
20
    private $fileSystem;
21
22
    /**
23
     * @var Client
24
     */
25
    private $httpClient;
26
27
    /**
28
     * @param array $config
29
     *                      Allowed keys:
30
     *                      - from type: Sting
31
     *                      - destination type: Sting
32
     *                      - httpClient type: @see Client
33
     */
34
    public function __construct(array $config = [])
35
    {
36
        if (isset($config['fileSystem'])) {
37
            $this->setFilesystem($config['fileSystem']);
38
        }
39
40
        if (!isset($config['httpClient'])) {
41
            $config['httpClient'] = new Client();
42
        }
43
44
        if (isset($config['from'])) {
45
            $this->from($config['from']);
46
        }
47
48
        if (isset($config['destination'])) {
49
            $this->to($config['destination']);
50
        }
51
52
        $this->setHttpClient($config['httpClient']);
53
    }
54
55
    public function download(UriInterface $uri)
56
    {
57
        $path = $uri->getPath();
58
        $source = $this->from . $path;
59
        $contents = $this->httpClient->request('GET', $source)->getBody();
60
        $this->getFilesystem()->write($path, $contents);
61
    }
62
63
    /**
64
     * @param string $from
65
     *
66
     * @return self
67
     */
68
    public function from($from)
69
    {
70
        $this->from = rtrim($from, '/');
71
72
        return $this;
73
    }
74
75
    /**
76
     * @param string $to path to save the assets
77
     *
78
     * @return self
79
     */
80
    public function to($to)
81
    {
82
        $filesystem = new Filesystem(new Local($to));
83
        $this->setFilesystem($filesystem);
84
85
        return $this;
86
    }
87
88
    private function getFilesystem()
89
    {
90
        if ($this->fileSystem === null) {
91
            throw new \LocalException('Destination was not set');
92
        }
93
94
        return $this->fileSystem;
95
    }
96
97
    private function setHttpClient(Client $client)
98
    {
99
        $this->httpClient = $client;
100
    }
101
102
    private function setFilesystem(Filesystem $fileSystem)
103
    {
104
        $this->fileSystem = $fileSystem;
105
    }
106
}
107