Passed
Push — master ( e9d799...86a7f0 )
by Бабичев
03:26 queued 01:52
created

Stream   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Test Coverage

Coverage 34.78%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
c 1
b 0
f 0
lcom 0
cbo 8
dl 0
loc 94
ccs 8
cts 23
cp 0.3478
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A curl() 0 4 1
A download() 0 21 4
B upload() 0 42 6
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