Completed
Push — master ( 19e3bd...22f213 )
by Guilherme
17:20
created

NfgSoap::getAuthentication()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace PROCERGS\LoginCidadao\NfgBundle\Service;
12
13
use libphonenumber\NumberParseException;
14
use libphonenumber\PhoneNumberType;
15
use libphonenumber\PhoneNumberUtil;
16
use PROCERGS\LoginCidadao\NfgBundle\Entity\NfgProfile;
17
use PROCERGS\LoginCidadao\NfgBundle\Exception\NfgServiceUnavailableException;
18
use PROCERGS\LoginCidadao\NfgBundle\Security\Credentials;
19
use Symfony\Component\DomCrawler\Crawler;
20
21
class NfgSoap implements NfgSoapInterface
22
{
23
    /** @var \SoapClient */
24
    private $client;
25
26
    /** @var Credentials */
27
    private $credentials;
28
29
    public function __construct(\SoapClient $client, Credentials $credentials)
30
    {
31
        $this->client = $client;
32
        $this->credentials = $credentials;
33
    }
34
35
    /**
36
     * @return string
37
     */
38
    public function getAccessID()
39
    {
40
        $response = $this->client->ObterAccessID($this->getAuthentication());
41
42
        if (false !== strpos($response->ObterAccessIDResult, ' ') || !isset($response->ObterAccessIDResult)) {
43
            throw new NfgServiceUnavailableException($response->ObterAccessIDResult);
44
        }
45
46
        return $response->ObterAccessIDResult;
47
    }
48
49
    /**
50
     * @param $accessToken
51
     * @param string $voterRegistration
0 ignored issues
show
Documentation introduced by
Should the type for parameter $voterRegistration not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
52
     * @return NfgProfile
53
     */
54
    public function getUserInfo($accessToken, $voterRegistration = null)
55
    {
56
        $params = $this->getAuthentication();
57
        $params['accessToken'] = $accessToken;
58
        if ($voterRegistration) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $voterRegistration of type string|null is loosely compared to true; 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...
59
            $params['tituloEleitoral'] = $voterRegistration;
60
        }
61
62
        $response = $this->client->ConsultaCadastro($params);
63
        $nfgProfile = new NfgProfile();
64
        $crawler = new Crawler($response->ConsultaCadastroResult);
65
66
        if ($crawler->filter('CodSitRetorno')->text() != 1) {
67
            throw new \RuntimeException($crawler->filter('MsgRetorno')->text());
68
        }
69
        $phoneNumber = $this->parsePhone($crawler);
70
71
        // Input example: 1970-01-01T00:00:00
72
        $birthday = \DateTime::createFromFormat('Y-m-d\TH:i:s', $this->getValue($crawler, 'DtNasc'));
73
74
        $nfgProfile
75
            ->setName($this->getValue($crawler, 'NomeConsumidor'))
76
            ->setEmail($this->getValue($crawler, 'EmailPrinc'))
77
            ->setBirthdate($birthday ?: null)
78
            ->setMobile($phoneNumber)
79
            ->setVoterRegistrationSit($this->getValue($crawler, 'CodSitTitulo'))
80
            ->setVoterRegistration($this->getValue($crawler, 'CodSitTitulo') != 0 ? $voterRegistration : null)
81
            ->setCpf($this->getValue($crawler, 'CodCpf'))
82
            ->setAccessLvl($this->getValue($crawler, 'CodNivelAcesso'));
83
84
        return $nfgProfile;
85
    }
86
87
    private function getAuthentication()
88
    {
89
        return [
90
            'organizacao' => $this->credentials->getOrganization(),
91
            'usuario' => $this->credentials->getUsername(),
92
            'senha' => $this->credentials->getPassword(),
93
        ];
94
    }
95
96
    private function parsePhone(Crawler $crawler)
97
    {
98
        if ($crawler->filter('NroFoneContato')->count() <= 0) {
99
            // Phone was not sent
100
            return null;
101
        }
102
103
        try {
104
            $phoneUtil = PhoneNumberUtil::getInstance();
105
            $phoneNumber = $phoneUtil->parse($crawler->filter('NroFoneContato')->text(), 'BR');
106
            $allowedTypes = [PhoneNumberType::MOBILE, PhoneNumberType::FIXED_LINE_OR_MOBILE];
107
            if (false === array_search($phoneUtil->getNumberType($phoneNumber), $allowedTypes)) {
108
                return null;
109
            }
110
111
            $nationalNumber = $phoneNumber->getNationalNumber();
112
            if ($phoneNumber->getCountryCode() === 55 && strlen($nationalNumber) == 10) {
113
                $with9thDigit = preg_replace('/^(\d{2})(\d{8})$/', '${1}9${2}', $nationalNumber);
114
                $phoneNumber->setNationalNumber($with9thDigit);
115
            }
116
        } catch (NumberParseException $e) {
117
            return null;
118
        }
119
120
        return $phoneNumber;
121
    }
122
123
    private function getValue(Crawler $crawler, $element)
124
    {
125
        $filter = $crawler->filter($element);
126
        if ($filter->count() <= 0) {
127
            return null;
128
        }
129
130
        return $filter->text();
131
    }
132
}
133