Passed
Push — master ( d65fb2...07d9b9 )
by Roberto
05:56 queued 03:13
created

Danfce::setFont()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 8
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace NFePHP\DA\NFe;
4
5
/**
6
 * Classe para a impressão em PDF do Documento Auxiliar de NFe Consumidor
7
 * NOTA: Esta classe não é a indicada para quem faz uso de impressoras térmicas ESCPOS
8
 *
9
 * @category  Library
10
 * @package   nfephp-org/sped-da
11
 * @copyright 2009-2020 NFePHP
12
 * @license   http://www.gnu.org/licenses/lesser.html LGPL v3
13
 * @link      http://github.com/nfephp-org/sped-da for the canonical source repository
14
 */
15
16
use DateTime;
17
use Exception;
18
use InvalidArgumentException;
19
use NFePHP\DA\Legacy\Dom;
20
use NFePHP\DA\Legacy\Pdf;
21
use NFePHP\DA\Common\DaCommon;
22
use Com\Tecnick\Barcode\Barcode;
23
24
class Danfce extends DaCommon
25
{
26
    protected $papel;
27
    protected $paperwidth = 80;
28
    protected $descPercent = 0.38;
29
    protected $xml; // string XML NFe
30
    protected $logomarca=''; // path para logomarca em jpg
31
    protected $formatoChave="#### #### #### #### #### #### #### #### #### #### ####";
32
    protected $nfeProc;
33
    protected $nfe;
34
    protected $infNFe;
35
    protected $ide;
36
    protected $enderDest;
37
    protected $ICMSTot;
38
    protected $imposto;
39
    protected $emit;
40
    protected $enderEmit;
41
    protected $qrCode;
42
    protected $urlChave;
43
    protected $det;
44
    protected $infAdic;
45
    protected $textoAdic;
46
    protected $tpEmis;
47
    protected $pag;
48
    protected $vTroco;
49
    protected $itens = [];
50
    protected $dest;
51
    protected $imgQRCode;
52
    protected $urlQR = '';
53
    protected $pdf;
54
    protected $margem = 2;
55
    protected $flagResume = false;
56
    protected $hMaxLinha = 5;
57
    protected $hBoxLinha = 6;
58
    protected $hLinha = 3;
59
    protected $aFontTit = ['font' => 'times', 'size' => 9, 'style' => 'B'];
60
    protected $aFontTex = ['font' => 'times', 'size' => 8, 'style' => ''];
61
    protected $via = "Via Consumidor";
62
    protected $canceled = false;
63
64
65
    protected $bloco1H = 18; //cabecalho
66
    protected $bloco2H = 12; //informação fiscal
67
    
68
    protected $bloco3H = 0; //itens
69
    protected $bloco4H = 13; //totais
70
    protected $bloco5H = 0; //formas de pagamento
71
    
72
    protected $bloco6H = 10; //informação para consulta
73
    protected $bloco7H = 20; //informações do consumidor
74
    protected $bloco8H = 50; //informações do consumidor
75
    protected $bloco9H = 4; //informações sobre tributos
76
    protected $bloco10H = 5; //informações do integrador
77
78
    use Traits\TraitBlocoI;
79
    use Traits\TraitBlocoII;
80
    use Traits\TraitBlocoIII;
81
    use Traits\TraitBlocoIV;
82
    use Traits\TraitBlocoV;
83
    use Traits\TraitBlocoVI;
84
    use Traits\TraitBlocoVII;
85
    use Traits\TraitBlocoVIII;
86
    use Traits\TraitBlocoIX;
87
    use Traits\TraitBlocoX;
88
89
    /**
90
     * Construtor
91
     *
92
     * @param string $xml
93
     *
94
     * @throws Exception
95
     */
96
    public function __construct($xml)
97
    {
98
        $this->xml = $xml;
99
        if (empty($xml)) {
100
            throw new \Exception('Um xml de NFCe deve ser passado ao construtor da classe.');
101
        }
102
        //carrega dados do xml
103
        $this->loadXml();
104
    }
105
106
    /**
107
     * Seta a largura do papel de impressão em mm
108
     *
109
     * @param int $width
110
     */
111
    public function setPaperWidth($width = 80)
112
    {
113
        if ($width < 58) {
114
            throw new Exception("Largura insuficiente para a impressão do documento");
115
        }
116
        $this->paperwidth = $width;
117
    }
118
119
    /**
120
     * Seta margens de impressão em mm
121
     *
122
     * @param int $width
123
     */
124
    public function setMargins($width = 2)
125
    {
126
        if ($width > 4 || $width < 0) {
127
            throw new Exception("As margens devem estar entre 0 e 4 mm.");
128
        }
129
        $this->margem = $width;
130
    }
131
132
    /**
133
     * Seta a fonte a ser usada times ou arial
134
     *
135
     * @param string $font
136
     */
137
    public function setFont($font = 'times')
138
    {
139
        if (!in_array($font, ['times', 'arial'])) {
140
            $this->fontePadrao = 'times';
141
        } else {
142
            $this->fontePadrao = $font;
143
        }
144
    }
145
    
146
    /**
147
     * Seta a impressão para NFCe completa ou Simplificada
148
     *
149
     * @param bool $flag
150
     */
151
    public function setPrintResume($flag = false)
152
    {
153
        $this->flagResume = $flag;
154
    }
155
    
156
    public function setAsCanceled()
157
    {
158
        $this->canceled = true;
159
    }
160
161
    public function render($logo = '')
162
    {
163
        $this->monta($logo);
164
        //$this->papel = 80;
165
        return $this->pdf->getPdf();
166
    }
167
168
    protected function monta(
169
        $logo = ''
170
    ) {
171
        if (!empty($logo)) {
172
            $this->logomarca = $this->adjustImage($logo, true);
173
        }
174
        $tamPapelVert = $this->calculatePaperLength();
175
        $this->orientacao = 'P';
176
        $this->papel = [$this->paperwidth, $tamPapelVert];
177
        $this->logoAlign = 'L';
178
        $this->pdf = new Pdf($this->orientacao, 'mm', $this->papel);
0 ignored issues
show
Documentation introduced by
$this->papel is of type array<integer,integer|do...integer","1":"double"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
179
180
        //margens do PDF, em milímetros. Obs.: a margem direita é sempre igual à
181
        //margem esquerda. A margem inferior *não* existe na FPDF, é definida aqui
182
        //apenas para controle se necessário ser maior do que a margem superior
183
        $margSup = $this->margem;
184
        $margEsq = $this->margem;
185
        $margInf = $this->margem;
186
        // posição inicial do conteúdo, a partir do canto superior esquerdo da página
187
        $xInic = $margEsq;
0 ignored issues
show
Unused Code introduced by
$xInic is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
188
        $yInic = $margSup;
0 ignored issues
show
Unused Code introduced by
$yInic is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
189
        $maxW = $this->paperwidth;
190
        $maxH = $tamPapelVert;
191
        //total inicial de paginas
192
        $totPag = 1;
0 ignored issues
show
Unused Code introduced by
$totPag is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
193
        //largura imprimivel em mm: largura da folha menos as margens esq/direita
194
        $this->wPrint = $maxW-($margEsq*2);
0 ignored issues
show
Documentation Bug introduced by
The property $wPrint was declared of type double, but $maxW - $margEsq * 2 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
195
        //comprimento (altura) imprimivel em mm: altura da folha menos as margens
196
        //superior e inferior
197
        $this->hPrint = $maxH-$margSup-$margInf;
198
        // estabelece contagem de paginas
199
        $this->pdf->aliasNbPages();
200
        $this->pdf->setMargins($margEsq, $margSup); // fixa as margens
201
        $this->pdf->setDrawColor(0, 0, 0);
202
        $this->pdf->setFillColor(255, 255, 255);
203
        $this->pdf->open(); // inicia o documento
204
        $this->pdf->addPage($this->orientacao, $this->papel); // adiciona a primeira página
0 ignored issues
show
Documentation introduced by
$this->papel is of type array<integer,integer|do...integer","1":"double"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
205
        $this->pdf->setLineWidth(0.1); // define a largura da linha
206
        $this->pdf->setTextColor(0, 0, 0);
207
208
        $y = $this->blocoI(); //cabecalho
209
        $y = $this->blocoII($y); //informação cabeçalho fiscal e contingência
210
        
211
        $y = $this->blocoIII($y); //informação dos itens
212
        $y = $this->blocoIV($y); //informação sobre os totais
213
        $y = $this->blocoV($y); //informação sobre pagamento
214
        
215
        $y = $this->blocoVI($y); //informações sobre consulta pela chave
216
        $y = $this->blocoVII($y); //informações sobre o consumidor e dados da NFCe
217
        $y = $this->blocoVIII($y); //QRCODE
218
        $y = $this->blocoIX($y); //informações sobre tributos
219
        $y = $this->blocoX($y); //creditos
0 ignored issues
show
Unused Code introduced by
$y is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
220
        
221
        if ($this->tpAmb == 2) {
0 ignored issues
show
Bug introduced by
The property tpAmb does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
222
            $this->pdf->setTextColor(120, 120, 120);
223
            $texto = "SEM VALOR FISCAL\nEmitida em ambiente de homologacao";
224
            $aFont = ['font' => $this->fontePadrao, 'size' => 20, 'style' => 'B'];
225
            $this->pdf->textBox(
226
                $this->margem,
227
                ($maxH/3),
228
                $this->wPrint,
229
                $maxH/2,
230
                $texto,
231
                $aFont,
232
                'T',
233
                'C',
234
                false,
235
                '',
236
                false
237
            );
238
            $this->pdf->setTextColor(0, 0, 0);
239
        } elseif ($this->canceled) {
240
            $this->pdf->setTextColor(120, 120, 120);
241
            $texto = "CANCELADA";
242
            $aFont = ['font' => $this->fontePadrao, 'size' => 20, 'style' => 'B'];
243
            $this->pdf->textBox(
244
                $this->margem,
245
                ($maxH/3),
246
                $this->wPrint,
247
                $maxH/2,
248
                $texto,
249
                $aFont,
250
                'T',
251
                'C',
252
                false,
253
                '',
254
                false
255
            );
256
            $this->pdf->setTextColor(0, 0, 0);
257
        }
258
    }
259
260
261
    private function calculatePaperLength()
262
    {
263
        $wprint = $this->paperwidth - (2 * $this->margem);
264
        $this->bloco3H = $this->calculateHeightItens($wprint * $this->descPercent);
265
        $this->bloco5H = $this->calculateHeightPag();
0 ignored issues
show
Documentation Bug introduced by
The property $bloco5H was declared of type integer, but $this->calculateHeightPag() is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
266
        
267
        $length = $this->bloco1H //cabecalho
268
            + $this->bloco2H //informação fiscal
269
            + $this->bloco3H //itens
270
            + $this->bloco4H //totais
271
            + $this->bloco5H //formas de pagamento
272
            + $this->bloco6H //informação para consulta
273
            + $this->bloco7H //informações do consumidor
274
            + $this->bloco8H //qrcode
275
            + $this->bloco9H //informações sobre tributos
276
            + $this->bloco10H; //informações do integrador
277
        return $length;
278
    }
279
280
    /**
281
     * Carrega os dados do xml na classe
282
     * @param string $xml
0 ignored issues
show
Bug introduced by
There is no parameter named $xml. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
283
     *
284
     * @throws InvalidArgumentException
285
     */
286
    private function loadXml()
287
    {
288
        $this->dom = new Dom();
0 ignored issues
show
Bug introduced by
The property dom does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
289
        $this->dom->loadXML($this->xml);
290
        $this->ide = $this->dom->getElementsByTagName("ide")->item(0);
291
        $mod = $this->getTagValue($this->ide, "mod");
0 ignored issues
show
Unused Code introduced by
$mod is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
292
        if ($this->getTagValue($this->ide, "mod") != '65') {
293
            throw new \Exception("O xml do DANFE deve ser uma NFC-e modelo 65");
294
        }
295
        $this->tpAmb = $this->getTagValue($this->ide, 'tpAmb');
296
        $this->nfeProc = $this->dom->getElementsByTagName("nfeProc")->item(0) ?? null;
297
        $this->infProt = $this->dom->getElementsByTagName("infProt")->item(0) ?? null;
0 ignored issues
show
Bug introduced by
The property infProt does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
298
        $this->nfe = $this->dom->getElementsByTagName("NFe")->item(0);
299
        $this->infNFe = $this->dom->getElementsByTagName("infNFe")->item(0);
300
        $this->emit = $this->dom->getElementsByTagName("emit")->item(0);
301
        $this->enderEmit = $this->dom->getElementsByTagName("enderEmit")->item(0);
302
        $this->det = $this->dom->getElementsByTagName("det");
303
        $this->dest = $this->dom->getElementsByTagName("dest")->item(0);
304
        $this->enderDest = $this->dom->getElementsByTagName("enderDest")->item(0);
305
        $this->imposto = $this->dom->getElementsByTagName("imposto")->item(0);
306
        $this->ICMSTot = $this->dom->getElementsByTagName("ICMSTot")->item(0);
307
        $this->tpImp = $this->ide->getElementsByTagName("tpImp")->item(0)->nodeValue;
0 ignored issues
show
Bug introduced by
The property tpImp does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
308
        $this->infAdic = $this->dom->getElementsByTagName("infAdic")->item(0);
309
        $this->tpEmis = $this->dom->getValue($this->ide, "tpEmis");
0 ignored issues
show
Documentation introduced by
$this->ide is of type object<DOMNode>, but the function expects a object<NFePHP\DA\Legacy\DOMElement>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
310
        //se for o layout 4.0 busca pelas tags de detalhe do pagamento
311
        //senão, busca pelas tags de pagamento principal
312
        if ($this->infNFe->getAttribute("versao") == "4.00") {
313
            $this->pag = $this->dom->getElementsByTagName("detPag");
314
            $tagPag = $this->dom->getElementsByTagName("pag")->item(0);
315
            $this->vTroco = $this->getTagValue($tagPag, "vTroco");
316
        } else {
317
            $this->pag = $this->dom->getElementsByTagName("pag");
318
        }
319
        $this->qrCode = !empty($this->dom->getElementsByTagName('qrCode')->item(0)->nodeValue)
320
            ? $this->dom->getElementsByTagName('qrCode')->item(0)->nodeValue : null;
321
        $this->urlChave = !empty($this->dom->getElementsByTagName('urlChave')->item(0)->nodeValue)
322
            ? $this->dom->getElementsByTagName('urlChave')->item(0)->nodeValue : null;
323
        if (!empty($this->infProt)) {
324
            $cStat = $this->getTagValue($this->infProt, 'cStat');
325
            if ($cStat != 100) {
326
                $this->canceled = true;
327
            }
328
        }
329
    }
330
}
331