Passed
Push — master ( 97d276...e9d799 )
by Бабичев
02:50
created

Stream::curl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
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
     * @return Curl
14
     */
15
    protected static function curl(): Curl
16
    {
17
        return new Curl();
18
    }
19
20
    /**
21
     * @param string $from
22
     * @param string $to
23
     *
24
     * @return bool
25
     *
26
     * @throws Exceptions\PermissionDenied
27
     * @throws NotFound\Path
28
     */
29 3
    public static function download($from, $to): bool
30
    {
31
        /**
32
         * @var bool|resource $fromStream
33
         */
34 3
        $fromStream = File::open($from);
35
36 3
        if (!is_resource($fromStream))
37
        {
38 1
            throw new NotFound\Path('Stream `' . $from . '` not found');
39
        }
40
41 2
        if (!File::real($to) && !File::touch($to))
42
        {
43 1
            throw new Exceptions\PermissionDenied('File `' . $to . '`');
44
        }
45
46 1
        File::put($to, $fromStream);
47
48 1
        return File::close($fromStream);
49
    }
50
51
    /**
52
     * @param string|array $options
53
     * @param array        $data
54
     *
55
     * @return Curl
56
     *
57
     * @throws Exceptions\Invalid
58
     */
59
    public static function upload($options, array $data = []): Curl
60
    {
61
62
        if (is_string($options))
63
        {
64
            $options = ['url' => $options];
65
        }
66
67
        if (!isset($options['url']))
68
        {
69
            throw new Exceptions\Invalid('Param option `URL` not found!');
70
        }
71
72
        $url    = $options['url'];
73
        $method = $options['method'] ?? 'post';
74
75
        $data = Arr::map($data, function ($value) {
76
77
            if (\is_string($value) && Str::sub($value, 0, 1) === '@')
78
            {
79
                return curl_file_create(Str::sub($value, 1));
80
            }
81
82
            return $value;
83
84
        });
85
86
        $curl = static::curl()
87
            ->$method($url, $data);
88
89
        $response = JSON::decode($curl->response);
90
91
        if (JSON::errorNone())
92
        {
93
            $curl->response = $response;
94
        }
95
96
        return $curl;
97
98
    }
99
100
}
101