Test Failed
Push — master ( d99c6b...fb4ca3 )
by Stiofan
15:44
created

Google_IO_Curl   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 152
Duplicated Lines 6.58 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 10
loc 152
rs 10
c 0
b 0
f 0
wmc 16
lcom 1
cbo 5

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 10 10 2
C executeRequest() 0 80 10
A setOptions() 0 4 1
A setTimeout() 0 9 1
A getTimeout() 0 4 1
A needsQuirk() 0 6 1

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
 * Copyright 2014 Google Inc.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/**
19
 * Curl based implementation of Google_IO.
20
 *
21
 * @author Stuart Langley <[email protected]>
22
 */
23
24
if (!class_exists('Google_Client')) {
25
  require_once dirname(__FILE__) . '/../autoload.php';
26
}
27
28
class Google_IO_Curl extends Google_IO_Abstract
29
{
30
  // cURL hex representation of version 7.30.0
31
  const NO_QUIRK_VERSION = 0x071E00;
32
33
  private $options = array();
34
35 View Code Duplication
  public function __construct(Google_Client $client)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
36
  {
37
    if (!extension_loaded('curl')) {
38
      $error = 'The cURL IO handler requires the cURL extension to be enabled';
39
      $client->getLogger()->critical($error);
40
      throw new Google_IO_Exception($error);
41
    }
42
43
    parent::__construct($client);
44
  }
45
46
  /**
47
   * Execute an HTTP Request
48
   *
49
   * @param Google_Http_Request $request the http request to be executed
50
   * @return array containing response headers, body, and http code
51
   * @throws Google_IO_Exception on curl or IO error
52
   */
53
  public function executeRequest(Google_Http_Request $request)
54
  {
55
    $curl = curl_init();
56
57
    if ($request->getPostBody()) {
58
      curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
59
    }
60
61
    $requestHeaders = $request->getRequestHeaders();
62
    if ($requestHeaders && is_array($requestHeaders)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $requestHeaders of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
63
      $curlHeaders = array();
64
      foreach ($requestHeaders as $k => $v) {
65
        $curlHeaders[] = "$k: $v";
66
      }
67
      curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
68
    }
69
    curl_setopt($curl, CURLOPT_URL, $request->getUrl());
70
71
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
72
    curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());
73
74
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
75
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
76
    // 1 is CURL_SSLVERSION_TLSv1, which is not always defined in PHP.
77
    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
78
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
79
    curl_setopt($curl, CURLOPT_HEADER, true);
80
81
    if ($request->canGzip()) {
82
      curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
83
    }
84
    
85
    $options = $this->client->getClassConfig('Google_IO_Curl', 'options');
86
    if (is_array($options)) {
87
      $this->setOptions($options);
88
    }
89
    
90
    foreach ($this->options as $key => $var) {
91
      curl_setopt($curl, $key, $var);
92
    }
93
94
    if (!isset($this->options[CURLOPT_CAINFO])) {
95
      curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
96
    }
97
98
    $this->client->getLogger()->debug(
99
        'cURL request',
100
        array(
101
            'url' => $request->getUrl(),
102
            'method' => $request->getRequestMethod(),
103
            'headers' => $requestHeaders,
104
            'body' => $request->getPostBody()
105
        )
106
    );
107
108
    $response = curl_exec($curl);
109
    if ($response === false) {
110
      $error = curl_error($curl);
111
      $code = curl_errno($curl);
112
      $map = $this->client->getClassConfig('Google_IO_Exception', 'retry_map');
113
114
      $this->client->getLogger()->error('cURL ' . $error);
115
      throw new Google_IO_Exception($error, $code, null, $map);
116
    }
117
    $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
118
119
    list($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
120
    $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
121
122
    $this->client->getLogger()->debug(
123
        'cURL response',
124
        array(
125
            'code' => $responseCode,
126
            'headers' => $responseHeaders,
127
            'body' => $responseBody,
128
        )
129
    );
130
131
    return array($responseBody, $responseHeaders, $responseCode);
132
  }
133
134
  /**
135
   * Set options that update the transport implementation's behavior.
136
   * @param $options
137
   */
138
  public function setOptions($options)
139
  {
140
    $this->options = $options + $this->options;
141
  }
142
143
  /**
144
   * Set the maximum request time in seconds.
145
   * @param $timeout in seconds
146
   */
147
  public function setTimeout($timeout)
148
  {
149
    // Since this timeout is really for putting a bound on the time
150
    // we'll set them both to the same. If you need to specify a longer
151
    // CURLOPT_TIMEOUT, or a higher CONNECTTIMEOUT, the best thing to
152
    // do is use the setOptions method for the values individually.
153
    $this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
154
    $this->options[CURLOPT_TIMEOUT] = $timeout;
155
  }
156
157
  /**
158
   * Get the maximum request time in seconds.
159
   * @return timeout in seconds
160
   */
161
  public function getTimeout()
162
  {
163
    return $this->options[CURLOPT_TIMEOUT];
164
  }
165
166
  /**
167
   * Test for the presence of a cURL header processing bug
168
   *
169
   * {@inheritDoc}
170
   *
171
   * @return boolean
172
   */
173
  protected function needsQuirk()
174
  {
175
    $ver = curl_version();
176
    $versionNum = $ver['version_number'];
177
    return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
178
  }
179
}
180