Completed
Pull Request — master (#131)
by Eric
63:39 queued 61:20
created

CurlHttpAdapter   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 192
Duplicated Lines 4.17 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 5.09%

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 10
dl 8
loc 192
ccs 5
cts 98
cp 0.0509
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getName() 0 4 1
A sendInternalRequest() 0 16 2
B sendInternalRequests() 0 39 6
D createCurl() 8 46 10
A configureTimeout() 0 8 2
A createResponse() 0 19 2
A resolveInternalRequest() 0 10 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the Ivory Http Adapter package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\HttpAdapter;
13
14
use Ivory\HttpAdapter\Extractor\ProtocolVersionExtractor;
15
use Ivory\HttpAdapter\Extractor\StatusCodeExtractor;
16
use Ivory\HttpAdapter\Message\InternalRequestInterface;
17
use Ivory\HttpAdapter\Message\RequestInterface;
18
use Ivory\HttpAdapter\Message\ResponseInterface;
19
use Ivory\HttpAdapter\Normalizer\BodyNormalizer;
20
use Ivory\HttpAdapter\Normalizer\HeadersNormalizer;
21
22
/**
23
 * @author GeLo <[email protected]>
24
 */
25
class CurlHttpAdapter extends AbstractCurlHttpAdapter
26
{
27
    /**
28
     * @param ConfigurationInterface|null $configuration
29
     */
30 17
    public function __construct(ConfigurationInterface $configuration = null)
31
    {
32 17
        parent::__construct($configuration);
33 16
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 1
    public function getName()
39
    {
40 1
        return 'curl';
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    protected function sendInternalRequest(InternalRequestInterface $internalRequest)
47
    {
48
        $curl = $this->createCurl($internalRequest);
49
50
        try {
51
            $response = $this->createResponse($curl, curl_exec($curl), $internalRequest);
52
        } catch (HttpAdapterException $e) {
53
            curl_close($curl);
54
55
            throw $e;
56
        }
57
58
        curl_close($curl);
59
60
        return $response;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function sendInternalRequests(array $internalRequests, $success, $error)
67
    {
68
        $curlMulti = curl_multi_init();
69
70
        $contexts = [];
71
        foreach ($internalRequests as $internalRequest) {
72
            $contexts[] = [
73
                'curl'    => $curl = $this->createCurl($internalRequest),
74
                'request' => $internalRequest,
75
            ];
76
77
            curl_multi_add_handle($curlMulti, $curl);
78
        }
79
80
        do {
81
            do {
82
                $exec = curl_multi_exec($curlMulti, $running);
83
            } while ($exec === CURLM_CALL_MULTI_PERFORM);
84
85
            while ($done = curl_multi_info_read($curlMulti)) {
86
                $curl = $done['handle'];
87
                $internalRequest = $this->resolveInternalRequest($curl, $contexts);
88
89
                try {
90
                    $response = $this->createResponse($curl, curl_multi_getcontent($curl), $internalRequest);
91
                    $response = $response->withParameter('request', $internalRequest);
92
                    call_user_func($success, $response);
93
                } catch (HttpAdapterException $e) {
94
                    $e->setRequest($internalRequest);
95
                    call_user_func($error, $e);
96
                }
97
98
                curl_multi_remove_handle($curlMulti, $curl);
99
                curl_close($curl);
100
            }
101
        } while ($running);
102
103
        curl_multi_close($curlMulti);
104
    }
105
106
    /**
107
     * @param InternalRequestInterface $internalRequest
108
     *
109
     * @return resource
110
     */
111
    private function createCurl(InternalRequestInterface $internalRequest)
112
    {
113
        $curl = curl_init();
114
115
        curl_setopt($curl, CURLOPT_URL, (string) $internalRequest->getUri());
116
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
117
        curl_setopt($curl, CURLOPT_HTTP_VERSION, $this->prepareProtocolVersion($internalRequest));
118
        curl_setopt($curl, CURLOPT_HEADER, true);
119
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
120
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->prepareHeaders($internalRequest, false, false));
121
122
        $this->configureTimeout($curl, 'CURLOPT_TIMEOUT');
123
        $this->configureTimeout($curl, 'CURLOPT_CONNECTTIMEOUT');
124
125
        $files = $internalRequest->getFiles();
126
127
        if (!empty($files) && $this->isSafeUpload()) {
128
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
129
        }
130
131
        switch ($internalRequest->getMethod()) {
132
            case RequestInterface::METHOD_HEAD:
133
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $internalRequest->getMethod());
134
                curl_setopt($curl, CURLOPT_NOBODY, true);
135
                break;
136
137
            case RequestInterface::METHOD_TRACE:
138
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $internalRequest->getMethod());
139
                break;
140
141 View Code Duplication
            case RequestInterface::METHOD_POST:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
142
                curl_setopt($curl, CURLOPT_POST, true);
143
                curl_setopt($curl, CURLOPT_POSTFIELDS, $this->prepareContent($internalRequest));
144
                break;
145
146
            case RequestInterface::METHOD_PUT:
147
            case RequestInterface::METHOD_PATCH:
148
            case RequestInterface::METHOD_DELETE:
149 View Code Duplication
            case RequestInterface::METHOD_OPTIONS:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $internalRequest->getMethod());
151
                curl_setopt($curl, CURLOPT_POSTFIELDS, $this->prepareContent($internalRequest));
152
                break;
153
        }
154
155
        return $curl;
156
    }
157
158
    /**
159
     * @param resource $curl
160
     * @param string   $type
161
     */
162
    private function configureTimeout($curl, $type)
163
    {
164
        if (defined($type.'_MS')) {
165
            curl_setopt($curl, constant($type.'_MS'), $this->getConfiguration()->getTimeout() * 1000);
166
        } else { // @codeCoverageIgnoreStart
167
            curl_setopt($curl, constant($type), $this->getConfiguration()->getTimeout());
168
        } // @codeCoverageIgnoreEnd
169
    }
170
171
    /**
172
     * @param resource                 $curl
173
     * @param string|bool|null         $data
174
     * @param InternalRequestInterface $internalRequest
175
     *
176
     * @throws HttpAdapterException
177
     *
178
     * @return ResponseInterface
179
     */
180
    private function createResponse($curl, $data, InternalRequestInterface $internalRequest)
181
    {
182
        if (empty($data)) {
183
            throw HttpAdapterException::cannotFetchUri(
184
                (string) $internalRequest->getUri(),
185
                $this->getName(),
186
                curl_error($curl)
187
            );
188
        }
189
190
        $headers = substr($data, 0, $headersSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE));
191
192
        return $this->getConfiguration()->getMessageFactory()->createResponse(
193
            StatusCodeExtractor::extract($headers),
194
            ProtocolVersionExtractor::extract($headers),
195
            HeadersNormalizer::normalize($headers),
196
            BodyNormalizer::normalize(substr($data, $headersSize), $internalRequest->getMethod())
197
        );
198
    }
199
200
    /**
201
     * @param resource $curl
202
     * @param array    $contexts
203
     *
204
     * @return InternalRequestInterface
205
     */
206
    private function resolveInternalRequest($curl, array $contexts)
207
    {
208
        foreach ($contexts as $context) {
209
            if ($context['curl'] === $curl) {
210
                break;
211
            }
212
        }
213
214
        return $context['request'];
0 ignored issues
show
Bug introduced by
The variable $context seems to be defined by a foreach iteration on line 208. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
215
    }
216
}
217