UserImportController::start()   B
last analyzed

Complexity

Conditions 10
Paths 67

Size

Total Lines 67
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
eloc 46
c 2
b 0
f 0
nc 67
nop 5
dl 0
loc 67
ccs 0
cts 33
cp 0
crap 110
rs 7.3115

How to fix   Long Method    Complexity   

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
namespace App\Controller;
4
5
use Symfony\Component\Messenger\MessageBusInterface;
6
use App\Form\ImportUsersFlow;
7
use App\Import\ImportUserData;
8
use App\Import\RecordInvalidException;
9
use App\Import\UserCsvImportHelper;
10
use App\Message\MustProvisionUser;
11
use App\Repository\UserRepositoryInterface;
12
use Exception;
13
use Psr\Log\LoggerInterface;
14
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
15
use Symfony\Component\Form\FormError;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\Routing\Annotation\Route;
18
use League\Csv\Exception as LeagueException;
19
use Symfony\Contracts\Translation\TranslatorInterface;
20
21
class UserImportController extends AbstractController {
22
23
    public function __construct(private MessageBusInterface $messageBus)
24
    {
25
    }
26
    #[Route(path: '/users/import', name: 'import_users')]
27
    public function start(ImportUsersFlow $flow, UserRepositoryInterface $userRepository, UserCsvImportHelper $helper,
28
                          TranslatorInterface $translator, LoggerInterface $logger): Response {
29
        $data = new ImportUserData();
30
        $flow->bind($data);
31
        $form = $flow->createForm();
32
33
        if ($flow->isValid($form)) {
34
            $flow->saveCurrentStepData($form);
35
36
            if ($flow->nextStep()) {
37
                try {
38
                    $form = $flow->createForm();
39
                } catch(RecordInvalidException $e) {
40
                    $flow->reset();
41
                    $form->addError(new FormError($translator->trans('import.error.invalid_record', [
42
                        '%field%' => $e->getField(),
43
                        '%offset%' => $e->getIndex()
44
                    ])));
45
                } catch (LeagueException $e) {
46
                    $flow->reset();
47
                    $logger->error('Error parsing CSV file.', [
48
                        'exception' => $e
49
                    ]);
50
                    $form->addError(new FormError('import.users.error.csv'));
51
                } catch (Exception $e) {
52
                    $logger->error('Error parsing CSV file.', [
53
                        'exception' => $e
54
                    ]);
55
                    $flow->reset();
56
                    $form->addError(new FormError('import.users.error.unknown'));
57
                }
58
            } else {
59
                try {
60
                    $userRepository->beginTransaction();
61
                    foreach ($data->getUsers() as $user) {
62
                        $userRepository->persist($user);
63
                    }
64
65
                    foreach($data->getRemoveUsers() as $user) {
66
                        $userRepository->remove($user);
67
                    }
68
                    $userRepository->commit();
69
70
                    foreach ($data->getUsers() as $user) {
71
                        $this->messageBus->dispatch(new MustProvisionUser($user->getId()));
72
                    }
73
74
                    $this->addFlash('success', 'import.users.success');
75
76
                    return $this->redirectToRoute('users');
77
                } catch (Exception $e) {
78
                    $userRepository->rollBack();
79
                    $form->addError(new FormError('import.error.unknown'));
80
81
                    $logger->error('Error persisting imported registration codes.', [
82
                        'exception' => $e
83
                    ]);
84
                }
85
            }
86
        }
87
88
        return $this->render('users/import.html.twig', [
89
            'form' => $form->createView(),
90
            'flow' => $flow,
91
            'headers' => $helper->getHeaders(),
92
            'required' => $helper->getRequiredHeaders()
93
        ]);
94
    }
95
}