Passed
Push — master ( 15347e...e929c7 )
by
unknown
02:05
created

Http   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 123
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 79
c 3
b 0
f 0
dl 0
loc 123
rs 10
wmc 16

2 Methods

Rating   Name   Duplication   Size   Complexity  
F execute() 0 100 13
A getCurlConnection() 0 6 3
1
<?php
2
3
namespace Manticoresearch\Transport;
4
5
use Manticoresearch\Exceptions\ConnectionException;
6
use Manticoresearch\Exceptions\ResponseException;
7
use Manticoresearch\Request;
8
use Manticoresearch\Response;
9
10
/**
11
 * Class Http
12
 * @package Manticoresearch\Transport
13
 */
14
class Http extends \Manticoresearch\Transport implements TransportInterface
15
{
16
17
    /**
18
     * @var string
19
     */
20
    protected $scheme = 'http';
21
22
    protected static $curl = null;
23
24
    /**
25
     * @param Request $request
26
     * @param array $params
27
     * @return Response
28
     */
29
    public function execute(Request $request, $params = [])
30
    {
31
        $connection = $this->getConnection();
32
        $conn = $this->getCurlConnection($connection->getConfig('persistent'));
0 ignored issues
show
Bug introduced by
It seems like $connection->getConfig('persistent') can also be of type null; however, parameter $persistent of Manticoresearch\Transpor...tp::getCurlConnection() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

32
        $conn = $this->getCurlConnection(/** @scrutinizer ignore-type */ $connection->getConfig('persistent'));
Loading history...
33
        $url = $this->scheme.'://'.$connection->getHost().':'.$connection->getPort();
34
        $endpoint = $request->getPath();
35
        $url .= $endpoint;
36
        $url = $this->setupURI($url, $request->getQuery());
0 ignored issues
show
Bug introduced by
$request->getQuery() of type string is incompatible with the type array expected by parameter $query of Manticoresearch\Transport::setupURI(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

36
        $url = $this->setupURI($url, /** @scrutinizer ignore-type */ $request->getQuery());
Loading history...
37
38
        curl_setopt($conn, CURLOPT_URL, $url);
39
        curl_setopt($conn, CURLOPT_TIMEOUT, $connection->getTimeout());
40
        curl_setopt($conn, CURLOPT_ENCODING, '');
41
        curl_setopt($conn, CURLOPT_FORBID_REUSE, 0);
42
        $data = $request->getBody();
43
        $method = $request->getMethod();
44
        $headers = $connection->getHeaders();
45
        $headers[] = sprintf('Content-Type: %s', $request->getContentType());
46
        if (!empty($data)) {
47
            if (is_array($data)) {
48
                $content = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
49
            } else {
50
                $content = $data;
51
            }
52
            curl_setopt($conn, CURLOPT_POSTFIELDS, $content);
53
        } else {
54
            curl_setopt($conn, CURLOPT_POSTFIELDS, '');
55
        }
56
        curl_setopt($conn, CURLOPT_CUSTOMREQUEST, $method);
57
        curl_setopt($conn, CURLOPT_HTTPHEADER, $headers);
58
59
        if ($connection->getConnectTimeout()>0) {
60
            curl_setopt($conn, CURLOPT_CONNECTTIMEOUT, $connection->getConnectTimeout());
61
        }
62
63
        if ($connection->getConfig('username') !== null && $connection->getConfig('password') !== null) {
64
            curl_setopt($conn, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
65
            curl_setopt(
66
                $conn,
67
                CURLOPT_USERPWD,
68
                $connection->getConfig('username').":".$connection->getConfig('password')
69
            );
70
        }
71
        if ($connection->getConfig('proxy') !== null) {
72
            curl_setopt($conn, CURLOPT_PROXY, $connection->getConfig('proxy'));
73
        }
74
        if (!empty($connection->getConfig('curl'))) {
75
            foreach ($connection->getConfig('curl') as $k => $v) {
76
                curl_setopt($conn, $k, $v);
77
            }
78
        }
79
        $start = microtime(true);
80
        ob_start();
81
        curl_exec($conn);
82
        $responseString = \ob_get_clean();
83
        $end = microtime(true);
84
        $errorno = curl_errno($conn);
85
        $status = curl_getinfo($conn, CURLINFO_HTTP_CODE);
86
        if (isset($params['responseClass'])) {
87
            $responseClass = $params['responseClass'];
88
            $responseClassParams = isset($params['responseClassParams'])?$params['responseClassParams']:[];
89
            $response = new $responseClass($responseString, $status, $responseClassParams);
90
        } else {
91
            $response = new Response($responseString, $status);
92
        }
93
94
        $time = $end-$start;
95
        $response->setTime($time);
96
        $response->setTransportInfo([
97
                'url' => $url,
98
                'headers' => $headers,
99
                'body' => $request->getBody()
100
            ]);
101
        //hard error
102
        if ($errorno>0) {
103
            $error = curl_error($conn);
104
105
            self::$curl = null;
106
            throw new ConnectionException($error, $request);
107
        }
108
109
110
        $this->logger->debug('Request body:', [
111
                'connection' => $connection->getConfig(),
112
                'payload'=> $request->getBody()
113
            ]);
114
        $this->logger->info(
115
            'Request:',
116
            [
117
                    'url' => $url,
118
                    'status' => $status,
119
                    'time' => $time
120
                ]
121
        );
122
        $this->logger->debug('Response body:', [json_decode($responseString, true)]);
123
        //soft error
124
        if ($response->hasError()) {
125
            $this->logger->error('Response error:', [$response->getError()]);
126
            throw new ResponseException($request, $response);
127
        }
128
        return $response;
129
    }
130
131
    protected function getCurlConnection(bool $persistent = true)
132
    {
133
        if (!$persistent || !self::$curl) {
134
            self::$curl = curl_init();
135
        }
136
        return self::$curl;
137
    }
138
}
139