Basic   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 2
cbo 2
dl 0
loc 66
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B handle() 0 23 4
A requireAuthentication() 0 8 1
1
<?php
2
3
namespace Jalle19\ReactHttpStatic\Authentication\Handler;
4
5
use React\Http\Request;
6
use React\Http\Response;
7
8
/**
9
 * Class Basic
10
 * @package   Jalle19\ReactHttpStatic\Authentication\Handler
11
 * @copyright Copyright &copy; Sam Stenvall 2016-
12
 * @license   @license https://opensource.org/licenses/MIT
13
 */
14
class Basic implements HandlerInterface
15
{
16
17
    /**
18
     * @var string
19
     */
20
    private $realm;
21
22
    /**
23
     * @var callable
24
     */
25
    private $implementation;
26
27
28
    /**
29
     * @param callable $implementation
30
     * @param string   $realm
31
     */
32
    public function __construct($realm, $implementation)
33
    {
34
        $this->realm          = $realm;
35
        $this->implementation = $implementation;
36
    }
37
38
39
    /**
40
     * @inheritdoc
41
     */
42
    public function handle(Request $request)
43
    {
44
        $headers = $request->getHeaders();
45
46
        if (array_key_exists('Authorization', $headers)) {
47
            $authorization = $headers['Authorization'];
48
49
            if (substr($authorization, 0, strlen('Basic ')) !== 'Basic ') {
50
                return false;
51
            }
52
53
            $authentication = base64_decode(substr($authorization, strlen('Basic ')));
54
            $parts          = explode(':', $authentication);
55
56
            if (count($parts) !== 2) {
57
                return false;
58
            }
59
60
            return call_user_func($this->implementation, $parts[0], $parts[1]);
61
        }
62
63
        return false;
64
    }
65
66
67
    /**
68
     * @inheritdoc
69
     */
70
    public function requireAuthentication(Response $response)
71
    {
72
        $response->writeHead(401, [
73
            'WWW-Authenticate' => 'Basic realm="' . $this->realm . '"',
74
        ]);
75
76
        $response->end();
77
    }
78
79
}
80