Passed
Push — master ( f753cb...380f19 )
by Roberto
01:24
created

Common::pSimpleGetValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 5
dl 0
loc 19
ccs 0
cts 7
cp 0
crap 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace NFePHP\DA\Legacy;
4
5
class Common
6
{
7
    /**
8
     * pAdicionaLogoPeloCnpj
9
     *
10
     * @param  none
11
     * @return none
12
     */
13
    protected function pAdicionaLogoPeloCnpj()
14
    {
15
        if (!isset($this->logomarca)) {
16
            return;
17
        }
18
        if ($this->logomarca != '') {
0 ignored issues
show
Bug introduced by
The property logomarca 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...
19
            return;
20
        }
21
        if (!isset($this->emit)) {
22
            return;
23
        }
24
        //se não foi passado o caminho para o logo procurar diretorio abaixo
25
        $imgPath = "logos/" . $this->emit->getElementsByTagName("CNPJ")->item(0)->nodeValue . ".jpg";
0 ignored issues
show
Bug introduced by
The property emit 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...
26
        if (file_exists($imgPath)) {
27
            $this->logomarca = $imgPath;
28
            return;
29
        }
30
        //procurar diretorio acima do anterior
31
        $imgPath = "../" . $imgPath;
32
        if (file_exists($imgPath)) {
33
            $this->logomarca = $imgPath;
34
            return;
35
        }
36
        //procurar diretorio acima do anterior
37
        $imgPath = "../" . $imgPath;
38
        if (file_exists($imgPath)) {
39
            $this->logomarca = $imgPath;
40
            return;
41
        }
42
        //procurar diretorio acima do anterior
43
        $imgPath = "../" . $imgPath;
44
        if (file_exists($imgPath)) {
45
            $this->logomarca = $imgPath;
46
            return;
47
        }
48
    }
49
50
    /**
51
     * pSimpleGetValue
52
     * Extrai o valor do node DOM
53
     *
54
     * @param  object                                        $theObj          Instancia de DOMDocument ou DOMElement
55
     * @param  string                                        $keyName         identificador da TAG do xml
56
     * @param  string                                        $extraTextBefore prefixo do retorno
57
     * @param  string extraTextAfter sufixo do retorno
58
     * @param  number itemNum numero do item a ser retornado
59
     * @return string
60
     */
61
    protected function pSimpleGetValue($theObj, $keyName, $extraTextBefore = '', $extraTextAfter = '', $itemNum = 0)
62
    {
63
        if (empty($theObj)) {
64
            return '';
65
        }
66
        
67
        //if (!($theObj instanceof DOMDocument) && !($theObj instanceof DOMElement)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
68
        //    throw new nfephpException(
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
69
        //        "Metodo CommonNFePHP::pSimpleGetValue() "
70
        //        . "com parametro do objeto invalido, verifique!"
71
        //    );
72
        //}
73
        
74
        $vct = $theObj->getElementsByTagName($keyName)->item($itemNum);
75
        if (isset($vct)) {
76
            return $extraTextBefore . trim($vct->nodeValue) . $extraTextAfter;
77
        }
78
        return '';
79
    }
80
81
    /**
82
     * pSimpleGetDate
83
     * Recupera e reformata a data do padrão da NFe para dd/mm/aaaa
84
     *
85
     * @author Marcos Diez
86
     * @param  DOM    $theObj
87
     * @param  string $keyName   identificador da TAG do xml
88
     * @param  string $extraText prefixo do retorno
89
     * @return string
90
     */
91
    protected function pSimpleGetDate($theObj, $keyName, $extraText = '')
92
    {
93
        if (!isset($theObj) || !is_object($theObj)) {
94
            return '';
95
        }
96
        $vct = $theObj->getElementsByTagName($keyName)->item(0);
97
        if (isset($vct)) {
98
            $theDate = explode("-", $vct->nodeValue);
99
            return $extraText . $theDate[2] . "/" . $theDate[1] . "/" . $theDate[0];
100
        }
101
        return '';
102
    } //fim pSimpleGetDate
103
104
    /**
105
     * pModulo11
106
     *
107
     * @param  string $numero
108
     * @return integer modulo11 do numero passado
109
     */
110
    protected function pModulo11($numero = '')
111
    {
112
        if ($numero == '') {
113
            return '';
114
        }
115
        $numero = (string) $numero;
116
        $tamanho = strlen($numero);
117
        $soma = 0;
118
        $mult = 2;
119
        for ($i = $tamanho-1; $i >= 0; $i--) {
120
            $digito = (int) $numero[$i];
121
            $r = $digito * $mult;
122
            $soma += $r;
123
            $mult++;
124
            if ($mult == 10) {
125
                $mult = 2;
126
            }
127
        }
128
        $resto = ($soma * 10) % 11;
129
        return ($resto == 10 || $resto == 0) ? 1 : $resto;
130
    }
131
132
    /**
133
     * pYmd2dmy
134
     * Converte datas no formato YMD (ex. 2009-11-02) para o formato brasileiro 02/11/2009)
135
     *
136
     * @param  string $data Parâmetro extraido da NFe
137
     * @return string Formatada para apresentação da data no padrão brasileiro
138
     */
139 1
    protected function pYmd2dmy($data = '')
140
    {
141 1
        if ($data == '') {
142
            return '';
143
        }
144 1
        $needle = "/";
145 1
        if (strstr($data, "-")) {
146 1
            $needle = "-";
147
        }
148 1
        $dt = explode($needle, $data);
149 1
        return "$dt[2]/$dt[1]/$dt[0]";
150
    }
151
152
    /**
153
     * pConvertTime
154
     * Converte a informação de data e tempo contida na NFe
155
     *
156
     * @param  string $DH Informação de data e tempo extraida da NFe
157
     * @return timestamp UNIX Para uso com a funçao date do php
158
     */
159 1
    protected function pConvertTime($DH = '')
160
    {
161 1
        if ($DH == '') {
162 1
            return '';
163
        }
164 1
        $DH = str_replace('+', '-', $DH);
165 1
        $aDH = explode('T', $DH);
166 1
        $adDH = explode('-', $aDH[0]);
167 1
        if (count($aDH) > 1) {
168 1
            $inter = explode('-', $aDH[1]);
169 1
            $atDH = explode(':', $inter[0]);
170 1
            $timestampDH = mktime($atDH[0], $atDH[1], $atDH[2], $adDH[1], $adDH[2], $adDH[0]);
171
        } else {
172
            $timestampDH = mktime($month = $adDH[1], $day =  $adDH[2], $year = $adDH[0]);
173
        }
174 1
        return $timestampDH;
175
    }
176
177
    /**
178
     * pFormat
179
     * Função de formatação de strings onde o cerquilha # é um coringa
180
     * que será substituido por digitos contidos em campo.
181
     *
182
     * @param  string $campo   String a ser formatada
183
     * @param  string $mascara Regra de formatção da string (ex. ##.###.###/####-##)
184
     * @return string Retorna o campo formatado
185
     */
186 1
    protected function pFormat($campo = '', $mascara = '')
187
    {
188 1
        if ($campo == '' || $mascara == '') {
189
            return $campo;
190
        }
191
        //remove qualquer formatação que ainda exista
192 1
        $sLimpo = preg_replace("(/[' '-./ t]/)", '', $campo);
193
        // pega o tamanho da string e da mascara
194 1
        $tCampo = strlen($sLimpo);
195 1
        $tMask = strlen($mascara);
196 1
        if ($tCampo > $tMask) {
197 1
            $tMaior = $tCampo;
198
        } else {
199 1
            $tMaior = $tMask;
200
        }
201
        //contar o numero de cerquilhas da mascara
202 1
        $aMask = str_split($mascara);
203 1
        $z=0;
204 1
        $flag=false;
205 1
        foreach ($aMask as $letra) {
206 1
            if ($letra == '#') {
207 1
                $z++;
208
            }
209
        }
210 1
        if ($z > $tCampo) {
211
            //o campo é menor que esperado
212 1
            $flag=true;
213
        }
214
        //cria uma variável grande o suficiente para conter os dados
215 1
        $sRetorno = '';
216 1
        $sRetorno = str_pad($sRetorno, $tCampo+$tMask, " ", STR_PAD_LEFT);
217
        //pega o tamanho da string de retorno
218 1
        $tRetorno = strlen($sRetorno);
219
        //se houve entrada de dados
220 1
        if ($sLimpo != '' && $mascara !='') {
221
            //inicia com a posição do ultimo digito da mascara
222 1
            $x = $tMask;
223 1
            $y = $tCampo;
224 1
            $cI = 0;
225 1
            for ($i = $tMaior-1; $i >= 0; $i--) {
226 1
                if ($cI < $z) {
227
                    // e o digito da mascara é # trocar pelo digito do campo
228
                    // se o inicio da string da mascara for atingido antes de terminar
229
                    // o campo considerar #
230 1
                    if ($x > 0) {
231 1
                        $digMask = $mascara[--$x];
232
                    } else {
233
                        $digMask = '#';
234
                    }
235
                    //se o fim do campo for atingido antes do fim da mascara
236
                    //verificar se é ( se não for não use
237 1
                    if ($digMask=='#') {
238 1
                        $cI++;
239 1
                        if ($y > 0) {
240 1
                            $sRetorno[--$tRetorno] = $sLimpo[--$y];
241 1
                        } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
242
                            //$sRetorno[--$tRetorno] = '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
243
                        }
244
                    } else {
245 1
                        if ($y > 0) {
246 1
                            $sRetorno[--$tRetorno] = $mascara[$x];
247
                        } else {
248
                            if ($mascara[$x] =='(') {
249
                                $sRetorno[--$tRetorno] = $mascara[$x];
250
                            }
251
                        }
252 1
                        $i++;
253
                    }
254
                }
255
            }
256 1
            if (!$flag) {
257 1
                if ($mascara[0] != '#') {
258
                    $sRetorno = '(' . trim($sRetorno);
259
                }
260
            }
261 1
            return trim($sRetorno);
262
        } else {
263
            return '';
264
        }
265
    }
266
267
    /**
268
     * pGetNumLines
269
     * Obtem o numero de linhas usadas pelo texto usando a fonte especifidada
270
     *
271
     * @param  string $text
272
     * @param  number $width
273
     * @param  array  $aFont
274
     * @return number numero de linhas
275
     */
276
    protected function pGetNumLines($text, $width, $aFont = array('font'=>'Times','size'=>8,'style'=>''))
277
    {
278
        $text = trim($text);
279
        $this->pdf->SetFont($aFont['font'], $aFont['style'], $aFont['size']);
0 ignored issues
show
Bug introduced by
The property pdf 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...
280
        $n = $this->pdf->WordWrap($text, $width-0.2);
281
        return $n;
282
    }
283
284
285
    /**
286
     * pTextBox
287
     * Cria uma caixa de texto com ou sem bordas. Esta função perimite o alinhamento horizontal
288
     * ou vertical do texto dentro da caixa.
289
     * Atenção : Esta função é dependente de outras classes de FPDF
290
     * Ex. $this->pTextBox(2,20,34,8,'Texto',array('fonte'=>$this->fontePadrao,
291
     * 'size'=>10,'style='B'),'C','L',FALSE,'http://www.nfephp.org')
292
     *
293
     * @param  number  $x       Posição horizontal da caixa, canto esquerdo superior
294
     * @param  number  $y       Posição vertical da caixa, canto esquerdo superior
295
     * @param  number  $w       Largura da caixa
296
     * @param  number  $h       Altura da caixa
297
     * @param  string  $text    Conteúdo da caixa
298
     * @param  array   $aFont   Matriz com as informações para formatação do texto com fonte, tamanho e estilo
299
     * @param  string  $vAlign  Alinhamento vertical do texto, T-topo C-centro B-base
300
     * @param  string  $hAlign  Alinhamento horizontal do texto, L-esquerda, C-centro, R-direita
301
     * @param  boolean $border  TRUE ou 1 desenha a borda, FALSE ou 0 Sem borda
302
     * @param  string  $link    Insere um hiperlink
303
     * @param  boolean $force   Se for true força a caixa com uma unica linha e para isso atera o tamanho do
304
     * fonte até caber no espaço, se falso mantem o tamanho do fonte e usa quantas linhas forem necessárias
305
     * e para isso atera o tamanho do fonte até caber no espaço,
306
     * se falso mantem o tamanho do fonte e usa quantas linhas forem necessárias
307
     * @param  number  $hmax
308
     * @param  number  $vOffSet incremento forçado na na posição Y
309
     * @return number $height Qual a altura necessária para desenhar esta textBox
310
     */
311 1
    protected function pTextBox(
312
        $x,
313
        $y,
314
        $w,
315
        $h,
316
        $text = '',
317
        $aFont = array('font'=>'Times','size'=>8,'style'=>''),
318
        $vAlign = 'T',
319
        $hAlign = 'L',
320
        $border = 1,
321
        $link = '',
0 ignored issues
show
Unused Code introduced by
The parameter $link is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
322
        $force = true,
323
        $hmax = 0,
324
        $vOffSet = 0
325
    ) {
326 1
        $oldY = $y;
327 1
        $temObs = false;
0 ignored issues
show
Unused Code introduced by
$temObs 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...
328 1
        $resetou = false;
329 1
        if ($w < 0) {
330
            return $y;
331
        }
332 1
        if (is_object($text)) {
333
            $text = '';
334
        }
335 1
        if (is_string($text)) {
336
            //remover espaços desnecessários
337 1
            $text = trim($text);
338
            //converter o charset para o fpdf
339 1
            $text = utf8_decode($text);
340
        } else {
341
            $text = (string) $text;
342
        }
343
        //desenhar a borda da caixa
344 1
        if ($border) {
345 1
            $this->pdf->RoundedRect($x, $y, $w, $h, 0.8, '1234', 'D');
346
        }
347
        //estabelecer o fonte
348 1
        $this->pdf->SetFont($aFont['font'], $aFont['style'], $aFont['size']);
349
        //calcular o incremento
350 1
        $incY = $this->pdf->fontSize; //tamanho da fonte na unidade definida
351 1
        if (!$force) {
352
            //verificar se o texto cabe no espaço
353 1
            $n = $this->pdf->WordWrap($text, $w);
354
        } else {
355 1
            $n = 1;
356
        }
357
        //calcular a altura do conjunto de texto
358 1
        $altText = $incY * $n;
359
        //separar o texto em linhas
360 1
        $lines = explode("\n", $text);
361
        //verificar o alinhamento vertical
362 1
        if ($vAlign == 'T') {
363
            //alinhado ao topo
364 1
            $y1 = $y+$incY;
365
        }
366 1
        if ($vAlign == 'C') {
367
            //alinhado ao centro
368 1
            $y1 = $y + $incY + (($h-$altText)/2);
369
        }
370 1
        if ($vAlign == 'B') {
371
            //alinhado a base
372
            $y1 = ($y + $h)-0.5;
373
        }
374
        //para cada linha
375 1
        foreach ($lines as $line) {
376
            //verificar o comprimento da frase
377 1
            $texto = trim($line);
378 1
            $comp = $this->pdf->getStringWidth($texto);
379 1
            if ($force) {
380 1
                $newSize = $aFont['size'];
381 1
                while ($comp > $w) {
382
                    //estabelecer novo fonte
383
                    $this->pdf->SetFont($aFont['font'], $aFont['style'], --$newSize);
384
                    $comp = $this->pdf->getStringWidth($texto);
385
                }
386
            }
387
            //ajustar ao alinhamento horizontal
388 1
            if ($hAlign == 'L') {
389 1
                $x1 = $x+0.5;
390
            }
391 1
            if ($hAlign == 'C') {
392 1
                $x1 = $x + (($w - $comp)/2);
393
            }
394 1
            if ($hAlign == 'R') {
395
                $x1 = $x + $w - ($comp+0.5);
396
            }
397
            //escrever o texto
398 1
            if ($vOffSet > 0) {
399
                if ($y1 > ($oldY+$vOffSet)) {
400
                    if (!$resetou) {
401
                        $y1 = $oldY;
402
                        $resetou = true;
403
                    }
404
                    $this->pdf->Text($x1, $y1, $texto);
0 ignored issues
show
Bug introduced by
The variable $x1 does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $y1 does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
405
                }
406
            } else {
407 1
                $this->pdf->Text($x1, $y1, $texto);
408
            }
409
            //incrementar para escrever o proximo
410 1
            $y1 += $incY;
411 1
            if (($hmax > 0) && ($y1 > ($y+($hmax-1)))) {
412
                $temObs = true;
0 ignored issues
show
Unused Code introduced by
$temObs 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...
413 1
                break;
414
            }
415
        }
416 1
        return ($y1-$y)-$incY;
417
    } // fim função __textBox
418
419
    /**
420
     * pTextBox90
421
     * Cria uma caixa de texto com ou sem bordas. Esta função permite o alinhamento horizontal
422
     * ou vertical do texto dentro da caixa, rotacionando-o em 90 graus, essa função precisa que
423
     * a classe PDF contenha a função Rotate($angle,$x,$y);
424
     * Atenção : Esta função é dependente de outras classes de FPDF
425
     * Ex. $this->__textBox90(2,20,34,8,'Texto',array('fonte'=>$this->fontePadrao,
426
     * 'size'=>10,'style='B'),'C','L',FALSE,'http://www.nfephp.org')
427
     *
428
     * @param  number  $x       Posição horizontal da caixa, canto esquerdo superior
429
     * @param  number  $y       Posição vertical da caixa, canto esquerdo superior
430
     * @param  number  $w       Largura da caixa
431
     * @param  number  $h       Altura da caixa
432
     * @param  string  $text    Conteúdo da caixa
433
     * @param  array   $aFont   Matriz com as informações para formatação do texto com fonte, tamanho e estilo
434
     * @param  string  $vAlign  Alinhamento vertical do texto, T-topo C-centro B-base
435
     * @param  string  $hAlign  Alinhamento horizontal do texto, L-esquerda, C-centro, R-direita
436
     * @param  boolean $border  TRUE ou 1 desenha a borda, FALSE ou 0 Sem borda
437
     * @param  string  $link    Insere um hiperlink
438
     * @param  boolean $force   Se for true força a caixa com uma unica linha e para isso atera o tamanho do
439
     *  fonte até caber no espaço, se falso mantem o tamanho do fonte e usa quantas linhas forem necessárias
440
     * linha e para isso atera o tamanho do fonte até caber no espaço,
441
     * se falso mantem o tamanho do fonte e usa quantas linhas forem necessárias
442
     * @param  number  $hmax
443
     * @param  number  $vOffSet incremento forçado na na posição Y
444
     * @return number $height Qual a altura necessária para desenhar esta textBox
445
     */
446
    protected function pTextBox90(
447
        $x,
448
        $y,
449
        $w,
450
        $h,
451
        $text = '',
452
        $aFont = array('font'=>'Times','size'=>8,'style'=>''),
453
        $vAlign = 'T',
454
        $hAlign = 'L',
455
        $border = 1,
456
        $link = '',
0 ignored issues
show
Unused Code introduced by
The parameter $link is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
457
        $force = true,
458
        $hmax = 0,
459
        $vOffSet = 0
460
    ) {
461
        //Rotacionado
462
        $this->pdf->Rotate(90, $x, $y);
463
        $oldY = $y;
464
        $temObs = false;
0 ignored issues
show
Unused Code introduced by
$temObs 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...
465
        $resetou = false;
466
        if ($w < 0) {
467
            return $y;
468
        }
469
        if (is_object($text)) {
470
            $text = '';
471
        }
472
        if (is_string($text)) {
473
            //remover espaços desnecessários
474
            $text = trim($text);
475
            //converter o charset para o fpdf
476
            $text = utf8_decode($text);
477
        } else {
478
            $text = (string) $text;
479
        }
480
        //desenhar a borda da caixa
481
        if ($border) {
482
            $this->pdf->RoundedRect($x, $y, $w, $h, 0.8, '1234', 'D');
483
        }
484
        //estabelecer o fonte
485
        $this->pdf->SetFont($aFont['font'], $aFont['style'], $aFont['size']);
486
        //calcular o incremento
487
        $incY = $this->pdf->fontSize; //tamanho da fonte na unidade definida
488
        if (!$force) {
489
            //verificar se o texto cabe no espaço
490
            $n = $this->pdf->WordWrap($text, $w);
491
        } else {
492
            $n = 1;
493
        }
494
        //calcular a altura do conjunto de texto
495
        $altText = $incY * $n;
496
        //separar o texto em linhas
497
        $lines = explode("\n", $text);
498
        //verificar o alinhamento vertical
499
        if ($vAlign == 'T') {
500
            //alinhado ao topo
501
            $y1 = $y+$incY;
502
        }
503
        if ($vAlign == 'C') {
504
            //alinhado ao centro
505
            $y1 = $y + $incY + (($h-$altText)/2);
506
        }
507
        if ($vAlign == 'B') {
508
            //alinhado a base
509
            $y1 = ($y + $h)-0.5;
510
        }
511
        //para cada linha
512
        foreach ($lines as $line) {
513
            //verificar o comprimento da frase
514
            $texto = trim($line);
515
            $comp = $this->pdf->GetStringWidth($texto);
516
            if ($force) {
517
                $newSize = $aFont['size'];
518
                while ($comp > $w) {
519
                    //estabelecer novo fonte
520
                    $this->pdf->SetFont($aFont['font'], $aFont['style'], --$newSize);
521
                    $comp = $this->pdf->GetStringWidth($texto);
522
                }
523
            }
524
            //ajustar ao alinhamento horizontal
525
            if ($hAlign == 'L') {
526
                $x1 = $x+0.5;
527
            }
528
            if ($hAlign == 'C') {
529
                $x1 = $x + (($w - $comp)/2);
530
            }
531
            if ($hAlign == 'R') {
532
                $x1 = $x + $w - ($comp+0.5);
533
            }
534
            //escrever o texto
535
            if ($vOffSet > 0) {
536
                if ($y1 > ($oldY+$vOffSet)) {
537
                    if (!$resetou) {
538
                        $y1 = $oldY;
539
                        $resetou = true;
540
                    }
541
                    $this->pdf->Text($x1, $y1, $texto);
0 ignored issues
show
Bug introduced by
The variable $x1 does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $y1 does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
542
                }
543
            } else {
544
                $this->pdf->Text($x1, $y1, $texto);
545
            }
546
            //incrementar para escrever o proximo
547
            $y1 += $incY;
548
            if (($hmax > 0) && ($y1 > ($y+($hmax-1)))) {
549
                $temObs = true;
0 ignored issues
show
Unused Code introduced by
$temObs 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...
550
                break;
551
            }
552
        }
553
        //Zerando rotação
554
        $this->pdf->Rotate(0, $x, $y);
555
        return ($y1-$y)-$incY;
556
    }
557
}
558