Completed
Pull Request — master (#98)
by Hiraku
07:53 queued 05:39
created

CopyRequest   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 335
Duplicated Lines 4.78 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 90.77%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 52
c 3
b 0
f 1
lcom 1
cbo 5
dl 16
loc 335
ccs 118
cts 130
cp 0.9077
rs 7.9487

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A __destruct() 0 12 4
A getURL() 0 14 2
A getMaskedURL() 0 8 1
A ifOr() 0 7 2
A setURL() 0 11 3
A addParam() 0 4 1
A addHeader() 0 4 1
A makeSuccess() 0 4 1
B getCurlOptions() 0 33 6
C setupAuthentication() 0 39 12
D getProxy() 16 28 9
A nssCiphers() 0 12 3
A setDestination() 0 18 3
A createDir() 0 11 3

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 CopyRequest 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 CopyRequest, 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
use Composer\Config;
12
13
class CopyRequest
14
{
15
    private $scheme;
16
    private $user;
17
    private $pass;
18
    private $host;
19
    private $port;
20
    private $path;
21
    private $query = array();
22
23
    /** @var [string => string] */
24
    private $headers = array();
25
26
    /** @var string */
27
    private $destination;
28
29
    /** @var resource<stream<plainfile>> */
30
    private $fp;
31
32
    private $success = false;
33
34
    private static $defaultCurlOptions = array(
35
        CURLOPT_HTTPGET => true,
36
        CURLOPT_FOLLOWLOCATION => true,
37
        CURLOPT_MAXREDIRS => 20,
38
        CURLOPT_ENCODING => '',
39
    );
40
41
    private $githubDomains = array();
42
    private $gitlabDomains = array();
43
44
    private $capath;
45
    private $cafile;
46
47
    private static $NSS_CIPHERS = array(
48
        'rsa_3des_sha',
49
        'rsa_des_sha',
50
        'rsa_null_md5',
51
        'rsa_null_sha',
52
        'rsa_rc2_40_md5',
53
        'rsa_rc4_128_md5',
54
        'rsa_rc4_128_sha',
55
        'rsa_rc4_40_md5',
56
        'fips_des_sha',
57
        'fips_3des_sha',
58
        'rsa_des_56_sha',
59
        'rsa_rc4_56_sha',
60
        'rsa_aes_128_sha',
61
        'rsa_aes_256_sha',
62
        'rsa_aes_128_gcm_sha_256',
63
        'dhe_rsa_aes_128_gcm_sha_256',
64
        'ecdh_ecdsa_null_sha',
65
        'ecdh_ecdsa_rc4_128_sha',
66
        'ecdh_ecdsa_3des_sha',
67
        'ecdh_ecdsa_aes_128_sha',
68
        'ecdh_ecdsa_aes_256_sha',
69
        'ecdhe_ecdsa_null_sha',
70
        'ecdhe_ecdsa_rc4_128_sha',
71
        'ecdhe_ecdsa_3des_sha',
72
        'ecdhe_ecdsa_aes_128_sha',
73
        'ecdhe_ecdsa_aes_256_sha',
74
        'ecdh_rsa_null_sha',
75
        'ecdh_rsa_128_sha',
76
        'ecdh_rsa_3des_sha',
77
        'ecdh_rsa_aes_128_sha',
78
        'ecdh_rsa_aes_256_sha',
79
        'echde_rsa_null',
80
        'ecdhe_rsa_rc4_128_sha',
81
        'ecdhe_rsa_3des_sha',
82
        'ecdhe_rsa_aes_128_sha',
83
        'ecdhe_rsa_aes_256_sha',
84
        'ecdhe_ecdsa_aes_128_gcm_sha_256',
85
        'ecdhe_rsa_aes_128_gcm_sha_256',
86
    );
87
88
    /**
89
     * @param string $url
90
     * @param string $destination
91
     * @param bool $useRedirector
92
     * @param IO\IOInterface $io
93
     * @param Config $config
94
     */
95 7
    public function __construct($url, $destination, $useRedirector, IO\IOInterface $io, Config $config)
96
    {
97 7
        $this->setURL($url);
98 7
        $this->setDestination($destination);
99 6
        $this->githubDomains = $config->get('github-domains');
0 ignored issues
show
Documentation Bug introduced by
It seems like $config->get('github-domains') of type * is incompatible with the declared type array of property $githubDomains.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
100 6
        $this->gitlabDomains = $config->get('gitlab-domains');
0 ignored issues
show
Documentation Bug introduced by
It seems like $config->get('gitlab-domains') of type * is incompatible with the declared type array of property $gitlabDomains.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
101 6
        $this->capath = $config->get('capath');
102 6
        $this->cafile = $config->get('cafile');
103 6
        $this->setupAuthentication($io, $useRedirector);
104 6
    }
105
106 6
    public function __destruct()
107
    {
108 6
        if ($this->fp) {
109 6
            fclose($this->fp);
110
        }
111
112 6
        if (!$this->success) {
113 6
            if (file_exists($this->destination)) {
114 6
                unlink($this->destination);
115
            }
116
        }
117 6
    }
118
119
    /**
120
     * @return string
121
     */
122 4
    public function getURL()
123
    {
124 4
        $url = self::ifOr($this->scheme, '', '://');
125 4
        if ($this->user) {
126 1
            $user = $this->user;
127 1
            $user .= self::ifOr($this->pass, ':');
128 1
            $url .= $user . '@';
129
        }
130 4
        $url .= self::ifOr($this->host);
131 4
        $url .= self::ifOr($this->port, ':');
132 4
        $url .= self::ifOr($this->path);
133 4
        $url .= self::ifOr(http_build_query($this->query), '?');
134 4
        return $url;
135
    }
136
137
    /**
138
     * @return string user/pass/access_token masked url
139
     */
140 1
    public function getMaskedURL()
141
    {
142 1
        $url = self::ifOr($this->scheme, '', '://');
143 1
        $url .= self::ifOr($this->host);
144 1
        $url .= self::ifOr($this->port, ':');
145 1
        $url .= self::ifOr($this->path);
146 1
        return $url;
147
    }
148
149 5
    private static function ifOr($str, $pre = '', $post = '')
150
    {
151 5
        if ($str) {
152 5
            return $pre . $str . $post;
153
        }
154 4
        return '';
155
    }
156
157
    /**
158
     * @param string $url
159
     */
160 7
    public function setURL($url)
161
    {
162 7
        $struct = parse_url($url);
163 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...
164 7
            if ($key === 'query') {
165 3
                parse_str($val, $this->query);
166
            } else {
167 7
                $this->$key = $val;
168
            }
169
        }
170 7
    }
171
172 1
    public function addParam($key, $val)
173
    {
174 1
        $this->query[$key] = $val;
175 1
    }
176
177 1
    public function addHeader($key, $val)
178
    {
179 1
        $this->headers[strtolower($key)] = $val;
180 1
    }
181
182 1
    public function makeSuccess()
183
    {
184 1
        $this->success = true;
185 1
    }
186
187
    /**
188
     * @return array
189
     */
190 2
    public function getCurlOptions()
191
    {
192 2
        $headers = array();
193 2
        foreach ($this->headers as $key => $val) {
194 1
            $headers[] = strtr(ucwords(strtr($key, '-', ' ')), ' ', '-') . ': ' . $val;
195
        }
196
197 2
        $url = $this->getURL();
198
199
        $curlOpts = array(
200 2
            CURLOPT_URL => $url,
201 2
            CURLOPT_HTTPHEADER => $headers,
202 2
            CURLOPT_USERAGENT => ConfigFacade::getUserAgent(),
203 2
            CURLOPT_FILE => $this->fp,
204
            //CURLOPT_VERBOSE => true, //for debug
205
        );
206 2
        $curlOpts += self::$defaultCurlOptions;
207
208 2
        if ($ciphers = $this->nssCiphers()) {
209
            $curlOpts[CURLOPT_SSL_CIPHER_LIST] = $ciphers;
210
        }
211 2
        if ($proxy = $this->getProxy($url)) {
212 1
            $curlOpts[CURLOPT_PROXY] = $proxy;
213
        }
214 2
        if ($this->capath) {
215
            $curlOpts[CURLOPT_CAPATH] = $this->capath;
216
        }
217 2
        if ($this->cafile) {
218
            $curlOpts[CURLOPT_CAINFO] = $this->cafile;
219
        }
220
221 2
        return $curlOpts;
222
    }
223
224
    /**
225
     * @param IO\IOInterface $io
226
     * @param bool $useRedirector
227
     */
228 6
    private function setupAuthentication(IO\IOInterface $io, $useRedirector)
229
    {
230 6
        if (preg_match('/\.github\.com$/', $this->host)) {
231 1
            $authKey = 'github.com';
232 1
            if ($useRedirector) {
233 1
                if ($this->host === 'api.github.com' && preg_match('%^/repos(/[^/]+/[^/]+/)zipball(.+)$%', $this->path, $_)) {
234 1
                    $this->host = 'codeload.github.com';
235 1
                    $this->path = $_[1] . 'legacy.zip' . $_[2];
236
                }
237
            }
238
        } else {
239 5
            $authKey = $this->host;
240
        }
241 6
        if (!$io->hasAuthentication($authKey)) {
242 4
            if ($this->user || $this->pass) {
243 2
                $io->setAuthentication($authKey, $this->user, $this->pass);
244
            } else {
245 2
                return;
246
            }
247
        }
248
249 4
        $auth = $io->getAuthentication($authKey);
250
251
        // is github
252 4
        if (in_array($authKey, $this->githubDomains) && 'x-oauth-basic' === $auth['password']) {
253 1
            $this->addParam('access_token', $auth['username']);
254 1
            $this->user = $this->pass = null;
255 1
            return;
256
        }
257
        // is gitlab
258 3
        if (in_array($authKey, $this->gitlabDomains) && 'oauth2' === $auth['password']) {
259 1
            $this->addHeader('authorization', 'Bearer ' . $auth['username']);
260 1
            $this->user = $this->pass = null;
261 1
            return;
262
        }
263
        // others, includes bitbucket
264 2
        $this->user = $auth['username'];
265 2
        $this->pass = $auth['password'];
266 2
    }
267
268 2
    private 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...
269
    {
270 2
        if (isset($_SERVER['no_proxy'])) {
271 1
            $pattern = new Util\NoProxyPattern($_SERVER['no_proxy']);
272 1
            if ($pattern->test($url)) {
273 1
                return null;
274
            }
275
        }
276
277 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...
278 1
            if (isset($_SERVER['HTTPS_PROXY'])) {
279
                return $_SERVER['HTTPS_PROXY'];
280
            }
281 1
            if (isset($_SERVER['https_proxy'])) {
282
                return $_SERVER['https_proxy'];
283
            }
284
        }
285
286 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...
287 1
            if (isset($_SERVER['HTTP_PROXY'])) {
288 1
                return $_SERVER['HTTP_PROXY'];
289
            }
290
            if (isset($_SERVER['http_proxy'])) {
291
                return $_SERVER['http_proxy'];
292
            }
293
        }
294 1
        return null;
295
    }
296
297
    /**
298
     * enable ECC cipher suites in cURL/NSS
299
     * @codeCoverageIgnore
300
     */
301
    public static function nssCiphers()
302
    {
303
        static $cache;
304
        if (isset($cache)) {
305
            return $cache;
306
        }
307
        $ver = curl_version();
308
        if (preg_match('/^NSS.*Basic ECC$/', $ver['ssl_version'])) {
309
            return $cache = implode(',', self::$NSS_CIPHERS);
310
        }
311
        return $cache = false;
312
    }
313
314
    /**
315
     * @param string
316
     */
317 7
    public function setDestination($destination)
318
    {
319 7
        $this->destination = $destination;
320 7
        if (is_dir($destination)) {
321 1
            throw new FetchException(
322 1
                'The file could not be written to ' . $destination . '. Directory exists.'
323
            );
324
        }
325
326 6
        $this->createDir($destination);
327
328 6
        $this->fp = fopen($destination, 'wb');
329 6
        if (!$this->fp) {
330
            throw new FetchException(
331
                'The file could not be written to ' . $destination
332
            );
333
        }
334 6
    }
335
336 6
    private function createDir($fileName)
337
    {
338 6
        $targetdir = dirname($fileName);
339 6
        if (!file_exists($targetdir)) {
340
            if (!mkdir($targetdir, 0766, true)) {
341
                throw new FetchException(
342
                    'The file could not be written to ' . $fileName
343
                );
344
            }
345
        }
346 6
    }
347
}
348