Passed
Pull Request — master (#1695)
by Tarmo
09:52
created

LoggedInUserValueResolver   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 33
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 16 5
A resolve() 0 3 1
A __construct() 0 3 1
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/ArgumentResolver/LoggedInUserValueResolver.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\ArgumentResolver;
10
11
use App\Entity\User;
12
use App\Security\UserTypeIdentification;
13
use Generator;
14
use Lexik\Bundle\JWTAuthenticationBundle\Exception\MissingTokenException;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
17
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
18
use Throwable;
19
20
/**
21
 * Class LoggedInUserValueResolver
22
 *
23
 * Example how to use this within your controller;
24
 *
25
 *  #[Route(path: 'some-path')]
26
 *  #[IsGranted(AuthenticatedVoter::IS_AUTHENTICATED_FULLY)]
27
 *  public function someMethod(\App\Entity\User $loggedInUser): Response
28
 *  {
29
 *      ...
30
 *  }
31
 *
32
 * This will automatically convert your security user to actual User entity that
33
 * you can use within your controller as you like.
34
 *
35
 * @package App\ArgumentResolver
36
 * @author TLe, Tarmo Leppänen <[email protected]>
37
 */
38
class LoggedInUserValueResolver implements ArgumentValueResolverInterface
39
{
40
    public function __construct(
41
        private UserTypeIdentification $userService,
42
    ) {
43
    }
44
45 122
    public function supports(Request $request, ArgumentMetadata $argument): bool
46
    {
47 122
        $output = false;
48
49
        // only security user implementations are supported
50 122
        if ($argument->getName() === 'loggedInUser' && $argument->getType() === User::class) {
51 41
            $securityUser = $this->userService->getSecurityUser();
52
53 41
            if ($securityUser === null && $argument->isNullable() === false) {
54 12
                throw new MissingTokenException('JWT Token not found');
55
            }
56
57 29
            $output = true;
58
        }
59
60 110
        return $output;
61
    }
62
63
    /**
64
     * @throws Throwable
65
     *
66
     * @return Generator<User|null>
67
     */
68 29
    public function resolve(Request $request, ArgumentMetadata $argument): Generator
69
    {
70 29
        yield $this->userService->getUser();
71
    }
72
}
73