Completed
Push — master ( b654b1...24c64a )
by Hiraku
04:07 queued 01:25
created

BaseRequest::getCurlOptions()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6.1666

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 32
ccs 15
cts 18
cp 0.8333
rs 8.439
cc 6
eloc 19
nc 32
nop 0
crap 6.1666
1
<?php
2
namespace Hirak\Prestissimo;
3
4
use Composer\Util;
5
use Composer\IO;
6
7
class BaseRequest
8
{
9
    private $scheme;
10
    private $user;
11
    private $pass;
12
    private $host;
13
    private $port;
14
    private $path;
15
    private $query = array();
16
17
    /** @var [string => string] */
18
    private $headers = array();
19
20
    private $capath;
21
    private $cafile;
22
23
    protected static $defaultCurlOptions = array();
24
25
    private static $NSS_CIPHERS = array(
26
        'rsa_3des_sha',
27
        'rsa_des_sha',
28
        'rsa_null_md5',
29
        'rsa_null_sha',
30
        'rsa_rc2_40_md5',
31
        'rsa_rc4_128_md5',
32
        'rsa_rc4_128_sha',
33
        'rsa_rc4_40_md5',
34
        'fips_des_sha',
35
        'fips_3des_sha',
36
        'rsa_des_56_sha',
37
        'rsa_rc4_56_sha',
38
        'rsa_aes_128_sha',
39
        'rsa_aes_256_sha',
40
        'rsa_aes_128_gcm_sha_256',
41
        'dhe_rsa_aes_128_gcm_sha_256',
42
        'ecdh_ecdsa_null_sha',
43
        'ecdh_ecdsa_rc4_128_sha',
44
        'ecdh_ecdsa_3des_sha',
45
        'ecdh_ecdsa_aes_128_sha',
46
        'ecdh_ecdsa_aes_256_sha',
47
        'ecdhe_ecdsa_null_sha',
48
        'ecdhe_ecdsa_rc4_128_sha',
49
        'ecdhe_ecdsa_3des_sha',
50
        'ecdhe_ecdsa_aes_128_sha',
51
        'ecdhe_ecdsa_aes_256_sha',
52
        'ecdh_rsa_null_sha',
53
        'ecdh_rsa_128_sha',
54
        'ecdh_rsa_3des_sha',
55
        'ecdh_rsa_aes_128_sha',
56
        'ecdh_rsa_aes_256_sha',
57
        'echde_rsa_null',
58
        'ecdhe_rsa_rc4_128_sha',
59
        'ecdhe_rsa_3des_sha',
60
        'ecdhe_rsa_aes_128_sha',
61
        'ecdhe_rsa_aes_256_sha',
62
        'ecdhe_ecdsa_aes_128_gcm_sha_256',
63
        'ecdhe_rsa_aes_128_gcm_sha_256',
64
    );
65
66
    /**
67
     * enable ECC cipher suites in cURL/NSS
68
     * @codeCoverageIgnore
69
     */
70
    public static function nssCiphers()
71
    {
72
        static $cache;
73
        if (isset($cache)) {
74
            return $cache;
75
        }
76
        $ver = curl_version();
77
        if (preg_match('/^NSS.*Basic ECC$/', $ver['ssl_version'])) {
78
            return $cache = implode(',', self::$NSS_CIPHERS);
79
        }
80
        return $cache = false;
81
    }
82
83 2
    protected function getProxy($url)
0 ignored issues
show
Coding Style introduced by
getProxy uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
84
    {
85 2
        if (isset($_SERVER['no_proxy'])) {
86 1
            $pattern = new Util\NoProxyPattern($_SERVER['no_proxy']);
87 1
            if ($pattern->test($url)) {
88 1
                return null;
89
            }
90
        }
91
92 2 View Code Duplication
        if ($this->scheme === 'https') {
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...
93 1
            if (isset($_SERVER['HTTPS_PROXY'])) {
94
                return $_SERVER['HTTPS_PROXY'];
95
            }
96 1
            if (isset($_SERVER['https_proxy'])) {
97
                return $_SERVER['https_proxy'];
98
            }
99
        }
100
101 2 View Code Duplication
        if ($this->scheme === 'http') {
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...
102 1
            if (isset($_SERVER['HTTP_PROXY'])) {
103 1
                return $_SERVER['HTTP_PROXY'];
104
            }
105
            if (isset($_SERVER['http_proxy'])) {
106
                return $_SERVER['http_proxy'];
107
            }
108
        }
109 1
        return null;
110
    }
111
112
    /**
113
     * @param $io
114
     * @param bool $useRedirector
115
     * @param $githubDomains
116
     * @param $gitlabDomains
117
     */
118 6
    protected function setupAuthentication(IO\IOInterface $io, $useRedirector, array $githubDomains, array $gitlabDomains)
119
    {
120 6
        if (preg_match('/\.github\.com$/', $this->host)) {
121 1
            $authKey = 'github.com';
122 1
            if ($useRedirector) {
123 1
                if ($this->host === 'api.github.com' && preg_match('%^/repos(/[^/]+/[^/]+/)zipball(.+)$%', $this->path, $_)) {
124 1
                    $this->host = 'codeload.github.com';
125 1
                    $this->path = $_[1] . 'legacy.zip' . $_[2];
126
                }
127
            }
128
        } else {
129 5
            $authKey = $this->host;
130
        }
131 6
        if (!$io->hasAuthentication($authKey)) {
132 4
            if ($this->user || $this->pass) {
133 2
                $io->setAuthentication($authKey, $this->user, $this->pass);
134
            } else {
135 2
                return;
136
            }
137
        }
138
139 4
        $auth = $io->getAuthentication($authKey);
140
141
        // is github
142 4
        if (in_array($authKey, $githubDomains) && 'x-oauth-basic' === $auth['password']) {
143 1
            $this->addParam('access_token', $auth['username']);
144 1
            $this->user = $this->pass = null;
145 1
            return;
146
        }
147
        // is gitlab
148 3
        if (in_array($authKey, $gitlabDomains) && 'oauth2' === $auth['password']) {
149 1
            $this->addHeader('authorization', 'Bearer ' . $auth['username']);
150 1
            $this->user = $this->pass = null;
151 1
            return;
152
        }
153
        // others, includes bitbucket
154 2
        $this->user = $auth['username'];
155 2
        $this->pass = $auth['password'];
156 2
    }
157
158
    /**
159
     * @return array
160
     */
161 2
    public function getCurlOptions()
162
    {
163 2
        $headers = array();
164 2
        foreach ($this->headers as $key => $val) {
165 1
            $headers[] = strtr(ucwords(strtr($key, '-', ' ')), ' ', '-') . ': ' . $val;
166
        }
167
168 2
        $url = $this->getURL();
169
170
        $curlOpts = array(
171 2
            CURLOPT_URL => $url,
172 2
            CURLOPT_HTTPHEADER => $headers,
173 2
            CURLOPT_USERAGENT => ConfigFacade::getUserAgent(),
174
            //CURLOPT_VERBOSE => true, //for debug
175
        );
176 2
        $curlOpts += static::$defaultCurlOptions;
177
178 2
        if ($ciphers = $this->nssCiphers()) {
179
            $curlOpts[CURLOPT_SSL_CIPHER_LIST] = $ciphers;
180
        }
181 2
        if ($proxy = $this->getProxy($url)) {
182 1
            $curlOpts[CURLOPT_PROXY] = $proxy;
183
        }
184 2
        if ($this->capath) {
185
            $curlOpts[CURLOPT_CAPATH] = $this->capath;
186
        }
187 2
        if ($this->cafile) {
188
            $curlOpts[CURLOPT_CAINFO] = $this->cafile;
189
        }
190
191 2
        return $curlOpts;
192
    }
193
194
    /**
195
     * @return string
196
     */
197 4
    public function getURL()
198
    {
199 4
        $url = self::ifOr($this->scheme, '', '://');
200 4
        if ($this->user) {
201 1
            $user = $this->user;
202 1
            $user .= self::ifOr($this->pass, ':');
203 1
            $url .= $user . '@';
204
        }
205 4
        $url .= self::ifOr($this->host);
206 4
        $url .= self::ifOr($this->port, ':');
207 4
        $url .= self::ifOr($this->path);
208 4
        $url .= self::ifOr(http_build_query($this->query), '?');
209 4
        return $url;
210
    }
211
212
    /**
213
     * @return string user/pass/access_token masked url
214
     */
215 1 View Code Duplication
    public function getMaskedURL()
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...
216
    {
217 1
        $url = self::ifOr($this->scheme, '', '://');
218 1
        $url .= self::ifOr($this->host);
219 1
        $url .= self::ifOr($this->port, ':');
220 1
        $url .= self::ifOr($this->path);
221 1
        return $url;
222
    }
223
224
    /**
225
     * @return string
226
     */
227 View Code Duplication
    public function getOriginURL()
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...
228
    {
229
        $url = self::ifOr($this->scheme, '', '://');
230
        $url .= self::ifOr($this->host);
231
        $url .= self::ifOr($this->port, ':');
232
        return $url;
233
    }
234
235 5
    private static function ifOr($str, $pre = '', $post = '')
236
    {
237 5
        if ($str) {
238 5
            return $pre . $str . $post;
239
        }
240 4
        return '';
241
    }
242
243
    /**
244
     * @param string $url
245
     */
246 7
    public function setURL($url)
247
    {
248 7
        $struct = parse_url($url);
249 7
        foreach ($struct as $key => $val) {
0 ignored issues
show
Bug introduced by
The expression $struct of type array<string,string>|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
250 7
            if ($key === 'query') {
251 3
                parse_str($val, $this->query);
252
            } else {
253 7
                $this->$key = $val;
254
            }
255
        }
256 7
    }
257
258 1
    public function addParam($key, $val)
259
    {
260 1
        $this->query[$key] = $val;
261 1
    }
262
263 1
    public function addHeader($key, $val)
264
    {
265 1
        $this->headers[strtolower($key)] = $val;
266 1
    }
267
268 6
    public function setCA($path = null, $file = null)
269
    {
270 6
        $this->capath = $path;
271 6
        $this->cafile = $file;
272 6
    }
273
}
274