Completed
Push — master ( 49e50d...b85d88 )
by Hiraku
9s
created

BaseRequest::isHTTP()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 2
eloc 2
nc 2
nop 0
crap 2
1
<?php
2
/*
3
 * hirak/prestissimo
4
 * @author Hiraku NAKANO
5
 * @license MIT https://github.com/hirak/prestissimo
6
 */
7
namespace Hirak\Prestissimo;
8
9
use Composer\Util;
10
use Composer\IO;
11
12
class BaseRequest
13
{
14
    private $scheme;
15
    private $user;
16
    private $pass;
17
    private $host;
18
    private $port;
19
    private $path;
20
    private $query = array();
21
22
    /** @var [string => string] */
23
    private $headers = array();
24
25
    private $capath;
26
    private $cafile;
27
28
    protected static $defaultCurlOptions = array();
29
30
    private static $NSS_CIPHERS = array(
31
        'rsa_3des_sha',
32
        'rsa_des_sha',
33
        'rsa_null_md5',
34
        'rsa_null_sha',
35
        'rsa_rc2_40_md5',
36
        'rsa_rc4_128_md5',
37
        'rsa_rc4_128_sha',
38
        'rsa_rc4_40_md5',
39
        'fips_des_sha',
40
        'fips_3des_sha',
41
        'rsa_des_56_sha',
42
        'rsa_rc4_56_sha',
43
        'rsa_aes_128_sha',
44
        'rsa_aes_256_sha',
45
        'rsa_aes_128_gcm_sha_256',
46
        'dhe_rsa_aes_128_gcm_sha_256',
47
        'ecdh_ecdsa_null_sha',
48
        'ecdh_ecdsa_rc4_128_sha',
49
        'ecdh_ecdsa_3des_sha',
50
        'ecdh_ecdsa_aes_128_sha',
51
        'ecdh_ecdsa_aes_256_sha',
52
        'ecdhe_ecdsa_null_sha',
53
        'ecdhe_ecdsa_rc4_128_sha',
54
        'ecdhe_ecdsa_3des_sha',
55
        'ecdhe_ecdsa_aes_128_sha',
56
        'ecdhe_ecdsa_aes_256_sha',
57
        'ecdh_rsa_null_sha',
58
        'ecdh_rsa_128_sha',
59
        'ecdh_rsa_3des_sha',
60
        'ecdh_rsa_aes_128_sha',
61
        'ecdh_rsa_aes_256_sha',
62
        'echde_rsa_null',
63
        'ecdhe_rsa_rc4_128_sha',
64
        'ecdhe_rsa_3des_sha',
65
        'ecdhe_rsa_aes_128_sha',
66
        'ecdhe_rsa_aes_256_sha',
67
        'ecdhe_ecdsa_aes_128_gcm_sha_256',
68
        'ecdhe_rsa_aes_128_gcm_sha_256',
69
    );
70
71
    /**
72
     * enable ECC cipher suites in cURL/NSS
73
     * @codeCoverageIgnore
74
     */
75
    public static function nssCiphers()
76
    {
77
        static $cache;
78
        if (isset($cache)) {
79
            return $cache;
80
        }
81
        $ver = curl_version();
82
        if (preg_match('/^NSS.*Basic ECC$/', $ver['ssl_version'])) {
83
            return $cache = implode(',', self::$NSS_CIPHERS);
84
        }
85
        return $cache = false;
86
    }
87
88 4
    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...
89
    {
90 4
        if (isset($_SERVER['no_proxy'])) {
91 1
            $pattern = new Util\NoProxyPattern($_SERVER['no_proxy']);
92 1
            if ($pattern->test($url)) {
93 1
                return null;
94
            }
95 1
        }
96
97 4
        foreach (array('https', 'http') as $scheme) {
98 4
            if ($this->scheme === $scheme) {
99 4
                $label = $scheme . '_proxy';
100 4
                foreach (array(strtoupper($label), $label) as $l) {
101 4
                    if (isset($_SERVER[$l])) {
102 1
                        return $_SERVER[$l];
103
                    }
104 3
                }
105 3
            }
106 4
        }
107 3
        return null;
108
    }
109
110
    /**
111
     * @param $io
112
     * @param bool $useRedirector
113
     * @param $githubDomains
114
     * @param $gitlabDomains
115
     */
116 6
    protected function setupAuthentication(IO\IOInterface $io, $useRedirector, array $githubDomains, array $gitlabDomains)
117
    {
118 6
        if (preg_match('/\.github\.com$/', $this->host)) {
119 1
            $authKey = 'github.com';
120 1
            if ($useRedirector) {
121 1
                if ($this->host === 'api.github.com' && preg_match('%^/repos(/[^/]+/[^/]+/)zipball(.+)$%', $this->path, $_)) {
122 1
                    $this->host = 'codeload.github.com';
123 1
                    $this->path = $_[1] . 'legacy.zip' . $_[2];
124 1
                }
125 1
            }
126 1
        } else {
127 5
            $authKey = $this->host;
128
        }
129 6
        if (!$io->hasAuthentication($authKey)) {
130 4
            if ($this->user || $this->pass) {
131 1
                $io->setAuthentication($authKey, $this->user, $this->pass);
132 1
            } else {
133 3
                return;
134
            }
135 1
        }
136
137 3
        $auth = $io->getAuthentication($authKey);
138
139
        // is github
140 3
        if (in_array($authKey, $githubDomains) && 'x-oauth-basic' === $auth['password']) {
141 1
            $this->addParam('access_token', $auth['username']);
142 1
            $this->user = $this->pass = null;
143 1
            return;
144
        }
145
        // is gitlab
146 2
        if (in_array($authKey, $gitlabDomains) && 'oauth2' === $auth['password']) {
147 1
            $this->addHeader('authorization', 'Bearer ' . $auth['username']);
148 1
            $this->user = $this->pass = null;
149 1
            return;
150
        }
151
        // others, includes bitbucket
152 1
        $this->user = $auth['username'];
153 1
        $this->pass = $auth['password'];
154 1
    }
155
156
    /**
157
     * @return array
158
     */
159 4
    public function getCurlOptions()
160
    {
161 4
        $headers = array();
162 4
        foreach ($this->headers as $key => $val) {
163 1
            $headers[] = strtr(ucwords(strtr($key, '-', ' ')), ' ', '-') . ': ' . $val;
164 4
        }
165
166 4
        $url = $this->getURL();
167
168
        $curlOpts = array(
169 4
            CURLOPT_URL => $url,
170 4
            CURLOPT_HTTPHEADER => $headers,
171 4
            CURLOPT_USERAGENT => ConfigFacade::getUserAgent(),
172
            //CURLOPT_VERBOSE => true, //for debug
173 4
        );
174 4
        $curlOpts += static::$defaultCurlOptions;
175
176
        // @codeCoverageIgnoreStart
177
        if ($ciphers = $this->nssCiphers()) {
178
            $curlOpts[CURLOPT_SSL_CIPHER_LIST] = $ciphers;
179
        }
180
        // @codeCoverageIgnoreEnd
181 4
        if ($proxy = $this->getProxy($url)) {
182 1
            $curlOpts[CURLOPT_PROXY] = $proxy;
183 1
        }
184 4
        if ($this->capath) {
185 1
            $curlOpts[CURLOPT_CAPATH] = $this->capath;
186 1
        }
187 4
        if ($this->cafile) {
188 1
            $curlOpts[CURLOPT_CAINFO] = $this->cafile;
189 1
        }
190
191 4
        return $curlOpts;
192
    }
193
194
    /**
195
     * @return string
196
     */
197 7
    public function getURL()
198
    {
199 7
        $url = self::ifOr($this->scheme, '', '://');
200 7
        if ($this->user) {
201 1
            $user = $this->user;
202 1
            $user .= self::ifOr($this->pass, ':');
203 1
            $url .= $user . '@';
204 1
        }
205 7
        $url .= self::ifOr($this->host);
206 7
        $url .= self::ifOr($this->port, ':');
207 7
        $url .= self::ifOr($this->path);
208 7
        $url .= self::ifOr(http_build_query($this->query), '?');
209 7
        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 2 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 2
        $url = self::ifOr($this->scheme, '', '://');
230 2
        $url .= self::ifOr($this->host);
231 2
        $url .= self::ifOr($this->port, ':');
232 2
        return $url;
233
    }
234
235 9
    private static function ifOr($str, $pre = '', $post = '')
236
    {
237 9
        if ($str) {
238 9
            return $pre . $str . $post;
239
        }
240 7
        return '';
241
    }
242
243
    /**
244
     * @param string $url
245
     */
246 11
    public function setURL($url)
247
    {
248 11
        $struct = parse_url($url);
249 11
        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 11
            if ($key === 'query') {
251 4
                parse_str($val, $this->query);
252 4
            } else {
253 11
                $this->$key = $val;
254
            }
255 11
        }
256 11
    }
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 7
    public function setCA($path = null, $file = null)
269
    {
270 7
        $this->capath = $path;
271 7
        $this->cafile = $file;
272 7
    }
273
274 1
    public function isHTTP()
275
    {
276 1
        return $this->scheme === 'http' || $this->scheme === 'https';
277
    }
278
}
279