Completed
Pull Request — master (#104)
by Hiraku
02:52
created

BaseRequest   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 262
Duplicated Lines 5.73 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 86.44%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 40
c 3
b 1
f 0
lcom 1
cbo 3
dl 15
loc 262
ccs 102
cts 118
cp 0.8644
rs 8.2608

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getMaskedURL() 8 8 1
A getOriginURL() 7 7 1
A ifOr() 0 7 2
A addParam() 0 4 1
A addHeader() 0 4 1
A setCA() 0 5 1
A getURL() 0 14 2
A setURL() 0 11 3
A nssCiphers() 0 12 3
B getProxy() 0 21 7
C setupAuthentication() 0 39 12
B getCurlOptions() 0 34 6

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like BaseRequest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseRequest, and based on these observations, apply Extract Interface, too.

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 2
            return $cache = implode(',', self::$NSS_CIPHERS);
84
        }
85 2
        return $cache = false;
86 1
    }
87 1
88 1
    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 1
        if (isset($_SERVER['no_proxy'])) {
91
            $pattern = new Util\NoProxyPattern($_SERVER['no_proxy']);
92 2
            if ($pattern->test($url)) {
93 1
                return null;
94
            }
95
        }
96 1
97
        foreach (array('https', 'http') as $scheme) {
98
            if ($this->scheme === $scheme) {
99 1
                $label = $scheme . '_proxy';
100
                foreach (array(strtoupper($label), $label) as $l) {
101 2
                    if (isset($_SERVER[$l])) {
102 1
                        return $_SERVER[$l];
103 1
                    }
104
                }
105
            }
106
        }
107
        return null;
108
    }
109 1
110
    /**
111
     * @param $io
112
     * @param bool $useRedirector
113
     * @param $githubDomains
114
     * @param $gitlabDomains
115
     */
116
    protected function setupAuthentication(IO\IOInterface $io, $useRedirector, array $githubDomains, array $gitlabDomains)
117
    {
118 6
        if (preg_match('/\.github\.com$/', $this->host)) {
119
            $authKey = 'github.com';
120 6
            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 1
            $authKey = $this->host;
128 1
        }
129 5
        if (!$io->hasAuthentication($authKey)) {
130
            if ($this->user || $this->pass) {
131 6
                $io->setAuthentication($authKey, $this->user, $this->pass);
132 4
            } else {
133 2
                return;
134 2
            }
135 2
        }
136
137 2
        $auth = $io->getAuthentication($authKey);
138
139 4
        // is github
140
        if (in_array($authKey, $githubDomains) && 'x-oauth-basic' === $auth['password']) {
141
            $this->addParam('access_token', $auth['username']);
142 4
            $this->user = $this->pass = null;
143 1
            return;
144 1
        }
145 1
        // is gitlab
146
        if (in_array($authKey, $gitlabDomains) && 'oauth2' === $auth['password']) {
147
            $this->addHeader('authorization', 'Bearer ' . $auth['username']);
148 3
            $this->user = $this->pass = null;
149 1
            return;
150 1
        }
151 1
        // others, includes bitbucket
152
        $this->user = $auth['username'];
153
        $this->pass = $auth['password'];
154 2
    }
155 2
156 2
    /**
157
     * @return array
158
     */
159
    public function getCurlOptions()
160
    {
161 2
        $headers = array();
162
        foreach ($this->headers as $key => $val) {
163 2
            $headers[] = strtr(ucwords(strtr($key, '-', ' ')), ' ', '-') . ': ' . $val;
164 2
        }
165 1
166 2
        $url = $this->getURL();
167
168 2
        $curlOpts = array(
169
            CURLOPT_URL => $url,
170
            CURLOPT_HTTPHEADER => $headers,
171 2
            CURLOPT_USERAGENT => ConfigFacade::getUserAgent(),
172 2
            //CURLOPT_VERBOSE => true, //for debug
173 2
        );
174
        $curlOpts += static::$defaultCurlOptions;
175 2
176 2
        // @codeCoverageIgnoreStart
177
        if ($ciphers = $this->nssCiphers()) {
178 2
            $curlOpts[CURLOPT_SSL_CIPHER_LIST] = $ciphers;
179
        }
180
        // @codeCoverageIgnoreEnd
181 2
        if ($proxy = $this->getProxy($url)) {
182 1
            $curlOpts[CURLOPT_PROXY] = $proxy;
183 1
        }
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 1
        }
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 3
            } else {
253 7
                $this->$key = $val;
254
            }
255 7
        }
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