Passed
Push — master ( e9d799...86a7f0 )
by Бабичев
03:26 queued 01:52
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 $urlOrOptions
53
     * @param array        $data
54
     *
55
     * @return Curl
56
     *
57
     * @throws Exceptions\Invalid
58
     */
59
    public static function upload($urlOrOptions, array $data = []): Curl
60
    {
61
62
        $options = $urlOrOptions;
63
64
        if (is_string($options))
65
        {
66
            $options = ['url' => $urlOrOptions];
67
        }
68
69
        if (!isset($options['url']))
70
        {
71
            throw new Exceptions\Invalid('Param option `URL` not found!');
72
        }
73
74
        $url    = $options['url'];
75
        $method = $options['method'] ?? 'post';
76
77
        $data = Arr::map($data, function ($value) {
78
79
            if (\is_string($value) && Str::sub($value, 0, 1) === '@')
80
            {
81
                return curl_file_create(Str::sub($value, 1));
82
            }
83
84
            return $value;
85
86
        });
87
88
        $curl = static::curl()
89
            ->$method($url, $data);
90
91
        $response = JSON::decode($curl->response);
92
93
        if (JSON::errorNone())
94
        {
95
            $curl->response = $response;
96
        }
97
98
        return $curl;
99
100
    }
101
102
}
103