UserAuth::authenticate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\User;
6
7
use Psr\Http\Message\ResponseFactoryInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Yiisoft\Auth\AuthenticationMethodInterface;
11
use Yiisoft\Auth\IdentityInterface;
12
use Yiisoft\Http\Status;
13
14
/**
15
 * Implementation of the authentication interface for the user.
16
 */
17
final class UserAuth implements AuthenticationMethodInterface
18
{
19
    private string $authUrl = '/login';
20
21 7
    public function __construct(private CurrentUser $currentUser, private ResponseFactoryInterface $responseFactory)
22
    {
23 7
    }
24
25 2
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
26
    {
27 2
        if ($this->currentUser->isGuest()) {
28 1
            return null;
29
        }
30
31 1
        return $this->currentUser->getIdentity();
32
    }
33
34
    /**
35
     * {@inheritDoc}
36
     *
37
     * Creates a new instance of the response and adds a `Location` header with a temporary redirect.
38
     */
39 2
    public function challenge(ResponseInterface $response): ResponseInterface
40
    {
41 2
        return $this->responseFactory
42 2
            ->createResponse(Status::FOUND)
43 2
            ->withHeader('Location', $this->authUrl);
44
    }
45
46
    /**
47
     * Returns a new instance with the specified authentication URL.
48
     *
49
     * @param string $url The authentication URL.
50
     */
51 4
    public function withAuthUrl(string $url): self
52
    {
53 4
        $new = clone $this;
54 4
        $new->authUrl = $url;
55 4
        return $new;
56
    }
57
}
58