Passed
Push — main ( b15a24...935ae5 )
by Axel
04:15
created

UserAdministrationController::listUsers()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 40
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 2
nop 9
dl 0
loc 40
rs 9.7333
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\UsersBundle\Controller;
15
16
use Doctrine\Persistence\ManagerRegistry;
17
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
18
use Symfony\Component\Form\FormInterface;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\Routing\Annotation\Route;
23
use Symfony\Component\Routing\RouterInterface;
24
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
25
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
26
use Symfony\Component\Security\Http\Attribute\IsGranted;
27
use Symfony\Contracts\Translation\TranslatorInterface;
28
use Translation\Extractor\Annotation\Desc;
29
use Zikula\Bundle\CoreBundle\Filter\AlphaFilter;
30
use Zikula\Bundle\CoreBundle\Response\PlainResponse;
31
use Zikula\Bundle\CoreBundle\Site\SiteDefinitionInterface;
32
use Zikula\UsersBundle\Api\ApiInterface\CurrentUserApiInterface;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Api\A...CurrentUserApiInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
33
use Zikula\UsersBundle\Collector\AuthenticationMethodCollector;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Colle...ticationMethodCollector was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
use Zikula\UsersBundle\Entity\User;
35
use Zikula\UsersBundle\Event\ActiveUserPostUpdatedEvent;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Event...iveUserPostUpdatedEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
use Zikula\UsersBundle\Event\DeleteUserFormPostCreatedEvent;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Event...serFormPostCreatedEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
use Zikula\UsersBundle\Event\DeleteUserFormPostValidatedEvent;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Event...rFormPostValidatedEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
38
use Zikula\UsersBundle\Event\EditUserFormPostCreatedEvent;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Event...serFormPostCreatedEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
39
use Zikula\UsersBundle\Event\EditUserFormPostValidatedEvent;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Event...rFormPostValidatedEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
40
use Zikula\UsersBundle\Event\RegistrationPostUpdatedEvent;
0 ignored issues
show
Bug introduced by
The type Zikula\UsersBundle\Event...trationPostUpdatedEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
41
use Zikula\UsersBundle\Form\Type\AdminModifyUserType;
42
use Zikula\UsersBundle\Form\Type\DeleteConfirmationType;
43
use Zikula\UsersBundle\Form\Type\DeleteType;
44
use Zikula\UsersBundle\Form\Type\MailType;
45
use Zikula\UsersBundle\Form\Type\RegistrationType\ApproveRegistrationConfirmationType;
46
use Zikula\UsersBundle\Form\Type\SearchUserType;
47
use Zikula\UsersBundle\Helper\AdministrationActionsHelper;
48
use Zikula\UsersBundle\Helper\DeleteHelper;
49
use Zikula\UsersBundle\Helper\MailHelper;
50
use Zikula\UsersBundle\Helper\RegistrationHelper;
51
use Zikula\UsersBundle\Repository\UserRepositoryInterface;
52
use Zikula\UsersBundle\UsersConstant;
53
54
#[Route('/users/admin')]
55
#[IsGranted('ROLE_ADMIN')]
56
class UserAdministrationController extends AbstractController
57
{
58
    public function __construct(
59
        private readonly TranslatorInterface $translator,
60
        private readonly int $itemsPerPage
61
    ) {
62
    }
63
64
    #[Route('/list/{sort}/{sortdir}/{letter}/{page}', name: 'zikulausersbundle_useradministration_listusers', methods: ['GET'], requirements: ['page' => '\d+'])]
65
    public function listUsers(
66
        Request $request,
67
        UserRepositoryInterface $userRepository,
68
        RouterInterface $router,
69
        AdministrationActionsHelper $actionsHelper,
70
        AuthenticationMethodCollector $authenticationMethodCollector,
71
        string $sort = 'uid',
72
        string $sortdir = 'DESC',
73
        string $letter = 'all',
74
        int $page = 1
75
    ): Response {
76
        /*$sortableColumns = new SortableColumns($router, 'zikulausersbundle_useradministration_listusers', 'sort', 'sortdir');
77
        $sortableColumns->addColumns([new Column('uname'), new Column('uid'), new Column('registrationDate'), new Column('lastLogin'), new Column('activated')]);
78
        $sortableColumns->setOrderByFromRequest($request);
79
        $sortableColumns->setAdditionalUrlParameters([
80
            'letter' => $letter,
81
            'page' => $page
82
        ]);
83
84
        */
85
        $filter = [];
86
        if (!empty($letter) && 'all' !== $letter) {
87
            $filter['uname'] = ['operator' => 'like', 'operand' => "${letter}%"];
88
        }
89
        $paginator = $userRepository->paginatedQuery($filter, [$sort => $sortdir], 'and', $page, $this->itemsPerPage);
90
        $paginator->setRoute('zikulausersbundle_useradministration_listusers');
91
        $routeParameters = [
92
            'sort' => $sort,
93
            'sortdir' => $sortdir,
94
            'letter' => $letter,
95
        ];
96
        $paginator->setRouteParameters($routeParameters);
97
98
        return $this->render('@ZikulaUsers/UserAdministration/list.html.twig', [
99
            // 'sort' => $sortableColumns->generateSortableColumns(),
100
            'actionsHelper' => $actionsHelper,
101
            'authMethodCollector' => $authenticationMethodCollector,
102
            'alpha' => new AlphaFilter('zikulausersbundle_useradministration_listusers', $routeParameters, $letter),
103
            'paginator' => $paginator,
104
        ]);
105
    }
106
107
    /**
108
     * Called from UsersBundle/Resources/public/js/Zikula.Users.Admin.View.js
109
     * to populate a username search
110
     */
111
    #[Route('/getusersbyfragmentastable', name: 'zikulausersbundle_useradministration_getusersbyfragmentastable', methods: ['POST'], options: ['expose' => true])]
112
    public function getUsersByFragmentAsTable(
113
        Request $request,
114
        UserRepositoryInterface $userRepository,
115
        AdministrationActionsHelper $actionsHelper
116
    ): Response {
117
        $fragment = $request->request->get('fragment');
118
        $filter = [
119
            'activated' => ['operator' => 'notIn', 'operand' => [
120
                UsersConstant::ACTIVATED_PENDING_REG,
121
                UsersConstant::ACTIVATED_PENDING_DELETE,
122
            ]],
123
            'uname' => ['operator' => 'like', 'operand' => "${fragment}%"]
124
        ];
125
        $users = $userRepository->query($filter);
126
127
        return $this->render('@ZikulaUsers/UserAdministration/userlist.html.twig', [
128
            'users' => $users,
129
            'actionsHelper' => $actionsHelper,
130
        ], new PlainResponse());
131
    }
132
133
    /**
134
     * @throws AccessDeniedException Thrown if guest user is being edited
135
     */
136
    #[Route('/user/modify/{user}', name: 'zikulausersbundle_useradministration_modify', requirements: ['user' => '^[1-9]\d*$'])]
137
    public function modify(
138
        Request $request,
139
        User $user,
140
        ManagerRegistry $doctrine,
141
        CurrentUserApiInterface $currentUserApi,
142
        EventDispatcherInterface $eventDispatcher
143
    ): Response {
144
        if (UsersConstant::USER_ID_ANONYMOUS === $user->getUid()) {
0 ignored issues
show
Bug introduced by
The method getUid() does not exist on Zikula\UsersBundle\Entity\User. ( Ignorable by Annotation )

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

144
        if (UsersConstant::USER_ID_ANONYMOUS === $user->/** @scrutinizer ignore-call */ getUid()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
145
            throw new AccessDeniedException($this->trans("Error! You can't edit the guest account."));
0 ignored issues
show
Bug introduced by
The method trans() does not exist on Zikula\UsersBundle\Contr...dministrationController. ( Ignorable by Annotation )

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

145
            throw new AccessDeniedException($this->/** @scrutinizer ignore-call */ trans("Error! You can't edit the guest account."));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
146
        }
147
148
        $form = $this->createForm(AdminModifyUserType::class, $user);
149
        $originalUser = clone $user;
150
        $editUserFormPostCreatedEvent = new EditUserFormPostCreatedEvent($form);
151
        $eventDispatcher->dispatch($editUserFormPostCreatedEvent);
152
        $form->handleRequest($request);
153
154
        if ($form->isSubmitted() && $form->isValid()) {
155
            if ($form->get('submit')->isClicked()) {
0 ignored issues
show
Bug introduced by
The method isClicked() does not exist on Symfony\Component\Form\FormInterface. It seems like you code against a sub-type of Symfony\Component\Form\FormInterface such as Symfony\Component\Form\SubmitButton. ( Ignorable by Annotation )

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

155
            if ($form->get('submit')->/** @scrutinizer ignore-call */ isClicked()) {
Loading history...
156
                $user = $form->getData();
157
                $this->checkSelf($currentUserApi, $user, $originalUser->getGroups()->toArray());
158
159
                $eventDispatcher->dispatch(new EditUserFormPostValidatedEvent($form, $user));
160
161
                $doctrine->getManager()->flush();
162
163
                $updateEvent = UsersConstant::ACTIVATED_PENDING_REG === $user->getActivated()
164
                    ? new RegistrationPostUpdatedEvent($user, $originalUser)
165
                    : new ActiveUserPostUpdatedEvent($user, $originalUser);
166
                $eventDispatcher->dispatch($updateEvent);
167
168
                $this->addFlash('status', "Done! Saved user's account information.");
169
            } elseif ($form->get('cancel')->isClicked()) {
170
                $this->addFlash('status', 'Operation cancelled.');
171
            }
172
173
            return $this->redirectToRoute('zikulausersbundle_useradministration_listusers');
174
        }
175
176
        return $this->render('@ZikulaUsers/UserAdministration/modify.html.twig', [
177
            'form' => $form->createView(),
178
            'additionalTemplates' => isset($editUserFormPostCreatedEvent) ? $editUserFormPostCreatedEvent->getTemplates() : [],
179
        ]);
180
    }
181
182
    #[Route('/user/approve/{user}/{force}', name: 'zikulausersbundle_useradministration_approve', requirements: ['user' => '^[1-9]\d*$'])]
183
    public function approve(
184
        Request $request,
185
        User $user,
186
        RegistrationHelper $registrationHelper,
187
        MailHelper $mailHelper,
188
        bool $force = false
189
    ): Response {
190
        $forceVerification = $force;
191
        $form = $this->createForm(ApproveRegistrationConfirmationType::class, [
192
            'user' => $user->getUid(),
193
            'force' => $forceVerification
194
        ], [
195
            'buttonLabel' => $this->translator->trans('Approve')
196
        ]);
197
        $redirectToRoute = 'zikulausersbundle_useradministration_listusers';
198
199
        if (!$forceVerification && $user->isApproved()) {
200
            $this->addFlash('error', $this->translator->trans('Warning! Nothing to do! %sub% is already approved.', ['%sub%' => $user->getUname()]));
0 ignored issues
show
Bug introduced by
The method getUname() does not exist on Zikula\UsersBundle\Entity\User. ( Ignorable by Annotation )

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

200
            $this->addFlash('error', $this->translator->trans('Warning! Nothing to do! %sub% is already approved.', ['%sub%' => $user->/** @scrutinizer ignore-call */ getUname()]));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
201
202
            return $this->redirectToRoute($redirectToRoute);
203
        }
204
205
        $form->handleRequest($request);
206
        if ($form->isSubmitted() && $form->isValid()) {
207
            if ($form->get('confirm')->isClicked()) {
208
                $registrationHelper->approve($user);
209
                if (UsersConstant::ACTIVATED_PENDING_REG === $user->getActivated()) {
0 ignored issues
show
Bug introduced by
The method getActivated() does not exist on Zikula\UsersBundle\Entity\User. ( Ignorable by Annotation )

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

209
                if (UsersConstant::ACTIVATED_PENDING_REG === $user->/** @scrutinizer ignore-call */ getActivated()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
210
                    $notificationErrors = $mailHelper->createAndSendRegistrationMail($user, true, false);
211
                } else {
212
                    $notificationErrors = $mailHelper->createAndSendUserMail($user, true, false);
213
                }
214
215
                if ($notificationErrors) {
216
                    $this->addFlash('error', implode('<br />', $notificationErrors));
217
                }
218
                $this->addFlash('status', $this->translator->trans('Done! %sub% has been approved.', ['%sub%' => $user->getUname()]));
219
            } elseif ($form->get('cancel')->isClicked()) {
220
                $this->addFlash('status', 'Operation cancelled.');
221
            }
222
223
            return $this->redirectToRoute($redirectToRoute);
224
        }
225
226
        return $this->render('@ZikulaUsers/UserAdministration/approve.html.twig', [
227
            'form' => $form->createView(),
228
            'user' => $user,
229
        ]);
230
    }
231
232
    #[Route('/delete/{user}', name: 'zikulausersbundle_useradministration_delete', requirements: ['user' => '^[1-9]\d*$'])]
233
    public function delete(
234
        Request $request,
235
        CurrentUserApiInterface $currentUserApi,
236
        UserRepositoryInterface $userRepository,
237
        EventDispatcherInterface $eventDispatcher,
238
        DeleteHelper $deleteHelper,
239
        User $user = null
240
    ): Response {
241
        $uids = [];
242
        if (!isset($user) && Request::METHOD_POST === $request->getMethod() && $request->request->has('zikulausersbundle_delete')) {
243
            $deletionData = $request->request->get('zikulausersbundle_delete');
244
            if (isset($deletionData['users']) && !empty($deletionData['users'])) {
245
                $uids = $deletionData['users'];
246
            }
247
        } elseif (isset($user)) {
248
            $uids = [$user->getUid()];
249
        }
250
        if (!count($uids) && !$request->request->has('zikulausersbundle_deleteconfirmation')) {
251
            $this->addFlash('warning', 'No users selected.');
252
253
            return $this->redirectToRoute('zikulausersbundle_useradministration_listusers');
254
        }
255
        $usersImploded = implode(',', $uids);
256
257
        $deleteConfirmationForm = $this->createForm(DeleteConfirmationType::class, [
258
            'users' => $usersImploded
259
        ]);
260
        $deleteUserFormPostCreatedEvent = new DeleteUserFormPostCreatedEvent($deleteConfirmationForm);
261
        $eventDispatcher->dispatch($deleteUserFormPostCreatedEvent);
262
        $deleteConfirmationForm->handleRequest($request);
263
        if ($deleteConfirmationForm->isSubmitted()) {
264
            if ($deleteConfirmationForm->get('cancel')->isClicked()) {
265
                $this->addFlash('success', 'Operation cancelled.');
266
267
                return $this->redirectToRoute('zikulausersbundle_useradministration_listusers');
268
            }
269
            $userIdsImploded = $deleteConfirmationForm->get('users')->getData();
270
            $userIds = explode(',', $userIdsImploded);
271
            $valid = true;
272
            foreach ($userIds as $k => $uid) {
273
                if (in_array($uid, [UsersConstant::USER_ID_ANONYMOUS, UsersConstant::USER_ID_ADMIN, $currentUserApi->get('uid')], true)) {
274
                    unset($userIds[$k]);
275
                    $this->addFlash('danger', $this->translator->trans('You are not allowed to delete user id %uid%', ['%uid%' => $uid]));
276
                    continue;
277
                }
278
            }
279
            if ($valid && $deleteConfirmationForm->isValid()) {
280
                $deletedUsers = $userRepository->query(['uid' => ['operator' => 'in', 'operand' => $userIds]]);
281
                $force = $deleteConfirmationForm->get('force')->getData();
282
                foreach ($deletedUsers as $deletedUser) {
283
                    $deleteHelper->deleteUser($deletedUser, $force);
284
                    $eventDispatcher->dispatch(new DeleteUserFormPostValidatedEvent($deleteConfirmationForm, $deletedUser));
285
                }
286
                $this->addFlash(
287
                    'success',
288
                    /** @Desc("{count, plural,\n  one   {User deleted!}\n  other {# users deleted!}\n}") */
289
                    $this->translator->trans(
290
                        'plural_n.users.deleted',
291
                        ['%count%' => count($deletedUsers)]
292
                    )
293
                );
294
295
                return $this->redirectToRoute('zikulausersbundle_useradministration_listusers');
296
            }
297
        }
298
        $users = $userRepository->findByUids($uids);
299
300
        return $this->render('@ZikulaUsers/UserAdministration/delete.html.twig', [
301
            'users' => $users,
302
            'form' => $deleteConfirmationForm->createView(),
303
            'additionalTemplates' => isset($deleteUserFormPostCreatedEvent) ? $deleteUserFormPostCreatedEvent->getTemplates() : [],
304
        ]);
305
    }
306
307
    #[Route('/search', name: 'zikulausersbundle_useradministration_search')]
308
    public function search(
309
        Request $request,
310
        UserRepositoryInterface $userRepository,
311
        SiteDefinitionInterface $site
312
    ): Response {
313
        $form = $this->createForm(SearchUserType::class, []);
314
        $form->handleRequest($request);
315
        if ($form->isSubmitted()) {
316
            $resultsForm = $this->createForm(DeleteType::class, [], [
317
                'choices' => $userRepository->queryBySearchForm($form->getData()),
318
                'action' => $this->generateUrl('zikulausersbundle_useradministration_delete')
319
            ]);
320
321
            return $this->render('@ZikulaUsers/UserAdministration/searchResults.html.twig', [
322
                'resultsForm' => $resultsForm->createView(),
323
                'mailForm' => $this->buildMailForm($site)->createView()
324
            ]);
325
        }
326
327
        return $this->render('@ZikulaUsers/UserAdministration/search.html.twig', [
328
            'form' => $form->createView(),
329
        ]);
330
    }
331
332
    #[Route('/mail', name: 'zikulausersbundle_useradministration_mailusers')]
333
    public function mailUsers(
334
        Request $request,
335
        UserRepositoryInterface $userRepository,
336
        MailHelper $mailHelper,
337
        SiteDefinitionInterface $site
338
    ): RedirectResponse {
339
        $mailForm = $this->buildMailForm($site);
340
        $mailForm->handleRequest($request);
341
        if ($mailForm->isSubmitted() && $mailForm->isValid()) {
342
            $data = $mailForm->getData();
343
            $users = $userRepository->query(['uid' => ['operator' => 'in', 'operand' => explode(',', $data['userIds'])]]);
344
            if (empty($users)) {
345
                throw new \InvalidArgumentException($this->translator->trans('No users found.'));
346
            }
347
            if ($mailHelper->mailUsers($users, $data)) {
348
                $this->addFlash('success', 'Done! Mail sent.');
349
            } else {
350
                $this->addFlash('error', 'Could not send mail.');
351
            }
352
        } else {
353
            $this->addFlash('error', 'Could not send mail.');
354
        }
355
356
        return $this->redirectToRoute('zikulausersbundle_useradministration_search');
357
    }
358
359
    private function buildMailForm(SiteDefinitionInterface $site): FormInterface
360
    {
361
        return $this->createForm(MailType::class, [
362
            'from' => $site->getName(),
363
            'replyto' => $site->getAdminMail(),
364
            'format' => 'text',
365
            'batchsize' => 100,
366
        ], [
367
            'action' => $this->generateUrl('zikulausersbundle_useradministration_mailusers')
368
        ]);
369
    }
370
371
    /**
372
     * Prevent user from modifying certain aspects of self.
373
     */
374
    private function checkSelf(
375
        CurrentUserApiInterface $currentUserApi,
376
        User $userBeingModified,
377
        array $originalGroups = []
378
    ): void {
379
        $currentUserId = $currentUserApi->get('uid');
380
        if ($currentUserId !== $userBeingModified->getUid()) {
381
            return;
382
        }
383
384
        // current user not allowed to deactivate self
385
        if (UsersConstant::ACTIVATED_ACTIVE !== $userBeingModified->getActivated()) {
386
            $this->addFlash('info', 'You are not allowed to alter your own active state.');
387
            $userBeingModified->setActivated(UsersConstant::ACTIVATED_ACTIVE);
0 ignored issues
show
Bug introduced by
The method setActivated() does not exist on Zikula\UsersBundle\Entity\User. ( Ignorable by Annotation )

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

387
            $userBeingModified->/** @scrutinizer ignore-call */ 
388
                                setActivated(UsersConstant::ACTIVATED_ACTIVE);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
388
        }
389
        /*
390
        // current user not allowed to remove self from default group
391
        $defaultGroupId = $this->defaultHelper->getDefaultGroupId();
392
        if (!$userBeingModified->getGroups()->containsKey($defaultGroupId)) {
393
            $this->addFlash('info', 'You are not allowed to remove yourself from the default group.');
394
            $userBeingModified->getGroups()->add($originalGroups[$defaultGroupId]);
395
        }
396
        // current user not allowed to remove self from admin group if currently a member
397
        if (isset($originalGroups[GroupsConstant::GROUP_ID_ADMIN]) && !$userBeingModified->getGroups()->containsKey(GroupsConstant::GROUP_ID_ADMIN)) {
398
            $this->addFlash('info', 'You are not allowed to remove yourself from the primary administrator group.');
399
            $userBeingModified->getGroups()->add($originalGroups[GroupsConstant::GROUP_ID_ADMIN]);
400
        }*/
401
    }
402
}
403