-1
Talk guys, it’s okay?
I am developing a note sending system, but as we learn something new every day I came across the following doubt:
I have a closure that treats some settings before calling the sending of the invoice in my system, but studying more deeply some tools I arrived at the magic method __invoke
.
Let me give you a practical example(I will use an example code in both situations):
Example of configuration array:
$conf['modeloNota'] = "55"; //65 ou 55
$conf['ambiente'] = 1 ; //Homologação ou Produção
closure
$ret = function ($idcliente) use ($conf) {
if(isset($conf['modeloNota']) && $conf['modeloNota'] == "65") {
//Aqui vai a chamada da função para o envio da nota modelo 65
$retorno = strtoupper('nfce');
}else if(isset($conf['modeloNota']) && $conf['modeloNota'] == "55"){
//Aqui vai a chamada da função para o envio da nota modelo 55
$retorno = strtoupper('nfe');
}else{
$retorno = "Modelo de nota não definido";
}
return $retorno;
};
Using the magic method invoke
, I came up with something like this:
class EnvioNota {
public function __invoke($idcliente ,$conf) {
if(isset($conf['modeloNota']) && $conf['modeloNota'] == "65") {
$retorno = strtoupper('nfce');
}else if(isset($conf['modeloNota']) && $conf['modeloNota'] == "55"){
$retorno = strtoupper('nfe');
}
echo $retorno;
}
}
$envio = new EnvioNota();
$envio(5, $conf);
The two work as expected, but what’s puzzling me is:
Which of the two methods is best considered when it comes to good programming practices?
About functions that require more amount of code it is recommended to use some of these approaches?
Is there any other way to create the same functions using other types of anonymous functions?
Edit:
Here is a real example: I have the following function within my Method class:
$retornoLote = function ($empresa) use ($request){
$chavenfce = $request->get('xml');
$xmlAssinado = file_get_contents(storage_path('app/notas/'. preg_replace("/[^0-9]/", "", $empresa->cnpj) . '/' . date('mY') . '/assinadas/' . $request->get('xml').'.xml'));
$config = [
"atualizacao" => "2018-02-06 06:01:21",
"tpAmb" => 2, // como 2 você emitirá a nota em ambiente de homologação(teste) e as notas fiscais aqui não tem valor fiscal
"razaosocial" => $empresa->razaosocial,
"siglaUF" => $empresa->endereco->uf,
"cnpj" => MetodosNF::limpaMascaraCnpjCpf($empresa->cnpj),
// "schemes" => "PL_008i2",
"schemes" => "PL_009_V4",
// "versao" => "3.10",
"versao" => "4.00",
"tokenIBPT" => "AAAAAAA",
"CSC" => $empresa->nfcecsc1,
"CSCid" => $empresa->nfceidtoken1,
];
$configJson = json_encode($config);
$filename = preg_replace("/[^0-9]/", "", $empresa->cnpj) . '.pfx';
$certificadoDigital = file_get_contents(public_path() . '/certificados/' . $filename);
$tools = new \NFePHP\NFe\Tools($configJson, \NFePHP\Common\Certificate::readPfx($certificadoDigital, '1234'));
$tools->model(65);
try {
$idLote = str_pad(100, 15, '0', STR_PAD_LEFT); // Identificador do lote
$resp = $tools->sefazEnviaLote([$xmlAssinado], $idLote);
$st = new \NFePHP\NFe\Common\Standardize();
$std = $st->toStd($resp);
if ($std->cStat != 103) {
//erro registrar e voltar
return array('status'=>1, 'mensagem'=>"[$std->cStat] $std->xMotivo");
}
$recibo = $std->infRec->nRec; // Vamos usar a variável $recibo para consultar o status da nota
} catch (\Exception $e) {
//aqui você trata possiveis exceptions do envio
return array('status'=>1, 'mensagem'=>$e->getMessage());
}
//Salvar o XML no backup
Storage::put('notas/'. MetodosNF::limpaMascaraCnpjCpf($empresa->cnpj) . '/' . date('mY') . '/retornoLote/' . $request->get('xml') .'.txt', "[$std->cStat] $std->xMotivo");
try {
$protocolo = $tools->sefazConsultaRecibo($recibo);
} catch (\Exception $e) {
//aqui você trata possíveis exceptions da consulta
return array('status'=>1, 'mensagem'=>$e->getMessage());
}
try {
$protocol = new \NFePHP\NFe\Factories\Protocol();
$xmlProtocolado = $protocol->add($xmlAssinado,$protocolo);
} catch (\Exception $e) {
//aqui você trata possíveis exceptions ao adicionar protocolo
return array('status'=>1, 'mensagem'=>$e->getMessage());
}
//Salvar o XML no backup
Storage::put('notas/'. MetodosNF::limpaMascaraCnpjCpf($empresa->cnpj) . '/' . date('mY') . '/' . $chavenfce.'.xml', $xmlProtocolado);
//Verifica o logo
//Só funciona se for jpg
if(file_exists(public_path() . '/images/empresa' . \Auth::user()->idglobal .'.jpg')){
$imagem = asset('images/empresa'. \Auth::user()->idglobal .'.jpg');
}else{
$imagem = "";
}
//Montagem do PDF
$docxml = $xmlProtocolado;
$pathLogo = $imagem;
$danfce = new Danfce($docxml, $pathLogo, 0);
$id = $danfce->monta();
$pdf = $danfce->render();
Storage::put('notas/' . MetodosNF::limpaMascaraCnpjCpf($empresa->cnpj) . '/' . $chavenfce.'.pdf', $pdf);
return array('status'=>200, 'url'=>$chavenfce);
}
I thought I’d create a new class and reprogram this code fragment by throwing it into a class retornoLote
, I’m studying a way to make this more "simple" and readable.
The issue issue that now may be different from the original, I responded based on what I was asking before. Wallace also. Although analyzing better nor occurred, it just doesn’t make sense in the question.
– Maniero
You are complicating something that is simpler, is encapsulating functions, and worsening the reading, the big problem of questions like this is because the scenario we can never see and automatically understand, perhaps, make as simple as possible, is much better.
– novic