AutoBasicAuth::authenticate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Http\Message\Authentication;
4
5
use Http\Message\Authentication;
6
use Psr\Http\Message\RequestInterface;
7
8
/**
9
 * Authenticate a PSR-7 Request using Basic Auth based on credentials in the URI.
10
 *
11
 * @author Márk Sági-Kazár <[email protected]>
12
 */
13
final class AutoBasicAuth implements Authentication
14
{
15
    /**
16
     * Whether user info should be removed from the URI.
17
     *
18
     * @var bool
19
     */
20
    private $shouldRemoveUserInfo;
21
22
    /**
23
     * @param bool|true $shouldRremoveUserInfo
24
     */
25 6
    public function __construct($shouldRremoveUserInfo = true)
26
    {
27 6
        $this->shouldRemoveUserInfo = (bool) $shouldRremoveUserInfo;
28 6
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 4
    public function authenticate(RequestInterface $request)
34
    {
35 4
        $uri = $request->getUri();
36 4
        $userInfo = $uri->getUserInfo();
37
38 4
        if (!empty($userInfo)) {
39 3
            if ($this->shouldRemoveUserInfo) {
40 2
                $request = $request->withUri($uri->withUserInfo(''));
41
            }
42
43 3
            $request = $request->withHeader('Authorization', sprintf('Basic %s', base64_encode($userInfo)));
44
        }
45
46 4
        return $request;
47
    }
48
}
49