Completed
Pull Request — master (#44)
by Hiraku
02:30
created

AspectAuth::after()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 3
1
<?php
2
/*
3
 * hirak/prestissimo
4
 * @author Hiraku NAKANO
5
 * @license MIT https://github.com/hirak/prestissimo
6
 */
7
namespace Hirak\Prestissimo\Aspects;
8
9
use SplObserver;
10
use SplSubject;
11
use Composer\Downloader;
12
13
/**
14
 * Authentication aspects.
15
 */
16
class AspectAuth implements SplObserver
17
{
18 10
    public function update(SplSubject $ev)
19
    {
20 10
        $name = (string)$ev;
21 10
        if ('pre-download' === $name) {
22 8
            return $this->before($ev->refRequest());
23
        }
24 7
        if ('post-download' === $name) {
25 7
            $this->after($ev->refResponse());
26 6
        }
27 6
    }
28
29 8
    private function before(HttpGetRequest $req)
30
    {
31 8
        if (!$req->username || !$req->password) {
32 6
            $req->username = $req->password = null;
33 6
            return;
34
        }
35
36 3
        if ($req instanceof GitHubRequest && $req->password === 'x-oauth-basic') {
37 1
            $req->query['access_token'] = $req->username;
38
            // forbid basic-auth
39 1
            $req->username = $req->password = null;
40 1
            return;
41
        }
42
43 2
        if ($req instanceof GitLabRequest && $req->password === 'oauth2') {
44 1
            $req->headers[] = 'Authorization: Bearer ' . $req->username;
45
            // forbid basic-auth
46 1
            $req->username = $req->password = null;
47 1
            return;
48
        }
49 1
    }
50
51 7
    private function after(HttpGetResponse $res)
52
    {
53 7
        if (CURLE_OK !== $res->errno) {
54 1
            throw new Downloader\TransportException("$res->error:$res->errno");
55
        }
56
57 6
        if (in_array($res->info['http_code'], array(401, 403, 404))) {
58 4
            $res->setNeedAuth();
59 4
            return;
60
        }
61 3
    }
62
}
63