Completed
Push — master ( 360314...c2aa1e )
by Ryosuke
08:47
created

ResponseYielder::syncExec()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.9683

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 8
cts 14
cp 0.5714
rs 8.8571
cc 5
eloc 13
nc 3
nop 1
crap 6.9683
1
<?php
2
3
namespace mpyw\Cowitter\Helpers;
4
5
use mpyw\Co\CURLException;
6
use mpyw\Co\CoInterface;
7
use mpyw\Cowitter\Response;
8
use mpyw\Cowitter\Helpers\ResponseBodyDecoder;
9
10
class ResponseYielder
11
{
12 3
    public static function syncExec($ch)
13 3
    {
14 3
        if (false === $buffer = curl_exec($ch)) {
15
            throw new CURLException(curl_error($ch), curl_errno($ch), $ch);
16
        }
17 3
        $response = new Response($buffer, $ch);
18 3
        if ($response->getStatusCode() >= 300 &&
19 3
            $response->getStatusCode() < 400 &&
20 3
            '' !== $url = $response->getHeaderLine('Location')) {
21
            curl_setopt_array($ch, [
22
                CURLOPT_URL => $url,
23
                CURLOPT_HTTPGET => true,
24
                CURLOPT_REFERER => curl_getinfo($ch, CURLINFO_EFFECTIVE_URL),
25
            ]);
26
            return static::syncExec($ch);
27
        }
28 3
        return $response;
29
    }
30
31 3
    public static function asyncExec($ch)
32 3
    {
33 3
        $response = new Response((yield $ch), $ch);
34 3
        if ($response->getStatusCode() >= 300 &&
35 3
            $response->getStatusCode() < 400 &&
36 3
            '' !== $url = $response->getHeaderLine('Location')) {
37
            curl_setopt_array($ch, [
38
                CURLOPT_URL => $url,
39
                CURLOPT_HTTPGET => true,
40
                CURLOPT_REFERER => curl_getinfo($ch, CURLINFO_EFFECTIVE_URL),
41
            ]);
42
            yield CoInterface::RETURN_WITH => static::syncExec($ch);
43
        }
44 3
        yield CoInterface::RETURN_WITH => $response;
45
    }
46
47 3
    public static function syncExecDecoded($ch, $return_response_object = false)
48 3
    {
49 3
        $response = static::syncExec($ch);
50 3
        $response = ResponseBodyDecoder::getDecodedResponse($response, $ch);
51 3
        if (!$return_response_object) {
52 3
            $response = $response->hasContent() ? $response->getContent() : null;
53
        }
54 3
        return $response;
55
    }
56
57 3
    public static function asyncExecDecoded($ch, $return_response_object = false)
58 3
    {
59 3
        $response = (yield static::asyncExec($ch));
60 3
        $response = ResponseBodyDecoder::getDecodedResponse($response, $ch);
61 3
        if (!$return_response_object) {
62 3
            $response = $response->hasContent() ? $response->getContent() : null;
63
        }
64 3
        yield CoInterface::RETURN_WITH => $response;
65
    }
66
}
67