LocaleController::switchLocale()   B
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 54
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 33
nc 5
nop 1
dl 0
loc 54
rs 8.7697
c 1
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types = 1);
4
5
/**
6
 * Copyright 2015 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\Controller;
22
23
use Psr\Log\LoggerInterface;
24
use Surfnet\StepupBundle\Command\SwitchLocaleCommand;
25
use Surfnet\StepupBundle\Form\Type\SwitchLocaleType;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Service\IdentityService;
27
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
28
use Symfony\Component\HttpFoundation\RedirectResponse;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
31
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
32
use Symfony\Component\Routing\Attribute\Route;
33
use Symfony\Contracts\Translation\TranslatorInterface;
34
35
final class LocaleController extends AbstractController
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class LocaleController
Loading history...
36
{
37
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
38
        private readonly LoggerInterface $logger,
39
        private readonly TranslatorInterface $translator,
40
        private readonly IdentityService $identityService,
41
    ) {
42
    }
43
44
    #[Route(
45
        path: '/switch-locale',
46
        name: 'ss_switch_locale',
47
        requirements: ['return-url' => '.+'],
48
        methods: ['POST']
49
    )]
50
    public function switchLocale(Request $request): RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function switchLocale()
Loading history...
51
    {
52
        $returnUrl = $request->query->get('return-url');
53
54
        // Return URLs generated by us always include a path (ie. at least a forward slash)
55
        // @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L878
56
        $domain = $request->getSchemeAndHttpHost() . '/';
57
        if (!str_starts_with($returnUrl, $domain)) {
58
            $this->logger->error(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...
59
                'Identity "%s" used illegal return-url for redirection after changing locale, aborting request',
60
                $this->getUser()->getIdentity()->id
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

60
                $this->getUser()->/** @scrutinizer ignore-call */ getIdentity()->id
Loading history...
61
            ));
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...
62
63
            throw new BadRequestHttpException('Invalid return-url given');
64
        }
65
66
        $this->logger->info('Switching locale...');
67
68
        $identity = $this->getUser()->getIdentity();
69
        if (!$identity) {
70
            throw new AccessDeniedHttpException('Cannot switch locales when not authenticated');
71
        }
72
73
        $command = new SwitchLocaleCommand();
74
        $command->identityId = $identity->id;
75
76
        $form = $this->createForm(
77
            SwitchLocaleType::class,
78
            $command,
79
            ['route' => 'ss_switch_locale', 'route_parameters' => ['return_url' => $returnUrl]]
80
        );
81
        $form->handleRequest($request);
82
83
        if (!$form->isSubmitted() || !$form->isValid()) {
84
            $this->addFlash('error', $this->translator->trans('ss.flash.invalid_switch_locale_form'));
85
            $this->logger->error('The switch locale form unexpectedly contained invalid data');
86
            return $this->redirect($returnUrl);
87
        }
88
89
        if (!$this->identityService->switchLocale($command)) {
90
            $this->addFlash('error', $this->translator->trans('ss.flash.error_while_switching_locale'));
91
            $this->logger->error('An error occurred while switching locales');
92
            return $this->redirect($returnUrl);
93
        }
94
95
        $this->logger->info('Successfully switched locale');
96
97
        return $this->redirect($returnUrl);
98
    }
99
}
100