Failed Conditions
Branch master (116909)
by Guilherme
08:28
created

NfgController   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 406
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 406
ccs 0
cts 229
cp 0
rs 6
c 0
b 0
f 0
wmc 55

13 Methods

Rating   Name   Duplication   Size   Complexity  
D createBackAction() 0 105 9
B checkAccessToken() 0 25 5
F bindBackAction() 0 77 14
A solveConflict() 0 16 3
A getMeuRSHelper() 0 3 1
C loginBacktAction() 0 51 11
A loginAction() 0 3 1
A checkOtherPerson() 0 21 4
A unbindAction() 0 15 2
A bindAction() 0 3 1
A notifyAndClearCpfAndNfg() 0 7 1
A toNfg() 0 20 2
A createAction() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like NfgController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use NfgController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PROCERGS\LoginCidadao\CoreBundle\Controller;
4
5
use LoginCidadao\CoreBundle\Model\PersonInterface;
6
use PROCERGS\LoginCidadao\CoreBundle\Entity\PersonMeuRS;
7
use PROCERGS\LoginCidadao\CoreBundle\Helper\NfgWsHelper;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\Routing\Annotation\Route;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\RedirectResponse;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
14
use PROCERGS\LoginCidadao\CoreBundle\Exception\NfgException;
15
use FOS\UserBundle\Event\FormEvent;
16
use FOS\UserBundle\FOSUserEvents;
17
use FOS\UserBundle\Event\FilterUserResponseEvent;
18
use FOS\UserBundle\Event\GetResponseUserEvent;
19
use PROCERGS\LoginCidadao\NfgBundle\Entity\NfgProfile;
20
use PROCERGS\LoginCidadao\CoreBundle\Helper\MeuRSHelper;
21
22
/**
23
 * @Route("/nfg-old")
24
 */
25
class NfgController extends Controller
26
{
27
28
    /**
29
     * @Route("/create", name="old_nfg_create")
30
     */
31
    public function createAction()
32
    {
33
        return $this->toNfg('nfg_url_auth', 'nfg_createback');
34
    }
35
36
    protected function toNfg($url, $callback, $useSession = false)
37
    {
38
        $nfg = $this->get('procergs_logincidadao.nfgws');
39
        $parm['accessid'] = $nfg->obterAccessID();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$parm was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parm = array(); before regardless.
Loading history...
40
        if ($useSession) {
41
            $this->getRequest()
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature. ( Ignorable by Annotation )

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

41
            /** @scrutinizer ignore-deprecated */ $this->getRequest()

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...
42
                ->getSession()
43
                ->set('ticketacessologin', $parm['accessid']);
44
        }
45
        $parm['urlretorno'] = $this->generateUrl(
46
            $callback,
47
            array(),
48
            UrlGeneratorInterface::ABSOLUTE_URL
49
        );
50
        // $url = $this->container->getParameter('nfg_url_auth') . '?' . http_build_query($parm);
51
        $url = $this->container->getParameter($url).'?accessid='.$parm['accessid'].'&urlretorno='.$parm['urlretorno'];
52
53
        //IE referer stuff, dont kill me
54
        return new Response(
55
            '<html><head><meta name="referrer" content="always"/></head><body><script type="text/javascript">document.location= "'.$url.'";</script></body></html>'
56
        );
57
    }
58
59
    /**
60
     * @Route("/create/back", name="old_nfg_createback")
61
     */
62
    public function createBackAction(Request $request)
63
    {
64
        /** @var MeuRSHelper $meursHelper */
65
        $meursHelper = $this->get('meurs.helper');
66
67
        $result1 = $this->checkAccessToken();
68
        $em = $this->getDoctrine()->getManager();
69
        $personRepo = $em->getRepository('LoginCidadaoCoreBundle:Person');
70
        if ($personRepo->findOneBy(
71
            array(
72
                'cpf' => $result1['CodCpf'],
73
            )
74
        )
75
        ) {
76
            throw new NfgException('nfg.cpf.already.used');
77
        }
78
        if ($personRepo->findOneBy(
79
            array(
80
                'email' => $result1['EmailPrinc'],
81
            )
82
        )
83
        ) {
84
            throw new NfgException('nfg.email.already.used');
85
        }
86
87
        $formFactory = $this->container->get('fos_user.registration.form.factory');
88
        $userManager = $this->container->get('fos_user.user_manager');
89
        $dispatcher = $this->container->get('event_dispatcher');
90
91
        $nfgProfile = $em->getRepository('PROCERGSNfgBundle:NfgProfile')->findOneBy(
92
            array(
93
                'cpf' => $result1['CodCpf'],
94
            )
95
        );
96
        if (!$nfgProfile) {
97
            $nfgProfile = new NfgProfile();
98
            $nfgProfile->setCpf($result1['CodCpf']);
99
        }
100
        $nfgProfile->setName($result1['NomeConsumidor']);
101
        $nfgProfile->setEmail($result1['EmailPrinc']);
102
103
        $user = $userManager->createUser();
104
        $user->setEnabled(true);
105
        $user->setPassword('');
106
        $user->setEmailConfirmedAt(new \DateTime());
107
        $user->setEmailExpiration(null);
108
        $user->setNfgAccessToken($result1['paccessid']);
109
        $user->setCpf($result1['CodCpf']);
110
        $user->setEmail($result1['EmailPrinc']);
111
        if ($result1['DtNasc']) {
112
            $user->setBirthdate(
113
                new \DateTime(
114
                    str_replace(
115
                        'T',
116
                        ' ',
117
                        $result1['DtNasc']
118
                    )
119
                )
120
            );
121
            $nfgProfile->setBirthdate($user->getBirthdate());
122
        }
123
        if (isset($result1['NroFoneContato'])) {
124
            $user->setMobile($result1['NroFoneContato']);
125
            $nfgProfile->setMobile($user->getMobile());
126
        }
127
        if ($result1['CodNivelAcesso']) {
128
            $nfgProfile->setAccessLvl($result1['CodNivelAcesso']);
129
        }
130
        $nome = explode(' ', $result1['NomeConsumidor']);
131
        $user->setFirstName(array_shift($nome));
132
        $user->setSurname(implode(' ', $nome));
133
134
        $em->persist($nfgProfile);
135
136
        $event = new GetResponseUserEvent($user, $request);
137
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
138
139
        if (null !== $event->getResponse()) {
140
            return $event->getResponse();
141
        }
142
143
        $form = $formFactory->createForm();
144
        $form->setData($user);
145
146
        $event = new FormEvent($form, $request);
147
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
148
149
        $userManager->updateUser($user);
150
151
        $personMeuRS = $meursHelper->getPersonMeuRS($user, true);
152
        $personMeuRS->setNfgProfile($nfgProfile);
153
        $em->persist($personMeuRS);
154
        $em->flush($personMeuRS);
155
156
        if (null === $response = $event->getResponse()) {
0 ignored issues
show
introduced by
The condition null === $response = $event->getResponse() can never be false.
Loading history...
157
            $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
158
            $response = new RedirectResponse($url);
159
        }
160
161
        $dispatcher->dispatch(
162
            FOSUserEvents::REGISTRATION_COMPLETED,
163
            new FilterUserResponseEvent($user, $request, $response)
164
        );
165
166
        return $response;
167
    }
168
169
    protected function checkAccessToken($voterRegistration = null)
170
    {
171
        $request = $this->getRequest();
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature. ( Ignorable by Annotation )

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

171
        $request = /** @scrutinizer ignore-deprecated */ $this->getRequest();

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...
172
        $paccessid = $request->get('paccessid');
173
        if (!$paccessid) {
174
            throw new NfgException('nfg.missing.token');
175
        }
176
        /** @var NfgWsHelper $nfg */
177
        $nfg = $this->get('procergs_logincidadao.nfgws');
178
        $nfg->setAccessToken($paccessid);
179
        if ($voterRegistration) {
180
            $nfg->setTituloEleitoral($voterRegistration);
181
        }
182
        $result1 = $nfg->consultaCadastro();
183
        if ($result1['CodSitRetorno'] != 1) {
184
            throw new NfgException($result1['MsgRetorno']);
185
        }
186
        if (!isset($result1['CodCpf'], $result1['NomeConsumidor'],
187
            $result1['EmailPrinc'])
188
        ) {
189
            throw new NfgException('nfg.missing.required.fields');
190
        }
191
        $result1['paccessid'] = $paccessid;
192
193
        return $result1;
194
    }
195
196
    /**
197
     * @Route("/login", name="old_nfg_login")
198
     */
199
    public function loginAction()
200
    {
201
        return $this->toNfg('nfg_url_login', 'nfg_loginback', true);
202
    }
203
204
    /**
205
     * @Route("/login/back", name="old_nfg_loginback")
206
     */
207
    public function loginBacktAction(Request $request)
208
    {
209
        /** @var MeuRSHelper $meursHelper */
210
        $meursHelper = $this->get('meurs.helper');
211
212
        $cpf = $request->get('cpf');
213
        $accessid = $request->get('accessid');
214
        $prsec = $request->get('prsec');
215
        if (null == $accessid || null == $cpf || null == $prsec) {
216
            throw new NfgException('nfg.corrupted.callback');
217
        }
218
        $sig = hash_hmac(
219
            'sha256',
220
            "$cpf$accessid",
221
            $this->container->getParameter('nfg_hmac_secret')
222
        );
223
        if (false == $sig || strcmp(strtoupper($sig), $prsec) !== 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $sig of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
224
            throw new NfgException('nfg.corrupted.callback');
225
        }
226
        if ($request->getSession()->get('ticketacessologin') != $accessid) {
227
            throw new NfgException('nfg.accessid.mismatch');
228
        }
229
        $cpf = str_pad($cpf, 11, "0", STR_PAD_LEFT);
230
        $em = $this->getDoctrine()->getManager();
231
        $personRepo = $em->getRepository('LoginCidadaoCoreBundle:Person');
232
        $user = $personRepo->findOneBy(
233
            array(
234
                'cpf' => $cpf,
235
            )
236
        );
237
238
        if ($user instanceof PersonInterface) {
239
            $personMeuRS = $meursHelper->getPersonMeuRS($user, true);
240
        } else {
241
            $personMeuRS = null;
242
        }
243
244
        if (!$user || !$personMeuRS->getNfgAccessToken()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $personMeuRS->getNfgAccessToken() of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
245
            throw new NfgException('nfg.user.notfound');
246
        }
247
        $response = $this->redirect($this->generateUrl('lc_home'));
248
        try {
249
            $loginManager = $this->container->get('fos_user.security.login_manager');
250
            $firewallName = $this->container->getParameter('fos_user.firewall_name');
251
            $loginManager->loginUser($firewallName, $user, $response);
252
        } catch (AccountStatusException $ex) {
0 ignored issues
show
Bug introduced by
The type PROCERGS\LoginCidadao\Co...\AccountStatusException 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...
253
            // We simply do not authenticate users which do not pass the user
254
            // checker (not enabled, expired, etc.).
255
        }
256
257
        return $response;
258
    }
259
260
    /**
261
     * @Route("/bind", name="old_nfg_bind")
262
     */
263
    public function bindAction()
264
    {
265
        return $this->toNfg('nfg_url_auth', 'nfg_bindback');
266
    }
267
268
    /**
269
     * @Route("/bind/back", name="old_nfg_bindback")
270
     */
271
    public function bindBackAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

271
    public function bindBackAction(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
272
    {
273
        $person = $this->getUser();
274
        $meuRSHelper = $this->getMeuRSHelper();
275
        if (!$person) {
276
            return $this->redirect($this->generateUrl('lc_home'));
277
        }
278
        $result1 = $this->checkAccessToken($meuRSHelper->getVoterRegistration($person));
279
        $em = $this->getDoctrine()->getManager();
280
        $personRepo = $em->getRepository('LoginCidadaoCoreBundle:Person');
281
282
        if ($person->getCpf()) {
283
            if ($person->getCpf() != $result1['CodCpf']) {
284
                $this->checkOtherPerson($result1, $em, $personRepo);
285
286
                $person->setCpf($result1['CodCpf']);
287
                // TODO: notify user
288
            }
289
        } else {
290
            $this->checkOtherPerson($result1, $em, $personRepo);
291
            $person->setCpf($result1['CodCpf']);
292
        }
293
294
        $nfgProfile = $em->getRepository('PROCERGSNfgBundle:NfgProfile')->findOneBy(
295
            array(
296
                'cpf' => $result1['CodCpf'],
297
            )
298
        );
299
        if (!$nfgProfile) {
300
            $nfgProfile = new NfgProfile();
301
            $nfgProfile->setCpf($result1['CodCpf']);
302
        }
303
        $nfgProfile->setName($result1['NomeConsumidor']);
304
        $nfgProfile->setEmail($result1['EmailPrinc']);
305
        if (isset($result1['DtNasc'])) {
306
            $nfgProfile->setBirthdate(
307
                new \DateTime(
308
                    str_replace(
309
                        'T',
310
                        ' ',
311
                        $result1['DtNasc']
312
                    )
313
                )
314
            );
315
            if (!$person->getBirthdate()) {
316
                $person->setBirthdate($nfgProfile->getBirthdate());
317
            }
318
        }
319
        if (isset($result1['NroFoneContato'])) {
320
            $nfgProfile->setMobile($result1['NroFoneContato']);
321
            if (!$person->getMobile()) {
322
                $person->setMobile($nfgProfile->getMobile());
323
            }
324
        }
325
        if ($result1['CodNivelAcesso']) {
326
            $nfgProfile->setAccessLvl($result1['CodNivelAcesso']);
327
        }
328
        if (isset($result1['CodSitTitulo'])) {
329
            $nfgProfile->setVoterRegistrationSit($result1['CodSitTitulo']);
330
            if (1 == $result1['CodSitTitulo']) {
331
                $nfgProfile->setVoterRegistration($meuRSHelper->getVoterRegistration($person));
332
            }
333
        }
334
        $em->persist($nfgProfile);
335
336
        $personMeuRS = $meuRSHelper->getPersonMeuRS($person);
337
        $personMeuRS->setNfgProfile($nfgProfile);
338
        $personMeuRS->setNfgAccessToken($result1['paccessid']);
339
        if (!$person->getFirstName() || !$person->getSurname()) {
340
            $nome = explode(' ', $result1['NomeConsumidor']);
341
            $person->setFirstName(array_shift($nome));
342
            $person->setSurname(implode(' ', $nome));
343
        }
344
345
        $this->container->get('fos_user.user_manager')->updateUser($person);
346
347
        return $this->redirect($this->generateUrl('lc_home'));
348
    }
349
350
    /**
351
     * @return MeuRSHelper
352
     */
353
    private function getMeuRSHelper()
354
    {
355
        return $this->get('meurs.helper');
356
    }
357
358
    protected function checkOtherPerson(&$result1, &$em, &$personRepo)
0 ignored issues
show
Unused Code introduced by
The parameter $em is not used and could be removed. ( Ignorable by Annotation )

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

358
    protected function checkOtherPerson(&$result1, /** @scrutinizer ignore-unused */ &$em, &$personRepo)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
359
    {
360
        $otherPerson = $personRepo->findOneBy(
361
            array(
362
                'cpf' => $result1['CodCpf'],
363
            )
364
        );
365
        if (!$otherPerson) {
366
            return;
367
        }
368
369
        if ($otherPerson->getNfgAccessToken()) {
370
            $this->solveConflict($result1, $otherPerson);
371
        } else {
372
            if ($result1['CodNivelAcesso'] == 1) {
373
                throw new NfgException(
374
                    'notification.nfg.already.cpf.but.weak',
375
                    NfgException::E_BIND
376
                );
377
            } else {
378
                $this->notifyAndClearCpfAndNfg($otherPerson);
379
            }
380
        }
381
    }
382
383
    private function solveConflict($thisPerson, Person $otherPerson)
384
    {
385
        $otherPersonNfg = $otherPerson->getNfgProfile();
386
        if ($otherPersonNfg->getAccessLvl() == 1) {
387
            if ($thisPerson['CodNivelAcesso'] == 1) {
388
                throw new NfgException(
389
                    'notification.nfg.already.bind.but.weak',
390
                    NfgException::E_BIND
391
                );
392
            } else {
393
                $this->notifyAndClearCpfAndNfg($otherPerson);
394
            }
395
        } else {
396
            throw new NfgException(
397
                'notification.nfg.already.bind',
398
                NfgException::E_BIND
399
            );
400
        }
401
    }
402
403
    private function notifyAndClearCpfAndNfg(Person $person)
404
    {
405
        $person->setCpf(null);
406
        $person->setNfgAccessToken(null);
407
        $person->setNfgProfile(null);
408
        //@TODO do no use updateUser
409
        $this->container->get('fos_user.user_manager')->updateUser($person);
410
        // TODO: notify user
411
    }
412
413
    /**
414
     * @Route("/unbind", name="old_nfg_unbind")
415
     */
416
    public function unbindAction()
417
    {
418
        $em = $this->getDoctrine()->getManager();
419
        $person = $this->getUser();
420
        $meuRSHelper = $this->getMeuRSHelper();
421
        $personMeuRS = $meuRSHelper->getPersonMeuRS($person);
422
        if ($personMeuRS instanceof PersonMeuRS) {
0 ignored issues
show
introduced by
The condition $personMeuRS instanceof ...ndle\Entity\PersonMeuRS can never be false since $personMeuRS is always a sub-type of PROCERGS\LoginCidadao\Co...ndle\Entity\PersonMeuRS.
Loading history...
423
            $personMeuRS->setNfgAccessToken(null);
424
            $personMeuRS->setNfgProfile(null);
425
            $em->persist($personMeuRS);
426
            $em->flush($personMeuRS);
427
            $this->container->get('fos_user.user_manager')->updateUser($person);
428
        }
429
430
        return $this->redirect($this->generateUrl('lc_home'));
431
    }
432
}
433