Passed
Push — issue#771 ( 623077...63169e )
by Guilherme
09:09
created

PersonController::editAction()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 52
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 32
nc 7
nop 2
dl 0
loc 52
ccs 0
cts 32
cp 0
crap 30
rs 8.6868
c 0
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
namespace LoginCidadao\CoreBundle\Controller\Admin;
4
5
use Doctrine\ORM\NonUniqueResultException;
6
use libphonenumber\PhoneNumber;
7
use LoginCidadao\APIBundle\Security\Audit\ActionLogger;
8
use LoginCidadao\CoreBundle\Entity\PersonRepository;
9
use LoginCidadao\PhoneVerificationBundle\Service\PhoneVerificationService;
10
use LoginCidadao\PhoneVerificationBundle\Service\PhoneVerificationServiceInterface;
11
use LoginCidadao\TOSBundle\Model\TOSManager;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
13
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
14
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
15
use Symfony\Component\Form\FormInterface;
16
use Symfony\Component\Routing\Annotation\Route;
17
use Symfony\Component\HttpFoundation\Request;
18
use LoginCidadao\CoreBundle\Helper\GridHelper;
19
use LoginCidadao\CoreBundle\Model\PersonInterface;
20
21
/**
22
 * @Route("/admin/person")
23
 * @Security("has_role('ROLE_PERSON_EDIT')")
24
 */
25
class PersonController extends Controller
26
{
27
28
    /**
29
     * @Route("/", name="lc_admin_person")
30
     * @Template()
31
     */
32
    public function indexAction(Request $request)
33
    {
34
        $data = null;
35
        if ($request->get('search') !== null) {
36
            $data = ['username' => $request->get('search')];
37
        }
38
        $form = $this->createForm('LoginCidadao\CoreBundle\Form\Type\PersonFilterFormType', $data);
39
        $form = $form->createView();
40
41
        return compact('form');
42
    }
43
44
    /**
45
     * @param Request $request
46
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
47
     *
48
     * @Route("/search", name="lc_admin_person_search")
49
     */
50
    public function smartSearchAction(Request $request)
51
    {
52
        $searchQuery = $request->get('query');
53
54
        /** @var PersonRepository $repo */
55
        $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
56
        try {
57
            $person = $repo->getSmartSearchQuery($searchQuery)
58
                ->getQuery()->getOneOrNullResult();
59
60
            if ($person instanceof PersonInterface) {
61
                return $this->redirectToRoute('lc_admin_person_edit', ['id' => $person->getId()]);
62
            }
63
        } catch (NonUniqueResultException $e) {
64
            // Failed...
65
        }
66
67
        return $this->redirectToRoute('lc_admin_person', ['search' => $searchQuery]);
68
    }
69
70
    /**
71
     * @Route("/grid", name="lc_admin_person_grid")
72
     * @Template()
73
     */
74
    public function gridAction(Request $request)
75
    {
76
        $form = $this->createForm('LoginCidadao\CoreBundle\Form\Type\PersonFilterFormType');
77
        $form->handleRequest($request);
78
        $gridView = null;
79
        if ($form->isValid()) {
80
            $data = $form->getData();
81
82
            $grid = new GridHelper();
83
            $grid->setId('person-grid');
84
            $grid->setPerPage(5);
85
            $grid->setMaxResult(5);
86
            $grid->setInfiniteGrid(true);
87
            $grid->setRoute('lc_admin_person_grid');
88
            $grid->setRouteParams([$form->getName()]);
89
90
            if ($data['username']) {
91
                /** @var PersonRepository $repo */
92
                $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
93
                $query = $repo->getSmartSearchQuery($data['username']);
94
                $grid->setQueryBuilder($query);
0 ignored issues
show
Deprecated Code introduced by
The function LoginCidadao\CoreBundle\...lper::setQueryBuilder() has been deprecated: since version 1.1.0 ( Ignorable by Annotation )

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

94
                /** @scrutinizer ignore-deprecated */ $grid->setQueryBuilder($query);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
95
            }
96
97
            $gridView = $grid->createView($request);
98
        }
99
100
        return ['grid' => $gridView];
101
    }
102
103
    /**
104
     * @Route("/{id}/edit", name="lc_admin_person_edit", requirements={"id" = "\d+"})
105
     * @Template()
106
     */
107
    public function editAction(Request $request, $id)
108
    {
109
        /** @var PersonRepository $repo */
110
        $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
111
112
        /** @var PersonInterface $person */
113
        $person = $repo->find($id);
114
        if (!$person) {
0 ignored issues
show
introduced by
$person is of type LoginCidadao\CoreBundle\Model\PersonInterface, thus it always evaluated to true.
Loading history...
115
            return $this->redirectToRoute('lc_admin_person');
116
        }
117
118
        /** @var ActionLogger $actionLogger */
119
        $actionLogger = $this->get('lc.action_logger');
120
        $actionLogger->registerProfileView($request, $person, $this->getUser(), [$this, 'editAction']);
121
122
        /** @var TOSManager $tosManager */
123
        $tosManager = $this->get('tos.manager');
124
        $agreement = $tosManager->getCurrentTermsAgreement($person);
125
126
        $phone = $person->getMobile();
127
        $phoneVerification = null;
128
        $samePhoneCount = 0;
129
        if ($phone instanceof PhoneNumber) {
130
            $samePhoneCount = $repo->countByPhone($phone);
131
132
            /** @var PhoneVerificationServiceInterface $phoneVerificationService */
133
            $phoneVerificationService = $this->get('phone_verification');
134
            $phoneVerification = $phoneVerificationService->getPhoneVerification($person, $person->getMobile());
135
        }
136
137
        $form = $this->createPersonForm($person);
138
        $form->handleRequest($request);
139
        if ($form->isValid()) {
140
            $securityHelper = $this->get('lc.security.helper');
141
            $loggedUserLevel = $securityHelper->getLoggedInUserLevel();
142
            $targetPersonLevel = $securityHelper->getTargetPersonLevel($person);
143
144
            if ($loggedUserLevel >= $targetPersonLevel) {
145
                $this->get('fos_user.user_manager')->updateUser($person);
146
                $this->addFlash('success', $this->get('translator')->trans('Updated successfully.'));
147
            }
148
        }
149
150
        $defaultClientUid = $this->container->getParameter('oauth_default_client.uid');
151
152
        return [
153
            'form' => $form->createView(),
154
            'person' => $person,
155
            'phoneVerification' => $phoneVerification,
156
            'samePhoneCount' => $samePhoneCount,
157
            'defaultClientUid' => $defaultClientUid,
158
            'agreement' => $agreement,
159
        ];
160
    }
161
162
    private function getRolesNames()
163
    {
164
        $rolesHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
165
        $roles = array();
166
167
        foreach ($rolesHierarchy as $role => $children) {
168
            $roles[$role] = $children;
169
            foreach ($children as $child) {
170
                if (!array_key_exists($child, $roles)) {
171
                    $roles[$child] = 0;
172
                }
173
            }
174
        }
175
176
        return array_keys($roles);
177
    }
178
179
    /**
180
     * @param PersonInterface $person
181
     * @return FormInterface
182
     */
183
    private function createPersonForm(PersonInterface $person)
184
    {
185
        $rolesNames = $this->getRolesNames();
186
187
        return $this->get('form.factory')->create(
188
            $this->get('lc.person.resume.form.type'),
189
            $person,
190
            array('available_roles' => $rolesNames)
191
        );
192
    }
193
194
    /**
195
     * @Route("/{id}/reports", name="lc_admin_person_impersonation_reports", requirements={"id" = "\d+"})
196
     * @Template()
197
     */
198
    public function impersonationReportsAction($id)
199
    {
200
        $reports = array();
201
        $person = $this->getDoctrine()
202
            ->getRepository('LoginCidadaoCoreBundle:Person')->find($id);
203
204
        if ($person instanceof PersonInterface) {
205
            $reportRepo = $this->getDoctrine()
206
                ->getRepository('LoginCidadaoCoreBundle:ImpersonationReport');
207
208
            $criteria = array('target' => $person);
209
            if (false === $this->isGranted('ROLE_IMPERSONATION_REPORTS_LIST_ALL')) {
210
                $criteria['impersonator'] = $this->getUser();
211
            }
212
213
            $reports = $reportRepo->findBy($criteria);
214
        }
215
216
        return compact('reports');
217
    }
218
}
219