Completed
Push — master ( a9cbe2...d61897 )
by Adrian
02:07
created

PhpHttp::execute()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 66
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 2
Metric Value
cc 6
eloc 49
c 3
b 0
f 2
nc 15
nop 2
dl 0
loc 66
rs 8.4905

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
namespace Manticoresearch\Transport;
5
6
use Http\Discovery\MessageFactoryDiscovery;
0 ignored issues
show
Bug introduced by
The type Http\Discovery\MessageFactoryDiscovery was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
8
use Manticoresearch\Connection;
9
use Manticoresearch\Exceptions\ConnectionException;
10
use Manticoresearch\Exceptions\ResponseException;
11
use Manticoresearch\Request;
12
use Manticoresearch\Response;
13
use Manticoresearch\Transport;
14
15
use Http\Discovery\HttpClientDiscovery;
0 ignored issues
show
Bug introduced by
The type Http\Discovery\HttpClientDiscovery was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Psr\Log\LoggerInterface;
17
18
/**
19
 * Class PhpHttp
20
 * @package Manticoresearch\Transport
21
 */
22
class PhpHttp extends Transport implements TransportInterface
23
{
24
    protected $client;
25
    protected $messageFactory;
26
    /**
27
     * PhpHttp constructor.
28
     * @param Connection|null $connection
29
     * @param LoggerInterface|null $logger
30
     */
31
32
    public function __construct(Connection $connection = null, LoggerInterface $logger = null)
33
    {
34
        $this->client = HttpClientDiscovery::find();
35
        $this->messageFactory = MessageFactoryDiscovery::find();
36
        parent::__construct($connection, $logger);
37
    }
38
39
    /**
40
     * @param Request $request
41
     * @param array $params
42
     * @return Response
43
     * @throws \Http\Client\Exception
44
     */
45
    public function execute(Request $request, $params=[])
46
    {
47
        $connection = $this->getConnection();
48
49
        $url = $this->_connection->getConfig('scheme') . '://' . $connection->getHost() . ':' . $connection->getPort();
50
        $endpoint = $request->getPath();
51
        $url .= $endpoint;
52
        $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

52
        $url = $this->setupURI($url, /** @scrutinizer ignore-type */ $request->getQuery());
Loading history...
53
        $method = $request->getMethod();
54
55
        $headers = $connection->getHeaders();
56
        $headers['Content-Type'] = $request->getContentType();
57
        $data = $request->getBody();
58
        if (!empty($data)) {
59
            if (is_array($data)) {
60
                $content = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
61
            } else {
62
                $content = $data;
63
            }
64
        } else {
65
            $content = '';
66
        }
67
        $start = microtime(true);
68
        $message = $this->messageFactory->createRequest($method, $url, $headers, $content);
69
        try {
70
            $responsePSR = $this->client->sendRequest($message);
71
        } catch (\Exception $e) {
72
            throw new ConnectionException($e->getMessage(), $request);
73
        }
74
        $end = microtime(true);
75
        $status = $responsePSR->getStatusCode();
76
        $responseString = $responsePSR->getBody();
77
78
        if (isset($params['responseClass'])) {
79
            $responseClass = $params['responseClass'];
80
            $response = new $responseClass($responseString, $status);
81
        } else {
82
            $response = new Response($responseString, $status);
83
        }
84
85
        $time = $end-$start;
86
        $response->setTime($time);
87
        $response->setTransportInfo([
88
            'url' => $url,
89
            'headers' => $headers,
90
            'body' => $request->getBody()
91
        ]);
92
        $this->_logger->debug('Request body:', [
93
            'connection' => $connection->getConfig(),
94
            'payload'=> $request->getBody()
95
        ]);
96
        $this->_logger->info(
97
            'Request:',
98
            [
99
                 'url' => $url,
100
                'status' => $status,
101
                'time' => $time
102
            ]
103
        );
104
        $this->_logger->debug('Response body:', $response->getResponse());
105
106
        if ($response->hasError()) {
107
            $this->_logger->error('Response error:', [$response->getError()]);
108
            throw new ResponseException($request, $response);
109
        }
110
        return $response;
111
    }
112
}
113