Completed
Push — master ( ac3329...5fe1c6 )
by Ryosuke
06:38 queued 45s
created

UploaderTrait::uploadAnimeGifAsync()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 4
crap 1
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
16 12
    protected static function validateChunkSize($value)
17 12
    {
18 12
        if (false === $value = filter_var($value, FILTER_VALIDATE_INT)) {
19 1
            throw new \InvalidArgumentException('Chunk size must be integer.');
20
        }
21 11
        if ($value < 10000) {
22 1
            throw new \LengthException('Chunk size must be no less than 10000 bytes.');
23
        }
24 10
        return $value;
25
    }
26
27 10
    protected static function getMimeType(\SplFileObject $file)
28 10
    {
29 10
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
30 10
        $type = $finfo->buffer($file->fread(1024));
31 10
        $file->rewind();
32 10
        return $type;
33
    }
34
35 12
    public function uploadAsync(\SplFileObject $file, $media_category = null, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
36 12
    {
37 12
        $response = (yield $this->uploadStep1($file, $media_category, $chunk_size, $on_uploading));
38 10
        if (!$response instanceof ResponseInterface) {
39 2
            yield Co::RETURN_WITH => $response;
40
        }
41 8
        if (!isset($response->getContent()->processing_info)) {
42 1
            yield Co::RETURN_WITH => $response->getContent();
43
        }
44 7
        yield Co::RETURN_WITH => (yield $this->uploadStep2($response, $on_processing));
45
        // @codeCoverageIgnoreStart
46
    }
47
    // @codeCoverageIgnoreEnd
48
49 12
    protected function uploadStep1(\SplFileObject $file, $media_category = null, $chunk_size = 300000, callable $on_uploading = null)
50 12
    {
51 12
        $chunk_size = static::validateChunkSize($chunk_size);
52 10
        $info = (yield $this->postAsync('media/upload', [
53 10
            'command' => 'INIT',
54 10
            'media_type' => static::getMimeType($file),
55 10
            'total_bytes' => $file->getSize(),
56 10
            'media_category' => $media_category,
57
        ]));
58
        try {
59 10
            yield $this->uploadBuffers($file, $info, $chunk_size, $on_uploading);
60 2
        } catch (CURLException $e) {
61 2
            if ($e->getCode() === CURLE_ABORTED_BY_CALLBACK) {
62 2
                return $info;
63
            }
64
            // @codeCoverageIgnoreStart
65
            throw $e;
66
            // @codeCoverageIgnoreEnd
67
        }
68 8
        yield Co::RETURN_WITH => (yield $this->postAsync('media/upload', [
69 8
            'command' => 'FINALIZE',
70 8
            'media_id' => $info->media_id_string,
71 8
        ], true));
72
        // @codeCoverageIgnoreStart
73
    }
74
    // @codeCoverageIgnoreEnd
75
76 10
    protected function uploadBuffers(\SplFileObject $file, \stdClass $info, $chunk_size, callable $on_uploading = null)
77 10
    {
78 10
        $tasks = [];
79 10
        $whole_uploaded = 0;
80 10
        $first = true;
81 10
        $canceled = false;
82 10
        for ($i = 0; '' !== $buffer = $file->fread($chunk_size); ++$i) {
83 10
            $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 3
                CURLOPT_NOPROGRESS => false,
85 3
                CURLOPT_PROGRESSFUNCTION => static::getProgressHandler($file, $on_uploading, $whole_uploaded, $first, $canceled),
86 10
            ]) : $this;
87 10
            $tasks[] = $client->postMultipartAsync('media/upload', [
88 10
                'command' => 'APPEND',
89 10
                'media_id' => $info->media_id_string,
90 10
                'segment_index' => $i,
91 10
                'media' => $buffer,
92
            ]);
93
        }
94 10
        yield $tasks;
95 8
    }
96
97 3
    protected static function getProgressHandler(\SplFileObject $file, callable $on_uploading, &$whole_uploaded, &$first, &$canceled)
98 3
    {
99
        // 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 3
            if ($canceled) {
104 1
                return 1;
105
            }
106 3
            if ($dl_now !== 0 || ($up_now === $previous_up_now && !$first)) {
107 2
                return 0;
108
            }
109 3
            $whole_uploaded_percent_before = (int)(min(100, (int)(($whole_uploaded / $file->getSize()) * 100)) / 5) * 5;
110 3
            $whole_uploaded += $up_now - $previous_up_now;
111 3
            $previous_up_now = $up_now;
112 3
            $whole_uploaded_percent_after  = (int)(min(100, (int)(($whole_uploaded / $file->getSize()) * 100)) / 5) * 5;
113 3
            if ($whole_uploaded_percent_before === $whole_uploaded_percent_after && !$first) {
114
                return 0;
115
            }
116 3
            $first = false;
117 3
            if ((new \ReflectionFunction($on_uploading))->isGenerator()) {
118
                Co::async(function () use ($on_uploading, $whole_uploaded_percent_after, &$canceled) {
119 1
                    if (false === (yield $on_uploading($whole_uploaded_percent_after))) {
120 1
                        $canceled = true;
121
                    }
122 1
                });
123
            }
124 3
            return (int)(false === $on_uploading($whole_uploaded_percent_after));
125 3
        };
126
    }
127
128 7
    protected function uploadStep2(ResponseInterface $response, callable $on_processing = null)
129 7
    {
130 7
        $info = $response->getContent();
131 7
        $canceled = false;
132 7
        $previous_percent = 0;
133 7
        while ($info->processing_info->state === 'pending' || $info->processing_info->state === 'in_progress') {
134 7
            $percent = isset($info->processing_info->progress_percent)
135 5
                ? $info->processing_info->progress_percent
136 7
                : $previous_percent
137
            ;
138 7
            $previous_percent = $percent;
139 7
            if ($on_processing) {
140 4
                if ((new \ReflectionFunction($on_processing))->isGenerator()) {
141 2
                    Co::async(function () use ($on_processing, $percent, $response, &$canceled) {
142 2
                        if (false === (yield $on_processing($percent, $response))) {
143 2
                            $canceled = true;
144
                        }
145 2
                    });
146 2
                } elseif (false === $on_processing($percent, $response)) {
147 1
                    yield Co::RETURN_WITH => $info;
148
                }
149
            }
150 6
            if ($canceled) yield Co::RETURN_WITH => $info;
151 5
            yield Co::DELAY => $info->processing_info->check_after_secs;
152 5
            if ($canceled) yield Co::RETURN_WITH => $info;
153 5
            $response = (yield $this->getAsync('media/upload', [
154 5
                'command' => 'STATUS',
155 5
                'media_id' => $info->media_id_string,
156 5
            ], true));
157 5
            $info = $response->getContent();
158
        }
159
160 4
        if ($info->processing_info->state === 'failed') {
161 2
            $message = isset($info->processing_info->error->message)
162 1
                ? $info->processing_info->error->message
163 2
                : $info->processing_info->error->name;
164 2
            throw new HttpException(
165
                $message,
166 2
                $info->processing_info->error->code,
167 2
                $response->getHandle(),
168
                $response
169
            );
170
        }
171
172 2
        yield Co::RETURN_WITH => $info;
173
        // @codeCoverageIgnoreStart
174
    }
175
    // @codeCoverageIgnoreEnd
176
177 9
    public function uploadImageAsync(\SplFileObject $file, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
178 9
    {
179 9
        return $this->uploadAsync($file, 'tweet_image', $on_uploading, $on_processing, $chunk_size);
180
    }
181
182 1
    public function uploadAnimeGifAsync(\SplFileObject $file, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
183 1
    {
184 1
        return $this->uploadAsync($file, 'tweet_gif', $on_uploading, $on_processing, $chunk_size);
185
    }
186
187 1
    public function uploadVideoAsync(\SplFileObject $file, callable $on_uploading = null, callable $on_processing = null, $chunk_size = 300000)
188 1
    {
189 1
        return $this->uploadAsync($file, 'tweet_video', $on_uploading, $on_processing, $chunk_size);
190
    }
191
}
192