1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Helpers; |
4
|
|
|
|
5
|
|
|
use Bavix\Exceptions; |
6
|
|
|
use Bavix\Exceptions\NotFound; |
7
|
|
|
use Curl\Curl; |
8
|
|
|
|
9
|
|
|
class Stream |
10
|
|
|
{ |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @param string $from |
14
|
|
|
* @param string $to |
15
|
|
|
* |
16
|
|
|
* @return bool |
17
|
|
|
* |
18
|
|
|
* @throws Exceptions\PermissionDenied |
19
|
|
|
* @throws NotFound\Path |
20
|
|
|
*/ |
21
|
3 |
|
public static function download($from, $to): bool |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var bool|resource $fromStream |
25
|
|
|
*/ |
26
|
3 |
|
$fromStream = File::open($from); |
27
|
|
|
|
28
|
3 |
|
if (!is_resource($fromStream)) |
29
|
|
|
{ |
30
|
1 |
|
throw new NotFound\Path('Stream `' . $from . '` not found'); |
31
|
|
|
} |
32
|
|
|
|
33
|
2 |
|
if (!File::real($to) && !File::touch($to)) |
34
|
|
|
{ |
35
|
1 |
|
throw new Exceptions\PermissionDenied('File `' . $to . '`'); |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
File::put($to, $fromStream); |
39
|
|
|
|
40
|
1 |
|
return File::close($fromStream); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string|array $urlOrOptions |
45
|
|
|
* @param array $data |
46
|
|
|
* |
47
|
|
|
* @return Curl |
48
|
|
|
* |
49
|
|
|
* @throws Exceptions\Invalid |
50
|
|
|
*/ |
51
|
|
|
public static function upload($urlOrOptions, array $data = []): Curl |
52
|
|
|
{ |
53
|
|
|
|
54
|
|
|
$options = $urlOrOptions; |
55
|
|
|
|
56
|
|
|
if (is_string($options)) |
57
|
|
|
{ |
58
|
|
|
$options = ['url' => $urlOrOptions]; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if (!isset($options['url'])) |
62
|
|
|
{ |
63
|
|
|
throw new Exceptions\Invalid('Param option `URL` not found!'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$url = $options['url']; |
67
|
|
|
$method = $options['method'] ?? 'post'; |
68
|
|
|
$headers = $options['headers'] ?? []; |
69
|
|
|
|
70
|
|
|
$data = Arr::map($data, function ($value) { |
71
|
|
|
|
72
|
|
|
if (\is_string($value) && Str::first($value) === '@') |
73
|
|
|
{ |
74
|
|
|
return curl_file_create(Str::withoutFirst($value)); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $value; |
78
|
|
|
|
79
|
|
|
}); |
80
|
|
|
|
81
|
|
|
$curl = new Curl(); |
82
|
|
|
|
83
|
|
|
if (!empty($headers)) |
84
|
|
|
{ |
85
|
|
|
foreach ($headers as $key => $value) |
86
|
|
|
{ |
87
|
|
|
$headers[$key] = $key . ': ' . implode(',', (array)$value); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$curl->setOpt(CURLOPT_HTTPHEADER, Arr::getValues($headers)); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
$curl->$method($url, $data); |
94
|
|
|
|
95
|
|
|
$response = JSON::decode($curl->response); |
96
|
|
|
|
97
|
|
|
if (JSON::errorNone()) |
98
|
|
|
{ |
99
|
|
|
$curl->response = $response; |
100
|
|
|
} |
101
|
|
|
|
102
|
|
|
return $curl; |
103
|
|
|
|
104
|
|
|
} |
105
|
|
|
|
106
|
|
|
} |
107
|
|
|
|