Completed
Push — master ( 29a805...bdeb81 )
by Eugene
06:00
created

AuthenticationMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the Tarantool Client package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Tarantool\Client\Middleware;
15
16
use Tarantool\Client\Connection\Greeting;
17
use Tarantool\Client\Handler\Handler;
18
use Tarantool\Client\Request\AuthenticateRequest;
19
use Tarantool\Client\Request\Request;
20
use Tarantool\Client\Response;
21
22
final class AuthenticationMiddleware implements Middleware
23
{
24
    private $username;
25
    private $password;
26
27
    /** @var Greeting|null */
28
    private $greeting;
29
30
    public function __construct(string $username, string $password = '')
31
    {
32
        $this->username = $username;
33
        $this->password = $password;
34
    }
35
36
    public function process(Request $request, Handler $handler) : Response
37
    {
38
        $greeting = $handler->getConnection()->open();
39
40
        if ($greeting->equals($this->greeting)) {
41
            return $handler->handle($request);
42
        }
43
44
        $handler->handle(new AuthenticateRequest(
45
            $greeting->getSalt(),
46
            $this->username,
47
            $this->password
48
        ));
49
50
        $this->greeting = $greeting;
51
52
        return $handler->handle($request);
53
    }
54
}
55