IdentityService::refreshUser()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
/**
6
 * Copyright 2014 SURFnet bv
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
Coding Style introduced by
Missing @link tag in file comment
Loading history...
20
21
namespace Surfnet\StepupSelfService\SelfServiceBundle\Service;
22
23
use Exception;
24
use Psr\Log\LoggerInterface;
25
use Surfnet\StepupBundle\Command\SwitchLocaleCommand;
26
use Surfnet\StepupMiddlewareClient\Identity\Dto\IdentitySearchQuery;
27
use Surfnet\StepupMiddlewareClientBundle\Command\Command;
28
use Surfnet\StepupMiddlewareClientBundle\Identity\Command\CreateIdentityCommand;
29
use Surfnet\StepupMiddlewareClientBundle\Identity\Command\ExpressLocalePreferenceCommand;
30
use Surfnet\StepupMiddlewareClientBundle\Identity\Command\UpdateIdentityCommand;
31
use Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity;
32
use Surfnet\StepupMiddlewareClientBundle\Identity\Service\IdentityService as ApiIdentityService;
33
use Surfnet\StepupSelfService\SelfServiceBundle\Exception\RuntimeException;
34
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
35
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
36
use Symfony\Component\Security\Core\User\UserInterface;
37
use Symfony\Component\Security\Core\User\UserProviderInterface;
38
39
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
40
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) -- Hard to reduce due to different commands and queries used.
41
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
42
readonly class IdentityService implements UserProviderInterface
43
{
44
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
45
        private ApiIdentityService $apiIdentityService,
46
        private CommandService $commandService,
47
        private TokenStorageInterface $tokenStorage,
48
        private LoggerInterface $logger,
49
    ) {
50
    }
51
52
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $identifier should have a doc-comment as per coding-style.
Loading history...
53
     * For now this functionality is disabled, unsure if actually needed.
54
     * If needed, the userIdentifier is the UUID
55
     * of the identity, so it can be fetched rather easy
56
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
57
    public function loadUserByIdentifier(string $identifier): UserInterface
58
    {
59
        throw new RuntimeException(sprintf('Cannot Load User By Identifier "%s"', $identifier));
60
    }
61
62
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $user should have a doc-comment as per coding-style.
Loading history...
63
     * For now this functionality is disabled, unsure if actually needed
64
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
65
    public function refreshUser(UserInterface $user): void
66
    {
67
        throw new RuntimeException(sprintf('Cannot Refresh User "%s"', $user->getUsername()));
0 ignored issues
show
Bug introduced by
The method getUsername() does not exist on Symfony\Component\Security\Core\User\UserInterface. It seems like you code against a sub-type of Symfony\Component\Security\Core\User\UserInterface such as Surfnet\StepupSelfServic...n\AuthenticatedIdentity. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
        throw new RuntimeException(sprintf('Cannot Refresh User "%s"', $user->/** @scrutinizer ignore-call */ getUsername()));
Loading history...
68
    }
69
70
    public function supportsClass(string $class): bool
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function supportsClass()
Loading history...
71
    {
72
        return $class === Identity::class;
73
    }
74
75
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $nameId should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $institution should have a doc-comment as per coding-style.
Loading history...
76
     * @throws RuntimeException
77
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
78
    public function findByNameIdAndInstitution(string $nameId, string $institution): ?Identity
79
    {
80
        $searchQuery = new IdentitySearchQuery();
81
        $searchQuery->setNameId($nameId);
82
        $searchQuery->setInstitution($institution);
83
84
        try {
85
            $result = $this->apiIdentityService->search($searchQuery);
86
        } catch (Exception $e) {
87
            $message = sprintf('Exception when searching identity: "%s"', $e->getMessage());
88
            $this->logger->critical($message);
89
            throw new RuntimeException($message, 0, $e);
90
        }
91
92
        $elements = $result->getElements();
93
        if ($elements === []) {
94
            return null;
95
        }
96
97
        if (count($elements) === 1) {
98
            return reset($elements);
99
        }
100
101
        throw new RuntimeException(sprintf(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
102
            'Got an unexpected amount of identities, expected 0 or 1, got "%d"',
103
            count($elements)
104
        ));
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
105
    }
106
107
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $identity should have a doc-comment as per coding-style.
Loading history...
108
     * Save or Update an existing Identity
109
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
110
    public function createIdentity(Identity $identity): void
111
    {
112
        $command = new CreateIdentityCommand();
113
        $command->id              = $identity->id;
114
        $command->nameId          = $identity->nameId;
115
        $command->institution     = $identity->institution;
116
        $command->email           = $identity->email;
117
        $command->commonName      = $identity->commonName;
118
        $command->preferredLocale = $identity->preferredLocale;
119
120
        $this->processCommand($command);
121
    }
122
123
    public function updateIdentity(Identity $identity): void
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function updateIdentity()
Loading history...
124
    {
125
        $command = new UpdateIdentityCommand($identity->id, $identity->institution);
0 ignored issues
show
Bug introduced by
It seems like $identity->id can also be of type null; however, parameter $id of Surfnet\StepupMiddleware...yCommand::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
        $command = new UpdateIdentityCommand(/** @scrutinizer ignore-type */ $identity->id, $identity->institution);
Loading history...
126
        $command->email      = $identity->email;
127
        $command->commonName = $identity->commonName;
128
129
        $this->processCommand($command);
130
    }
131
132
    public function switchLocale(SwitchLocaleCommand $command): bool
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function switchLocale()
Loading history...
133
    {
134
        /** @var TokenInterface|null */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
135
        $token = $this->tokenStorage->getToken();
136
137
        if ($token === null) {
138
            throw new RuntimeException('Cannot switch locales when unauthenticated');
139
        }
140
141
        /** @var Identity $identity */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
142
        $identity = $token->getUser()->getIdentity();
0 ignored issues
show
Bug introduced by
The method getIdentity() does not exist on Symfony\Component\Security\Core\User\UserInterface. It seems like you code against a sub-type of Symfony\Component\Security\Core\User\UserInterface such as Surfnet\StepupSelfServic...n\AuthenticatedIdentity. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

142
        $identity = $token->getUser()->/** @scrutinizer ignore-call */ getIdentity();
Loading history...
143
144
        $expressLocalePreferenceCommand = new ExpressLocalePreferenceCommand();
145
        $expressLocalePreferenceCommand->identityId = $command->identityId;
146
        $expressLocalePreferenceCommand->preferredLocale = $command->locale;
147
148
        $result = $this->commandService->execute($expressLocalePreferenceCommand);
149
150
        if ($result->isSuccessful()) {
151
            $identity->preferredLocale = $command->locale;
152
        }
153
154
        return $result->isSuccessful();
155
    }
156
157
    public function processCommand(Command $command): void
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function processCommand()
Loading history...
158
    {
159
        $messageTemplate = 'Exception when saving Identity "%s": with command "%s", error: "%s"';
160
161
        try {
162
            $result = $this->commandService->execute($command);
163
        } catch (Exception $e) {
164
            $message = sprintf($messageTemplate, $command->id, $command::class, $e->getMessage());
0 ignored issues
show
Bug introduced by
Accessing id on the interface Surfnet\StepupMiddleware...tBundle\Command\Command suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
165
            $this->logger->critical($message);
166
167
            throw new RuntimeException($message, 0, $e);
168
        }
169
170
        if (!$result->isSuccessful()) {
171
            $note = sprintf($messageTemplate, $command->id, $command::class, implode('", "', $result->getErrors()));
172
            $this->logger->critical($note);
173
174
            throw new RuntimeException($note);
175
        }
176
    }
177
}
178