LoginMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\User\Login;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Psr\Log\LoggerInterface;
12
use Yiisoft\Auth\IdentityInterface;
13
use Yiisoft\Auth\Middleware\Authentication;
14
use Yiisoft\User\CurrentUser;
15
16
/**
17
 * `LoginMiddleware` automatically logs user in if {@see IdentityInterface} instance presents in a request
18
 * attribute. It is usually put there by {@see Authentication}.
19
 */
20
final class LoginMiddleware implements MiddlewareInterface
21
{
22
    /**
23
     * @param CurrentUser $currentUser The current user instance.
24
     * @param LoggerInterface $logger The logger instance.
25
     */
26 4
    public function __construct(
27
        private CurrentUser $currentUser,
28
        private LoggerInterface $logger,
29
    ) {
30 4
    }
31
32
    /**
33
     * {@inheritDoc}
34
     *
35
     * Before this middleware, there should be {@see Authentication} in the middleware stack.
36
     * It authenticates the user and places {@see IdentityInterface} instance in the corresponding request attribute.
37
     */
38 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40 3
        if (!$this->currentUser->isGuest()) {
41 1
            return $handler->handle($request);
42
        }
43
44
        /** @var mixed $identity */
45 3
        $identity = $request->getAttribute(Authentication::class);
46
47 3
        if ($identity instanceof IdentityInterface) {
48 2
            $this->currentUser->login($identity);
49
        } else {
50 1
            $this->logger->warning(sprintf(
51 1
                'Unable to authenticate user by token %s. Identity not found.',
52 1
                is_scalar($identity) ? ('"' . $identity . '"') : ('of type ' . get_debug_type($identity)),
53 1
            ));
54
        }
55
56 3
        return $handler->handle($request);
57
    }
58
}
59