Completed
Push — master ( f5c851...12cc61 )
by Craig
07:00
created

ApplicationController::createAction()   C

Complexity

Conditions 12
Paths 9

Size

Total Lines 53
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 36
c 0
b 0
f 0
nc 9
nop 2
dl 0
loc 53
rs 6.3525

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
/*
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()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
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()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
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
        if (($group->getGtype() == CommonHelper::GTYPE_CORE)
107
            || ($group->getState() == CommonHelper::STATE_CLOSED)
108
            || ($group->getNbumax() > 0 && $group->getUsers()->count() > $group->getNbumax())
109
            || ($group->getUsers()->contains($userEntity))) {
110
            $this->addFlash('error', $this->__('Sorry!, You cannot apply to join the requested group')); // @todo more specific info would be better
111
112
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
113
        }
114
        $existingApplication = $this->get('zikula_groups_module.group_application_repository')->findOneBy(['group' => $group, 'user' => $userEntity]);
115
        if ($existingApplication) {
116
            $this->addFlash('info', $this->__('You already have a pending application. Please wait until the administrator notifies you.'));
117
118
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
119
        }
120
121
        $groupApplicationEntity = new GroupApplicationEntity();
122
        $groupApplicationEntity->setGroup($group);
123
        $groupApplicationEntity->setUser($userEntity);
124
        $form = $this->createForm('Zikula\GroupsModule\Form\Type\MembershipApplicationType', $groupApplicationEntity, [
125
                'translator' => $this->get('translator.default'),
126
            ]
127
        );
128
        if ($form->handleRequest($request)->isValid()) {
129
            if ($form->get('apply')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
130
                $groupApplicationEntity = $form->getData();
131
                $this->get('doctrine')->getManager()->persist($groupApplicationEntity);
132
                $this->get('doctrine')->getManager()->flush();
133
                $newApplicationEvent = new GenericEvent($groupApplicationEntity);
134
                $this->get('event_dispatcher')->dispatch(GroupEvents::GROUP_NEW_APPLICATION, $newApplicationEvent);
135
                $this->addFlash('status', $this->__('Done! The application has been sent. You will be notified by email when the application is processed.'));
136
            }
137
            if ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
138
                $this->addFlash('status', $this->__('Application cancelled.'));
139
            }
140
141
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
142
        }
143
144
        return [
145
            'form' => $form->createView(),
146
            'group' => $group,
147
        ];
148
    }
149
}
150