BasicAuth::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace App\Middleware;
5
6
use Psr\Http\Server\MiddlewareInterface;
7
use Psr\Http\Server\RequestHandlerInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Laminas\Diactoros\Response\TextResponse;
11
12
class BasicAuth implements MiddlewareInterface
13
{
14
    /** @var string  */
15
    private $expectedAuthHeader;
16
17
    /** @var string  */
18
    private $realm;
19
20 4
    public function __construct(string $userName, string $password, string $realm)
21
    {
22 4
        $this->expectedAuthHeader = 'Basic ' . base64_encode("{$userName}:{$password}");
23 4
        $this->realm = $realm;
24 4
    }
25
26
    /**
27
     * @inheritDoc
28
     */
29 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
30
    {
31 3
        if ($this->expectedAuthHeader !== $request->getHeaderLine('Authorization')) {
32 2
            return new TextResponse(
33 2
                'Authentication required',
34 2
                401,
35 2
                ['WWW-Authenticate' => 'Basic realm="'. $this->realm . '"']
36
            );
37
        }
38
39 1
        return $handler->handle($request);
40
    }
41
}
42