Completed
Push — master ( ef0404...81c807 )
by Craig
23:17 queued 14:56
created

ApplicationController::getSpecificGroupMessage()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 16
nop 4
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\GroupsModule\Controller;
13
14
use Symfony\Component\HttpFoundation\RedirectResponse;
15
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
16
use Symfony\Component\HttpFoundation\Request;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
19
use Zikula\Core\Controller\AbstractController;
20
use Zikula\Core\Event\GenericEvent;
21
use Zikula\GroupsModule\Entity\GroupApplicationEntity;
22
use Zikula\GroupsModule\Entity\GroupEntity;
23
use Zikula\GroupsModule\GroupEvents;
24
use Zikula\GroupsModule\Helper\CommonHelper;
25
use Zikula\ThemeModule\Engine\Annotation\Theme;
26
27
/**
28
 * @Route("/application")
29
 */
30
class ApplicationController extends AbstractController
31
{
32
    /**
33
     * @Route("/admin/{action}/{app_id}", requirements={"action" = "deny|accept", "app_id" = "^[1-9]\d*$"})
34
     * @Theme("admin")
35
     * @Template
36
     *
37
     * display a list of group applications
38
     *
39
     * @param Request $request
40
     * @param string $action Name of desired action
41
     * @param GroupApplicationEntity $groupApplicationEntity
42
     * @return array|RedirectResponse
43
     */
44
    public function adminAction(Request $request, $action, GroupApplicationEntity $groupApplicationEntity)
45
    {
46
        if (!$this->hasPermission('ZikulaGroupsModule::', '::', ACCESS_EDIT)) {
47
            throw new AccessDeniedException();
48
        }
49
        $formValues = [
50
            'theAction' => $action,
51
            'application' => $groupApplicationEntity,
52
        ];
53
        $form = $this->createForm('Zikula\GroupsModule\Form\Type\ManageApplicationType', $formValues, [
54
            'translator' => $this->get('translator.default')
55
        ]);
56
57
        if ($form->handleRequest($request)->isValid()) {
58
            if ($form->get('save')->isClicked()) {
59
                $formData = $form->getData();
60
                $groupApplicationEntity = $formData['application'];
61
                $this->get('doctrine')->getManager()->remove($groupApplicationEntity);
62
                if ($action == 'accept') {
63
                    $groupApplicationEntity->getUser()->addGroup($groupApplicationEntity->getGroup());
64
                    $addUserEvent = new GenericEvent(['gid' => $groupApplicationEntity->getGroup()->getGid(), 'uid' => $groupApplicationEntity->getUser()->getUid()]);
65
                    $this->get('event_dispatcher')->dispatch(GroupEvents::GROUP_ADD_USER, $addUserEvent);
66
                }
67
                $this->get('doctrine')->getManager()->flush();
68
                $applicationProcessedEvent = new GenericEvent($groupApplicationEntity, $formData);
69
                $this->get('event_dispatcher')->dispatch(GroupEvents::GROUP_APPLICATION_PROCESSED, $applicationProcessedEvent);
70
                $this->addFlash('success', $this->__f('Application processed (%action %user)', ['%action' => $action, '%user' => $groupApplicationEntity->getUser()->getUname()]));
71
            }
72
            if ($form->get('cancel')->isClicked()) {
73
                $this->addFlash('success', $this->__('Operation cancelled.'));
74
            }
75
76
            return $this->redirectToRoute('zikulagroupsmodule_group_adminlist');
77
        }
78
79
        return [
80
            'form' => $form->createView(),
81
            'action' => $action,
82
            'application' => $groupApplicationEntity,
83
        ];
84
    }
85
86
    /**
87
     * @Route("/create/{gid}", requirements={"gid" = "^[1-9]\d*$"})
88
     * @Template
89
     *
90
     * Create an application to a group
91
     *
92
     * @param Request $request
93
     * @param GroupEntity $group
94
     * @return array|RedirectResponse
95
     */
96
    public function createAction(Request $request, GroupEntity $group)
97
    {
98
        if (!$this->hasPermission('ZikulaGroupsModule::', '::', ACCESS_OVERVIEW)) {
99
            throw new AccessDeniedException();
100
        }
101
        $currentUserApi = $this->get('zikula_users_module.current_user');
102
        if (!$currentUserApi->isLoggedIn()) {
103
            throw new AccessDeniedException($this->__('Error! You must register for a user account on this site before you can apply for membership of a group.'));
104
        }
105
        $userEntity = $this->get('zikula_users_module.user_repository')->find($currentUserApi->get('uid'));
106
        $groupTypeIsCore = $group->getGtype() == CommonHelper::GTYPE_CORE;
107
        $groupStateIsClosed = $group->getState() == CommonHelper::STATE_CLOSED;
108
        $groupCountIsLimit = $group->getNbumax() > 0 && $group->getUsers()->count() > $group->getNbumax();
109
        $alreadyGroupMember = $group->getUsers()->contains($userEntity);
110
        if ($groupTypeIsCore || $groupStateIsClosed || $groupCountIsLimit || $alreadyGroupMember) {
111
            $this->addFlash('error', $this->getSpecificGroupMessage($groupTypeIsCore, $groupStateIsClosed, $groupCountIsLimit, $alreadyGroupMember));
112
113
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
114
        }
115
        $existingApplication = $this->get('zikula_groups_module.group_application_repository')->findOneBy(['group' => $group, 'user' => $userEntity]);
116
        if ($existingApplication) {
117
            $this->addFlash('info', $this->__('You already have a pending application. Please wait until the administrator notifies you.'));
118
119
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
120
        }
121
122
        $groupApplicationEntity = new GroupApplicationEntity();
123
        $groupApplicationEntity->setGroup($group);
124
        $groupApplicationEntity->setUser($userEntity);
125
        $form = $this->createForm('Zikula\GroupsModule\Form\Type\MembershipApplicationType', $groupApplicationEntity, [
126
                'translator' => $this->get('translator.default'),
127
            ]
128
        );
129
        if ($form->handleRequest($request)->isValid()) {
130
            if ($form->get('apply')->isClicked()) {
131
                $groupApplicationEntity = $form->getData();
132
                $this->get('doctrine')->getManager()->persist($groupApplicationEntity);
133
                $this->get('doctrine')->getManager()->flush();
134
                $newApplicationEvent = new GenericEvent($groupApplicationEntity);
135
                $this->get('event_dispatcher')->dispatch(GroupEvents::GROUP_NEW_APPLICATION, $newApplicationEvent);
136
                $this->addFlash('status', $this->__('Done! The application has been sent. You will be notified by email when the application is processed.'));
137
            }
138
            if ($form->get('cancel')->isClicked()) {
139
                $this->addFlash('status', $this->__('Application cancelled.'));
140
            }
141
142
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
143
        }
144
145
        return [
146
            'form' => $form->createView(),
147
            'group' => $group,
148
        ];
149
    }
150
151
    private function getSpecificGroupMessage($groupTypeIsCore, $groupStateIsClosed, $groupCountIsLimit, $alreadyGroupMember)
152
    {
153
        $messages = [];
154
        $messages[] = $this->__('Sorry!, You cannot apply to join the requested group');
155
        if ($groupTypeIsCore) {
156
            $messages[] = $this->__('This group is a core-only group');
157
        }
158
        if ($groupStateIsClosed) {
159
            $messages[] = $this->__('This group is closed.');
160
        }
161
        if ($groupCountIsLimit) {
162
            $messages[] = $this->__('This group is has reached its membership limit.');
163
        }
164
        if ($alreadyGroupMember) {
165
            $messages[] = $this->__('You are already a member of this group.');
166
        }
167
168
        return implode('<br>', $messages);
169
    }
170
}
171