Complex classes like SEFAZ 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 SEFAZ, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
38 | class SEFAZ |
||
39 | { |
||
40 | /** |
||
41 | * Lista de notas a serem processadas |
||
42 | * @var Nota[] |
||
43 | */ |
||
44 | private $notas; |
||
45 | |||
46 | /** |
||
47 | * Configurações a serem usadas |
||
48 | * @var \NFe\Common\Configuracao |
||
49 | */ |
||
50 | private $configuracao; |
||
51 | |||
52 | /** |
||
53 | * Instância global |
||
54 | * @var self |
||
55 | */ |
||
56 | private static $instance; |
||
57 | |||
58 | /** |
||
59 | * Constroi uma intência a partir de outra ou array |
||
60 | * @param mixed $sefaz outra instância ou array |
||
61 | */ |
||
62 | 105 | public function __construct($sefaz = []) |
|
66 | |||
67 | /** |
||
68 | * Obtém a instância global dessa classe |
||
69 | * @param bool $new cria uma nova instância |
||
70 | * @return self default instance |
||
71 | */ |
||
72 | 110 | public static function getInstance($new = false) |
|
79 | |||
80 | /** |
||
81 | * Lista de notas a serem processadas |
||
82 | * @return Nota[] |
||
83 | */ |
||
84 | 4 | public function getNotas() |
|
88 | |||
89 | /** |
||
90 | * Informa a lista de notas a serem processadas |
||
91 | * @param Nota[] $notas |
||
92 | * @return self |
||
93 | */ |
||
94 | 105 | public function setNotas($notas) |
|
99 | |||
100 | /** |
||
101 | * Adiciona uma nota ao processamento |
||
102 | * @param Nota $nota |
||
103 | * @return self |
||
104 | */ |
||
105 | 3 | public function addNota($nota) |
|
110 | |||
111 | /** |
||
112 | * Configuração usada atualmente |
||
113 | * @return \NFe\Common\Configuracao |
||
114 | */ |
||
115 | 96 | public function getConfiguracao() |
|
119 | |||
120 | /** |
||
121 | * Informa a nova configuração a ser usada |
||
122 | * @param \NFe\Common\Configuracao $configuracao |
||
123 | * @return self |
||
124 | */ |
||
125 | 105 | public function setConfiguracao($configuracao) |
|
130 | |||
131 | /** |
||
132 | * Converte a instância atual em array |
||
133 | * @param bool $recursive se deve converter os itens também em array |
||
134 | * @return array |
||
135 | */ |
||
136 | 1 | public function toArray($recursive = false) |
|
156 | |||
157 | /** |
||
158 | * Preenche a instância atual com dados do array ou outra instância |
||
159 | * @param mixed $sefaz outra instância ou array de dados |
||
160 | * @return self |
||
161 | */ |
||
162 | 105 | public function fromArray($sefaz = []) |
|
177 | |||
178 | /** |
||
179 | * Chama os eventos da nota lançando exceção em caso de rejeição |
||
180 | * @param Nota $nota nota a ser despachada |
||
181 | * @param \DOMDocument $dom xml da nota |
||
182 | * @param \NFe\Task\Retorno $retorno resposta da SEFAZ |
||
183 | */ |
||
184 | 1 | private function despacha($nota, $dom, $retorno) |
|
204 | |||
205 | /** |
||
206 | * Envia as notas adicionadas para a SEFAZ, caso não consiga, torna-as em contingência |
||
207 | * todos os status são informados no evento da configuração, caso não possua evento, |
||
208 | * uma \Exception será lançada na primeira falha |
||
209 | * @return int quantidade de notas processadas ou que entraram em contingência |
||
210 | */ |
||
211 | 3 | public function autoriza() |
|
212 | { |
||
213 | 3 | $i = 0; |
|
214 | 3 | $evento = $this->getConfiguracao()->getEvento(); |
|
215 | 3 | foreach ($this->getNotas() as $nota) { |
|
216 | try { |
||
217 | 2 | $envia = true; |
|
218 | do { |
||
219 | 2 | $dom = $nota->getNode()->ownerDocument; |
|
220 | 2 | $evento->onNotaGerada($nota, $dom); |
|
221 | 2 | $dom = $nota->assinar($dom); |
|
222 | 2 | $evento->onNotaAssinada($nota, $dom); |
|
223 | 2 | $dom = $nota->validar($dom); // valida o XML da nota |
|
224 | 2 | $evento->onNotaValidada($nota, $dom); |
|
225 | 2 | if (!$envia) { |
|
226 | 1 | break; |
|
227 | } |
||
228 | 2 | $evento->onNotaEnviando($nota, $dom); |
|
229 | 2 | $autorizacao = new Autorizacao(); |
|
230 | try { |
||
231 | 2 | $retorno = $autorizacao->envia($nota, $dom); |
|
232 | 1 | } catch (\Exception $e) { |
|
233 | 1 | $partial_response = $e instanceof \NFe\Exception\IncompleteRequestException; |
|
234 | 1 | if ($partial_response) { |
|
235 | 1 | $evento->onNotaPendente($nota, $dom, $e); |
|
236 | } |
||
237 | 1 | if ($nota->getEmissao() == Nota::EMISSAO_CONTINGENCIA) { |
|
238 | throw $e; |
||
239 | } |
||
240 | 1 | Log::debug('SEFAZ.autoriza(' . $e->getCode() . ') - Mudando emissão para contingência: ' . |
|
241 | 1 | $e->getMessage() . ' - ' . $nota->getID(true)); |
|
242 | 1 | $msg = 'Falha no envio da nota'; |
|
243 | 1 | $nota->setEmissao(Nota::EMISSAO_CONTINGENCIA); |
|
244 | 1 | $nota->setDataContingencia(time()); |
|
245 | 1 | $nota->setJustificativa($msg); |
|
246 | 1 | $evento->onNotaContingencia($nota, !$partial_response, $e); |
|
247 | 1 | $envia = false; |
|
248 | 1 | continue; |
|
249 | } |
||
250 | 1 | Log::debug('SEFAZ.autoriza(' . $retorno->getStatus() . ') - ' . |
|
251 | 1 | $retorno->getMotivo() . ' - ' . $nota->getID(true)); |
|
252 | 1 | $this->despacha($nota, $dom, $retorno); |
|
253 | 1 | break; |
|
254 | 1 | } while (true); |
|
255 | 2 | $evento->onNotaCompleto($nota, $dom); |
|
256 | 2 | $i++; |
|
257 | } catch (\Exception $e) { |
||
258 | Log::error('SEFAZ.autoriza(' . $e->getCode() . ') - ' . $e->getMessage()); |
||
259 | 2 | $evento->onNotaErro($nota, $e); |
|
260 | } |
||
261 | } |
||
262 | 3 | return $i; |
|
263 | } |
||
264 | |||
265 | /** |
||
266 | * Consulta o status das notas em processamento |
||
267 | * @return int quantidade de consultas executadas com sucesso |
||
268 | */ |
||
269 | 2 | public function consulta($pendencias) |
|
292 | |||
293 | /** |
||
294 | * Consulta se as notas existem e cancela ou inutiliza seus números |
||
295 | * Também processa pedido de inutilização e cancelamento de notas |
||
296 | * @return int quantidade de tarefas executadas com sucesso |
||
297 | */ |
||
298 | 4 | public function executa($tarefas) |
|
330 | |||
331 | /** |
||
332 | * Inutiliza um intervalo de números de notas fiscais e insere o resultado no |
||
333 | * próprio objeto de inutilização |
||
334 | * @param \NFe\Task\Inutilizacao $inutilizacao tarefa a ser inutilizada |
||
335 | * @return bool se a inutilização foi realizada com sucesso |
||
336 | */ |
||
337 | 2 | public function inutiliza($inutilizacao) |
|
350 | |||
351 | /** |
||
352 | * Obtém as notas pendentes de autorização e envia para a SEFAZ |
||
353 | * @return int quantidade de tarefas e notas processadas |
||
354 | */ |
||
355 | 1 | public function processa() |
|
387 | } |
||
388 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: