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