Passed
Push — issue#771 ( 4c16c2...4d760a )
by Guilherme
07:32
created

PersonController::gridAction()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 18
nc 3
nop 1
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
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\CoreBundle\Security\User\Manager\UserManager;
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\HttpFoundation\Response;
17
use Symfony\Component\HttpFoundation\Session\SessionInterface;
18
use Symfony\Component\Routing\Annotation\Route;
19
use Symfony\Component\HttpFoundation\Request;
20
use LoginCidadao\CoreBundle\Helper\GridHelper;
21
use LoginCidadao\CoreBundle\Model\PersonInterface;
22
23
/**
24
 * @Route("/admin/person")
25
 * @Security("has_role('ROLE_PERSON_EDIT')")
26
 * @codeCoverageIgnore
27
 */
28
class PersonController extends Controller
29
{
30
31
    /**
32
     * @Route("/", name="lc_admin_person")
33
     * @Template()
34
     */
35
    public function indexAction(Request $request)
36
    {
37
        $data = null;
38
        if ($request->get('search') !== null) {
39
            $data = ['username' => $request->get('search')];
40
        }
41
        $form = $this->createForm('LoginCidadao\CoreBundle\Form\Type\PersonFilterFormType', $data);
42
        $form = $form->createView();
43
44
        return compact('form');
45
    }
46
47
    /**
48
     * @param Request $request
49
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
50
     *
51
     * @Route("/search", name="lc_admin_person_search")
52
     */
53
    public function smartSearchAction(Request $request)
54
    {
55
        $searchQuery = $request->get('query');
56
57
        /** @var PersonRepository $repo */
58
        $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
59
        try {
60
            $person = $repo->getSmartSearchQuery($searchQuery)
61
                ->getQuery()->getOneOrNullResult();
62
63
            if ($person instanceof PersonInterface) {
64
                return $this->redirectToRoute('lc_admin_person_edit', ['id' => $person->getId()]);
65
            }
66
        } catch (NonUniqueResultException $e) {
67
            // Failed...
68
        }
69
70
        return $this->redirectToRoute('lc_admin_person', ['search' => $searchQuery]);
71
    }
72
73
    /**
74
     * @param Request $request
75
     * @param $id
76
     * @param $token
77
     * @return Response
78
     *
79
     * @Route("/{id}/block/{token}", name="lc_admin_person_block")
80
     * @Security("has_role('ROLE_PERSON_BLOCK')")
81
     */
82
    public function blockAction(Request $request, $id, $token)
83
    {
84
        if (!$this->isBlockTokenValid($request->getSession(), $id, $token)) {
85
            $this->addFlash('error', $this->get('translator')->trans('lc.admin.person.block.invalid_token'));
86
87
            return $this->redirectToRoute('lc_admin_person_edit', ['id' => $id]);
88
        }
89
90
        /** @var UserManager $userManager */
91
        $userManager = $this->get('lc.user_manager');
92
        /** @var PersonRepository $repo */
93
        $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
94
95
        $person = $repo->find($id);
96
        if (!$person instanceof PersonInterface) {
97
            return $this->redirectToRoute('lc_admin_person');
98
        }
99
100
        $blockResponse = $userManager->blockPerson($person);
101
        if (null === $blockResponse) {
102
            $this->addFlash('error', $this->get('translator')->trans('lc.admin.person.block.failed'));
103
        } else {
104
            $this->addFlash('success', $this->get('translator')->trans('lc.admin.person.block.success'));
105
        }
106
107
        return $this->redirectToRoute('lc_admin_person_edit', ['id' => $id]);
108
    }
109
110
    /**
111
     * @Route("/grid", name="lc_admin_person_grid")
112
     * @Template()
113
     */
114
    public function gridAction(Request $request)
115
    {
116
        $form = $this->createForm('LoginCidadao\CoreBundle\Form\Type\PersonFilterFormType');
117
        $form->handleRequest($request);
118
        $gridView = null;
119
        if ($form->isValid()) {
120
            $data = $form->getData();
121
122
            $grid = new GridHelper();
123
            $grid->setId('person-grid');
124
            $grid->setPerPage(5);
125
            $grid->setMaxResult(5);
126
            $grid->setInfiniteGrid(true);
127
            $grid->setRoute('lc_admin_person_grid');
128
            $grid->setRouteParams([$form->getName()]);
129
130
            if ($data['username']) {
131
                /** @var PersonRepository $repo */
132
                $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
133
                $query = $repo->getSmartSearchQuery($data['username']);
134
                $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

134
                /** @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...
135
            }
136
137
            $gridView = $grid->createView($request);
138
        }
139
140
        return ['grid' => $gridView];
141
    }
142
143
    /**
144
     * @Route("/{id}/edit", name="lc_admin_person_edit", requirements={"id" = "\d+"})
145
     * @Template()
146
     */
147
    public function editAction(Request $request, $id)
148
    {
149
        /** @var PersonRepository $repo */
150
        $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
151
152
        /** @var PersonInterface $person */
153
        $person = $repo->find($id);
154
        if (!$person) {
0 ignored issues
show
introduced by
$person is of type LoginCidadao\CoreBundle\Model\PersonInterface, thus it always evaluated to true. If $person can have other possible types, add them to src/LoginCidadao/CoreBun...in/PersonController.php:152
Loading history...
155
            return $this->redirectToRoute('lc_admin_person');
156
        }
157
158
        /** @var ActionLogger $actionLogger */
159
        $actionLogger = $this->get('lc.action_logger');
160
        $actionLogger->registerProfileView($request, $person, $this->getUser(), [$this, 'editAction']);
161
162
        /** @var TOSManager $tosManager */
163
        $tosManager = $this->get('tos.manager');
164
        $agreement = $tosManager->getCurrentTermsAgreement($person);
165
166
        $phone = $person->getMobile();
167
        $phoneVerification = null;
168
        $samePhoneCount = 0;
169
        if ($phone instanceof PhoneNumber) {
170
            $samePhoneCount = $repo->countByPhone($phone);
171
172
            /** @var PhoneVerificationServiceInterface $phoneVerificationService */
173
            $phoneVerificationService = $this->get('phone_verification');
174
            $phoneVerification = $phoneVerificationService->getPhoneVerification($person, $person->getMobile());
175
        }
176
177
        $form = $this->createPersonForm($person);
178
        $form->handleRequest($request);
179
        if ($form->isValid()) {
180
            $securityHelper = $this->get('lc.security.helper');
181
            $loggedUserLevel = $securityHelper->getLoggedInUserLevel();
182
            $targetPersonLevel = $securityHelper->getTargetPersonLevel($person);
183
184
            if ($loggedUserLevel >= $targetPersonLevel) {
185
                $this->get('fos_user.user_manager')->updateUser($person);
186
                $this->addFlash('success', $this->get('translator')->trans('Updated successfully.'));
187
            }
188
        }
189
190
        $defaultClientUid = $this->container->getParameter('oauth_default_client.uid');
191
192
        $blockToken = $this->setBlockToken($request->getSession(), $person->getId());
193
194
        return [
195
            'form' => $form->createView(),
196
            'person' => $person,
197
            'phoneVerification' => $phoneVerification,
198
            'samePhoneCount' => $samePhoneCount,
199
            'defaultClientUid' => $defaultClientUid,
200
            'agreement' => $agreement,
201
            'blockToken' => $blockToken,
202
        ];
203
    }
204
205
    private function getRolesNames()
206
    {
207
        $rolesHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
208
        $roles = array();
209
210
        foreach ($rolesHierarchy as $role => $children) {
211
            $roles[$role] = $children;
212
            foreach ($children as $child) {
213
                if (!array_key_exists($child, $roles)) {
214
                    $roles[$child] = 0;
215
                }
216
            }
217
        }
218
219
        return array_keys($roles);
220
    }
221
222
    /**
223
     * @param PersonInterface $person
224
     * @return FormInterface
225
     */
226
    private function createPersonForm(PersonInterface $person)
227
    {
228
        $rolesNames = $this->getRolesNames();
229
230
        return $this->get('form.factory')->create(
231
            $this->get('lc.person.resume.form.type'),
232
            $person,
233
            array('available_roles' => $rolesNames)
234
        );
235
    }
236
237
    /**
238
     * @Route("/{id}/reports", name="lc_admin_person_impersonation_reports", requirements={"id" = "\d+"})
239
     * @Template()
240
     */
241
    public function impersonationReportsAction($id)
242
    {
243
        $reports = array();
244
        $person = $this->getDoctrine()
245
            ->getRepository('LoginCidadaoCoreBundle:Person')->find($id);
246
247
        if ($person instanceof PersonInterface) {
248
            $reportRepo = $this->getDoctrine()
249
                ->getRepository('LoginCidadaoCoreBundle:ImpersonationReport');
250
251
            $criteria = array('target' => $person);
252
            if (false === $this->isGranted('ROLE_IMPERSONATION_REPORTS_LIST_ALL')) {
253
                $criteria['impersonator'] = $this->getUser();
254
            }
255
256
            $reports = $reportRepo->findBy($criteria);
257
        }
258
259
        return compact('reports');
260
    }
261
262
    private function setBlockToken(SessionInterface $session, $id)
263
    {
264
        $token = bin2hex(random_bytes(64));
265
        $session->set("block_token_{$id}", $token);
266
267
        return $token;
268
    }
269
270
    /**
271
     * @param SessionInterface $session
272
     * @param mixed $id
273
     * @param string $token
274
     * @return bool
275
     */
276
    private function isBlockTokenValid(SessionInterface $session, $id, $token, $clear = true)
277
    {
278
        $key = "block_token_{$id}";
279
        $stored = $session->get($key);
280
        if ($clear) {
281
            $session->remove($key);
282
        }
283
284
        return $stored !== null && $stored === $token;
285
    }
286
}
287