Completed
Pull Request — master (#98)
by Hiraku
02:37
created

CopyRequest::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 5
crap 1
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 static $NSS_CIPHERS = array(
45
        'rsa_3des_sha',
46
        'rsa_des_sha',
47
        'rsa_null_md5',
48
        'rsa_null_sha',
49
        'rsa_rc2_40_md5',
50
        'rsa_rc4_128_md5',
51
        'rsa_rc4_128_sha',
52
        'rsa_rc4_40_md5',
53
        'fips_des_sha',
54
        'fips_3des_sha',
55
        'rsa_des_56_sha',
56
        'rsa_rc4_56_sha',
57
        'rsa_aes_128_sha',
58
        'rsa_aes_256_sha',
59
        'rsa_aes_128_gcm_sha_256',
60
        'dhe_rsa_aes_128_gcm_sha_256',
61
        'ecdh_ecdsa_null_sha',
62
        'ecdh_ecdsa_rc4_128_sha',
63
        'ecdh_ecdsa_3des_sha',
64
        'ecdh_ecdsa_aes_128_sha',
65
        'ecdh_ecdsa_aes_256_sha',
66
        'ecdhe_ecdsa_null_sha',
67
        'ecdhe_ecdsa_rc4_128_sha',
68
        'ecdhe_ecdsa_3des_sha',
69
        'ecdhe_ecdsa_aes_128_sha',
70
        'ecdhe_ecdsa_aes_256_sha',
71
        'ecdh_rsa_null_sha',
72
        'ecdh_rsa_128_sha',
73
        'ecdh_rsa_3des_sha',
74
        'ecdh_rsa_aes_128_sha',
75
        'ecdh_rsa_aes_256_sha',
76
        'echde_rsa_null',
77
        'ecdhe_rsa_rc4_128_sha',
78
        'ecdhe_rsa_3des_sha',
79
        'ecdhe_rsa_aes_128_sha',
80
        'ecdhe_rsa_aes_256_sha',
81
        'ecdhe_ecdsa_aes_128_gcm_sha_256',
82
        'ecdhe_rsa_aes_128_gcm_sha_256',
83
    );
84
85
    /**
86
     * @param string $url
87
     * @param string $destination
88
     * @param bool $useRedirector
89
     * @param IO\IOInterface $io
90
     * @param Config $config
91
     */
92 7
    public function __construct($url, $destination, $useRedirector, IO\IOInterface $io, Config $config)
93
    {
94 7
        $this->setURL($url);
95 7
        $this->setDestination($destination);
96 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...
97 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...
98 6
        $this->setupAuthentication($io, $useRedirector);
99 6
    }
100
101 6
    public function __destruct()
102
    {
103 6
        if ($this->fp) {
104 6
            fclose($this->fp);
105 6
        }
106
107 6
        if (!$this->success) {
108 6
            if (file_exists($this->destination)) {
109 6
                unlink($this->destination);
110 6
            }
111 6
        }
112 6
    }
113
114
    /**
115
     * @return string
116
     */
117 4
    public function getURL()
118
    {
119 4
        $url = self::ifOr($this->scheme, '', '://');
120 4
        if ($this->user) {
121 1
            $user = $this->user;
122 1
            $user .= self::ifOr($this->pass, ':');
123 1
            $url .= $user . '@';
124 1
        }
125 4
        $url .= self::ifOr($this->host);
126 4
        $url .= self::ifOr($this->port, ':');
127 4
        $url .= self::ifOr($this->path);
128 4
        $url .= self::ifOr(http_build_query($this->query), '?');
129 4
        return $url;
130
    }
131
132
    /**
133
     * @return string user/pass/access_token masked url
134
     */
135 1
    public function getMaskedURL()
136
    {
137 1
        $url = self::ifOr($this->scheme, '', '://');
138 1
        $url .= self::ifOr($this->host);
139 1
        $url .= self::ifOr($this->port, ':');
140 1
        $url .= self::ifOr($this->path);
141 1
        return $url;
142
    }
143
144 5
    private static function ifOr($str, $pre = '', $post = '')
145
    {
146 5
        if ($str) {
147 5
            return $pre . $str . $post;
148
        }
149 4
        return '';
150
    }
151
152
    /**
153
     * @param string $url
154
     */
155 7
    public function setURL($url)
156
    {
157 7
        $struct = parse_url($url);
158 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...
159 7
            if ($key === 'query') {
160 3
                parse_str($val, $this->query);
161 3
            } else {
162 7
                $this->$key = $val;
163
            }
164 7
        }
165 7
    }
166
167 1
    public function addParam($key, $val)
168
    {
169 1
        $this->query[$key] = $val;
170 1
    }
171
172 1
    public function addHeader($key, $val)
173
    {
174 1
        $this->headers[strtolower($key)] = $val;
175 1
    }
176
177 1
    public function makeSuccess()
178
    {
179 1
        $this->success = true;
180 1
    }
181
182
    /**
183
     * @return array
184
     */
185 2
    public function getCurlOptions()
186
    {
187 2
        $headers = array();
188 2
        foreach ($this->headers as $key => $val) {
189 1
            $headers[] = strtr(ucwords(strtr($key, '-', ' ')), ' ', '-') . ': ' . $val;
190 2
        }
191
192 2
        $url = $this->getURL();
193
194
        $curlOpts = array(
195 2
            CURLOPT_URL => $url,
196 2
            CURLOPT_HTTPHEADER => $headers,
197 2
            CURLOPT_USERAGENT => ConfigFacade::getUserAgent(),
198 2
            CURLOPT_FILE => $this->fp,
199
            //CURLOPT_VERBOSE => true, //for debug
200 2
        );
201 2
        $curlOpts += self::$defaultCurlOptions;
202
203 2
        if ($ciphers = $this->nssCiphers()) {
204
            $curlOpts[CURLOPT_SSL_CIPHER_LIST] = $ciphers;
205
        }
206 2
        if ($proxy = $this->getProxy($url)) {
207 1
            $curlOpts[CURLOPT_PROXY] = $proxy;
208 1
        }
209
210 2
        return $curlOpts;
211
    }
212
213
    /**
214
     * @param IO\IOInterface $io
215
     * @param bool $useRedirector
216
     */
217 6
    private function setupAuthentication(IO\IOInterface $io, $useRedirector)
218
    {
219 6
        if (preg_match('/\.github\.com$/', $this->host)) {
220 1
            $authKey = 'github.com';
221 1
            if ($useRedirector) {
222 1
                if ($this->host === 'api.github.com' && preg_match('%^/repos(/[^/]+/[^/]+/)zipball(.+)$%', $this->path, $_)) {
223 1
                    $this->host = 'codeload.github.com';
224 1
                    $this->path = $_[1] . 'legacy.zip' . $_[2];
225 1
                }
226 1
            }
227 1
        } else {
228 5
            $authKey = $this->host;
229
        }
230 6
        if (!$io->hasAuthentication($authKey)) {
231 4
            if ($this->user || $this->pass) {
232 2
                $io->setAuthentication($authKey, $this->user, $this->pass);
233 2
            } else {
234 2
                return;
235
            }
236 2
        }
237
238 4
        $auth = $io->getAuthentication($authKey);
239
240
        // is github
241 4
        if (in_array($authKey, $this->githubDomains) && 'x-oauth-basic' === $auth['password']) {
242 1
            $this->addParam('access_token', $auth['username']);
243 1
            $this->user = $this->pass = null;
244 1
            return;
245
        }
246
        // is gitlab
247 3
        if (in_array($authKey, $this->gitlabDomains) && 'oauth2' === $auth['password']) {
248 1
            $this->addHeader('authorization', 'Bearer ' . $auth['username']);
249 1
            $this->user = $this->pass = null;
250 1
            return;
251
        }
252
        // others, includes bitbucket
253 2
        $this->user = $auth['username'];
254 2
        $this->pass = $auth['password'];
255 2
    }
256
257 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...
258
    {
259 2
        if (isset($_SERVER['no_proxy'])) {
260 1
            $pattern = new Util\NoProxyPattern($_SERVER['no_proxy']);
261 1
            if ($pattern->test($url)) {
262 1
                return null;
263
            }
264 1
        }
265
266 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...
267 1
            if (isset($_SERVER['HTTPS_PROXY'])) {
268
                return $_SERVER['HTTPS_PROXY'];
269
            }
270 1
            if (isset($_SERVER['https_proxy'])) {
271
                return $_SERVER['https_proxy'];
272
            }
273 1
        }
274
275 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...
276 1
            if (isset($_SERVER['HTTP_PROXY'])) {
277 1
                return $_SERVER['HTTP_PROXY'];
278
            }
279
            if (isset($_SERVER['http_proxy'])) {
280
                return $_SERVER['http_proxy'];
281
            }
282
        }
283 1
        return null;
284
    }
285
286
    /**
287
     * enable ECC cipher suites in cURL/NSS
288
     */
289 2
    public static function nssCiphers()
290
    {
291 2
        static $cache;
292 2
        if (isset($cache)) {
293 1
            return $cache;
294
        }
295 1
        $ver = curl_version();
296 1
        if (preg_match('/^NSS.*Basic ECC$/', $ver['ssl_version'])) {
297
            return $cache = implode(',', self::$NSS_CIPHERS);
298
        }
299 1
        return $cache = false;
300
    }
301
302
    /**
303
     * @param string
304
     */
305 7
    public function setDestination($destination)
306
    {
307 7
        $this->destination = $destination;
308 7
        if (is_dir($destination)) {
309 1
            throw new FetchException(
310 1
                'The file could not be written to ' . $destination . '. Directory exists.'
311 1
            );
312
        }
313
314 6
        $this->createDir($destination);
315
316 6
        $this->fp = fopen($destination, 'wb');
317 6
        if (!$this->fp) {
318
            throw new FetchException(
319
                'The file could not be written to ' . $destination
320
            );
321
        }
322 6
    }
323
324 6
    private function createDir($fileName)
325
    {
326 6
        $targetdir = dirname($fileName);
327 6
        if (!file_exists($targetdir)) {
328
            if (!mkdir($targetdir, 0766, true)) {
329
                throw new FetchException(
330
                    'The file could not be written to ' . $fileName
331
                );
332
            }
333
        }
334 6
    }
335
}
336