Test Failed
Push — master ( 6cd0f3...dc4572 )
by Ryosuke
03:04
created

UploaderTrait::getProgressHandler()   D

Complexity

Conditions 9
Paths 1

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 30
ccs 17
cts 17
cp 1
rs 4.909
cc 9
eloc 19
nc 1
nop 5
crap 9
1
<?php
2
3
namespace mpyw\Cowitter\Traits;
4
5
use mpyw\Cowitter\HttpException;
6
use mpyw\Co\Co;
7
use mpyw\Co\CURLException;
8
use mpyw\Cowitter\ResponseInterface;
9
10
trait UploaderTrait
11
{
12
    abstract public function getAsync($endpoint, array $params = [], $return_response_object = false);
13
    abstract public function postAsync($endpoint, array $params = [], $return_response_object = false);
14
    abstract public function postMultipartAsync($endpoint, array $params = [], $return_response_object = false);
15 9
16 9
    protected static function validateChunkSize($value)
17 9
    {
18 1
        if (false === $value = filter_var($value, FILTER_VALIDATE_INT)) {
19
            throw new \InvalidArgumentException('Chunk size must be integer.');
20 8
        }
21 1
        if ($value < 10000) {
22
            throw new \LengthException('Chunk size must be no less than 10000 bytes.');
23 7
        }
24
        return $value;
25
    }
26 7
27 7
    protected static function getMimeType(\SplFileObject $file)
28 7
    {
29 7
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
30 7
        $type = $finfo->buffer($file->fread(1024));
31 7
        $file->rewind();
32
        return $type;
33
    }
34 9
35 9
    public function uploadAsync(\SplFileObject $file, $media_category = null, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
36 9
    {
37 7
        $response = (yield $this->uploadStep1($file, $media_category, $chunk_size, $on_uploading));
38 1
        if (!$response instanceof ResponseInterface) {
39
            yield Co::RETURN_WITH => $response;
40 6
        }
41
        if (!isset($response->getContent()->processing_info)) {
42
            yield Co::RETURN_WITH => $response->getContent();
43
        }
44
        yield Co::RETURN_WITH => (yield $this->uploadStep2($response, $on_processing));
45 9
        // @codeCoverageIgnoreStart
46 9
    }
47 9
    // @codeCoverageIgnoreEnd
48 7
49 7
    protected function uploadStep1(\SplFileObject $file, $media_category = null, $chunk_size = 300000, callable $on_uploading = null)
50 7
    {
51 7
        $chunk_size = static::validateChunkSize($chunk_size);
52 7
        $info = (yield $this->postAsync('media/upload', [
53
            'command' => 'INIT',
54 7
            'media_type' => static::getMimeType($file),
55 7
            'total_bytes' => $file->getSize(),
56 7
            'media_category' => $media_category,
57 7
        ]));
58 7
        try {
59 7
            yield $this->uploadBuffers($file, $info, $chunk_size, $on_uploading);
60 7
        } catch (CURLException $e) {
61
            if ($e->getCode() === CURLE_ABORTED_BY_CALLBACK) {
62
                return $info;
63 7
            }
64 7
            // @codeCoverageIgnoreStart
65 7
            throw $e;
66 7
            // @codeCoverageIgnoreEnd
67 7
        }
68
        yield Co::RETURN_WITH => (yield $this->postAsync('media/upload', [
69
            'command' => 'FINALIZE',
70
            'media_id' => $info->media_id_string,
71
        ], true));
72 6
        // @codeCoverageIgnoreStart
73 6
    }
74 6
    // @codeCoverageIgnoreEnd
75 6
76 6
    protected function uploadBuffers(\SplFileObject $file, \stdClass $info, $chunk_size, callable $on_uploading = null)
77 6
    {
78 4
        $tasks = [];
79 6
        $whole_uploaded = 0;
80
        $first = true;
81 6
        $canceled = false;
82 4
        for ($i = 0; '' !== $buffer = $file->fread($chunk_size); ++$i) {
83 2
            $client = $on_uploading ? $this->withOptions([
0 ignored issues
show
Bug introduced by
It seems like withOptions() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
84 2
                CURLOPT_NOPROGRESS => false,
85 2
                CURLOPT_PROGRESSFUNCTION => static::getProgressHandler($file, $on_uploading, $whole_uploaded, $first, $canceled),
86
            ]) : $this;
87 2
            $tasks[] = $client->postMultipartAsync('media/upload', [
88 2
                'command' => 'APPEND',
89 1
                'media_id' => $info->media_id_string,
90
                'segment_index' => $i,
91
                'media' => $buffer,
92 5
            ]);
93 4
        }
94 4
        yield $tasks;
95 4
    }
96 4
97 4
    protected static function getProgressHandler(\SplFileObject $file, callable $on_uploading, &$whole_uploaded, &$first, &$canceled)
98 4
    {
99 4
        // NOTE: File size doesn't include other parameters' size.
100
        //       It is calculated for approximate usage.
101
        return function ($ch, $dl_total, $dl_now, $up_total, $up_now) use ($file, $on_uploading, &$whole_uploaded, &$first, &$canceled) {
102 3
            static $previous_up_now = 0;
103 2
            if ($canceled) {
104 1
                return 1;
105 2
            }
106 2
            if ($dl_now !== 0 || ($up_now === $previous_up_now && !$first)) {
107
                return 0;
108 2
            }
109 2
            $whole_uploaded_percent_before = (int)(min(100, (int)(($whole_uploaded / $file->getSize()) * 100)) / 5) * 5;
110
            $whole_uploaded += $up_now - $previous_up_now;
111
            $previous_up_now = $up_now;
112
            $whole_uploaded_percent_after  = (int)(min(100, (int)(($whole_uploaded / $file->getSize()) * 100)) / 5) * 5;
113
            if ($whole_uploaded_percent_before === $whole_uploaded_percent_after && !$first) {
114 1
                return 0;
115
            }
116
            $first = false;
117
            if ((new \ReflectionFunction($on_uploading))->isGenerator()) {
118
                Co::async(function () use ($on_uploading, $whole_uploaded_percent_after, &$canceled) {
119 6
                    if (false === (yield $on_uploading($whole_uploaded_percent_after))) {
120 6
                        $canceled = true;
121 6
                    }
122
                });
123
            }
124 1
            return (int)(false === $on_uploading($whole_uploaded_percent_after));
125 1
        };
126 1
    }
127
128
    protected function uploadStep2(ResponseInterface $response, callable $on_processing = null)
129 1
    {
130 1
        $info = $response->getContent();
131 1
        $canceled = false;
132
        $previous_percent = 0;
133
        while ($info->processing_info->state === 'pending' || $info->processing_info->state === 'in_progress') {
134
            $percent = isset($info->processing_info->progress_percent)
135
                ? $info->processing_info->progress_percent
136
                : $previous_percent
137
            ;
138
            $previous_percent = $percent;
139
            if ($on_processing) {
140
                if ((new \ReflectionFunction($on_processing))->isGenerator()) {
141
                    Co::async(function () use ($on_processing, $percent, $response, &$canceled) {
142
                        if (false === (yield $on_processing($percent, $response))) {
143
                            $canceled = true;
144
                        }
145
                    });
146
                } elseif (false === $on_processing($percent, $response)) {
147
                    yield Co::RETURN_WITH => $info;
148
                }
149
            }
150
            if ($canceled) yield Co::RETURN_WITH => $info;
151
            yield Co::DELAY => $info->processing_info->check_after_secs;
152
            if ($canceled) yield Co::RETURN_WITH => $info;
153
            $response = (yield $this->getAsync('media/upload', [
154
                'command' => 'STATUS',
155
                'media_id' => $info->media_id_string,
156
            ], true));
157
            $info = $response->getContent();
158
        }
159
160
        if ($info->processing_info->state === 'failed') {
161
            $message = isset($info->processing_info->error->message)
162
                ? $info->processing_info->error->message
163
                : $info->processing_info->error->name;
164
            throw new HttpException(
165
                $message,
166
                $info->processing_info->error->code,
167
                $response->getHandle(),
168
                $response
169
            );
170
        }
171
172
        yield Co::RETURN_WITH => $info;
173
        // @codeCoverageIgnoreStart
174
    }
175
    // @codeCoverageIgnoreEnd
176
177
    public function uploadImageAsync(\SplFileObject $file, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
178
    {
179
        return $this->uploadAsync($file, 'tweet_image', $on_uploading, $on_processing, $chunk_size);
180
    }
181
182
    public function uploadAnimeGifAsync(\SplFileObject $file, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
183
    {
184
        return $this->uploadAsync($file, 'tweet_gif', $on_uploading, $on_processing, $chunk_size);
185
    }
186
187
    public function uploadVideoAsync(\SplFileObject $file, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
188
    {
189
        return $this->uploadAsync($file, 'tweet_video', $on_uploading, $on_processing, $chunk_size);
190
    }
191
}
192