Client::getCookies()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Solutosoft\Receita;
4
5
use GuzzleHttp\Client as HttpClient;
6
use GuzzleHttp\Cookie\CookieJar;
7
use Symfony\Component\DomCrawler\Crawler;
8
9
class Client
10
{
11
    const URL_CAPTCHA = 'https://servicos.receita.fazenda.gov.br/Servicos/cnpjreva/captcha/gerarCaptcha.asp';
12
    const URL_REFER = 'https://servicos.receita.fazenda.gov.br/Servicos/cnpjreva/Cnpjreva_solicitacao3.asp';
13
    const URL_POST = 'https://servicos.receita.fazenda.gov.br/Servicos/cnpjreva/valida.asp';
14
15
    private $attributes =[
16
        'NOME EMPRESARIAL' => 'razao_social',
17
        'TÍTULO DO ESTABELECIMENTO (NOME DE FANTASIA)' => 'nome_fantasia',
18
        'CÓDIGO E DESCRIÇÃO DA ATIVIDADE ECONÔMICA PRINCIPAL' => 'cnae_principal',
19
        'CÓDIGO E DESCRIÇÃO DA NATUREZA JURÍDICA' => 'cnaes_secundario',
20
        'LOGRADOURO' => 'logradouro',
21
        'NÚMERO' => 'numero',
22
        'COMPLEMENTO' => 'complemento',
23
        'CEP' => 'cep',
24
        'BAIRRO/DISTRITO' => 'bairro',
25
        'MUNICÍPIO' => 'cidade',
26
        'UF' => 'uf',
27
        'SITUAÇÃO CADASTRAL' => 'situacao_cadastral',
28
        'DATA DA SITUAÇÃO CADASTRAL' => 'situacao_cadastral_data',
29
        'DATA DA SITUAÇÃO ESPECIAL' => 'situacao_especial',
30
        'TELEFONE' => 'telefone',
31
        'ENDEREÇO ELETRÔNICO' =>'email',
32
        'ENTE FEDERATIVO RESPONSÁVEL (EFR)' => 'responsavel',
33
        'DATA DE ABERTURA' => 'data_abertura'
34
    ];
35
36
    /**
37
     * @var array response cookies
38
     */
39
    private $cookies = [];
40
41
    /**
42
     * @var array $config Client configuration settings.
43
     */
44
    private $config;
45
46
    /**
47
     * The http client configuration settings
48
     *
49
     * @param array $config Client configuration settings.
50
     *
51
     * @see http://docs.guzzlephp.org/en/latest/request-options.html
52
     */
53
    public function __construct(array $config = [])
54
    {
55
        $this->config = $config;
56
    }
57
58
    /**
59
     * The Captcha image
60
     * @return mixed
61
     */
62
    public function getCaptcha()
63
    {
64
        $client = $this->createClient();
65
        $response = $client->get(self::URL_CAPTCHA);
66
67
        if ($response->getStatusCode() === 200) {
68
            $this->cookies = $this->encodeCookies($client->getConfig('cookies')->toArray());
69
            return $response->getBody()->getContents();
70
        }
71
72
        return null;
73
    }
74
75
    /**
76
     * Captcha response cookies
77
     * @return array
78
     */
79
    public function getCookies()
80
    {
81
       return $this->cookies;
82
    }
83
84
    /**
85
     * @param string $cnpj
86
     * @param string $captcha
87
     * @return array
88
     */
89
    public function findByCNPJ($cnpj, $captcha, $cookies)
90
    {
91
        $i = 0;
92
        $client = $this->createClient();
93
94
        do {
95
            $result = [];
96
            $response = $client->post(self::URL_POST, [
97
                'cookies' => CookieJar::fromArray($cookies, 'servicos.receita.fazenda.gov.br'),
98
                'form_params' =>  [
99
                    'cnpj' => $cnpj,
100
                    'origem' => 'comprovante',
101
                    'search_type' => 'cnpj',
102
                    'submit1' => 'Consultar',
103
                    'txtTexto_captcha_serpro_gov_br' => $captcha,
104
                ]
105
            ]);
106
107
            if ($response->getStatusCode() == 200) {
108
                $contents = $response->getBody()->getContents();
109
                if (preg_match_all('/<table border="0" width="100%" style="\s+BORDER-COLLAPSE: collapse;\s+">.*?<\/table>/ism', $contents , $matches)) {
110
                    foreach($matches[0] as $html) {
111
                        $result = array_merge($result, $this->parseCNPJ($html));
112
                    }
113
                }
114
            }
115
        } while (empty($result) && $i < 2);
116
117
        return $result;
118
    }
119
120
    /**
121
     * Parses html content
122
     * @param string $content
123
     * @return array
124
     */
125
    protected function parseCNPJ($content)
126
    {
127
        $result = [];
128
        $crawler = new Crawler($content);
129
130
        foreach ($crawler->filter('td') as $td) {
131
            $td = new Crawler($td);
132
            $info = $td->filter('font:nth-child(1)');
133
134
            if ($info->count() > 0) {
135
                $key = trim(strip_tags(preg_replace('/\s+/', ' ', $info->html())));
136
                $attr =  isset($this->attributes[$key]) ? $this->attributes[$key] : null;
137
138
                if ($attr === null) {
139
                    continue;
140
                }
141
142
                $bs = $td->filter('font > b');
143
                foreach ($bs as $b) {
144
                    $b = new Crawler($b);
145
146
                    $str = trim(preg_replace('/\s+/', ' ', $b->html()));
147
                    $attach = htmlspecialchars_decode($str);
148
149
                    if ($bs->count() == 1)
150
                        $result[$attr] = $attach;
151
                    else
152
                        $result[$attr][] = $attach;
153
                }
154
            }
155
        }
156
157
        return $result;
158
    }
159
160
    /**
161
     * Encodes response cookies
162
     * @return array
163
     */
164
    protected function encodeCookies($cookies)
165
    {
166
        $result = [];
167
168
        foreach ($cookies as $cookie) {
169
            $result[$cookie['Name']] = $cookie['Value'];
170
        }
171
172
        return $result;
173
    }
174
175
    /**
176
     * Creates a http client instance.
177
     * @return HttpClient
178
     */
179
    protected function createClient()
180
    {
181
        return new HttpClient(array_merge([
182
            'verify' => false,
183
            'cookies' => true,
184
            'headers' => [
185
                'Cache-Control' => 'no-cache',
186
                'Accept' => '*/*',
187
                'Accept-Encoding' => 'gzip, deflate, br'
188
            ],
189
        ], $this->config));
190
    }
191
192
}
193