Passed
Push — master ( f8305a...b6c7f7 )
by Roberto
03:01 queued 11s
created

DaCommon::printParameters()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
nc 8
nop 5
dl 0
loc 20
ccs 0
cts 20
cp 0
crap 42
rs 8.9777
c 0
b 0
f 0
1
<?php
2
3
namespace NFePHP\DA\Common;
4
5
use NFePHP\DA\Legacy\Common;
6
7
class DaCommon extends Common
8
{
9
10
    protected $debugmode;
11
    protected $orientacao = 'P';
12
    protected $force;
13
    protected $papel = 'A4';
14
    protected $margsup = 2;
15
    protected $margesq = 2;
16
    protected $wPrint;
17
    protected $hPrint;
18
    protected $xIni;
19
    protected $yIni;
20
    protected $maxH;
21
    protected $maxW;
22
    protected $fontePadrao = 'times';
23
    protected $aFont = ['font' => 'times', 'size' => 8, 'style' => ''];
24
    protected $creditos;
25
    protected $logomarca = '';
26
    protected $logotype = 'jpg';
27
28
    /**
29
     * Ativa ou desativa o modo debug
30
     *
31
     * @param bool $activate Ativa ou desativa o modo debug
32
     *
33
     * @return bool
34
     */
35
    public function debugMode($activate = null)
36
    {
37
        if (isset($activate) && is_bool($activate)) {
38
            $this->debugmode = $activate;
39
        }
40
        if ($this->debugmode) {
41
            //ativar modo debug
42
            error_reporting(E_ALL);
43
            ini_set('display_errors', 'On');
44
            set_error_handler(function (int $number, string $message, string $errfile, int $errline) {
45
                throw new \Exception("Handler captured error $number: '$message' $errfile [linha:" . $errline . "]");
46
            });
47
        } else {
48
            //desativar modo debug
49
            error_reporting(0);
50
            ini_set('display_errors', 'Off');
51
        }
52
        return $this->debugmode;
53
    }
54
    
55
    /**
56
     * Define parametros de impressão
57
     * @param string $orientacao
58
     * @param string $papel
59
     * @param int $margSup
60
     * @param int $margEsq
61
     */
62
    public function printParameters(
63
        $orientacao = 'P',
64
        $papel = 'A4',
65
        $margSup = null,
66
        $margEsq = null,
67
        $logoAlign = null
68
    ) {
69
        if ($orientação === 'P' || $orientacao === 'L') {
0 ignored issues
show
Bug introduced by
The variable $orientação does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
70
            $this->force = $orientacao;
71
        }
72
        $p = strtoupper($papel);
73
        if ($p == 'A4' || $p == 'LEGAL') {
74
            $this->papel = $papel;
75
        }
76
        $this->margsup = $margSup ?? 2;
77
        $this->margesq = $margEsq ?? 2;
78
        if (!empty($logoAlign)) {
79
            $this->logoAlign = $logoAlign;
0 ignored issues
show
Bug introduced by
The property logoAlign 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...
80
        }
81
    }
82
83
    /**
84
     * Renderiza o pdf e retorna como raw
85
     *
86
     * @return string
87
     */
88
    public function render(
89
        $logo = '',
90
        $depecNumReg = ''
91
    ) {
92
        if (empty($this->pdf)) {
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...
93
            $this->monta($logo, $depecNumReg);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class NFePHP\DA\Common\DaCommon as the method monta() does only exist in the following sub-classes of NFePHP\DA\Common\DaCommon: NFePHP\DA\BPe\Dabpe, NFePHP\DA\CTe\Dacte, NFePHP\DA\CTe\DacteOS, NFePHP\DA\CTe\Daevento, NFePHP\DA\MDFe\Damdfe, NFePHP\DA\NFe\Daevento, NFePHP\DA\NFe\Danfce, NFePHP\DA\NFe\Danfe. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

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

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
94
        }
95
        return $this->pdf->getPdf();
96
    }
97
98
    /**
99
     * Add the credits to the integrator in the footer message
100
     *
101
     * @param string $message Mensagem do integrador a ser impressa no rodapé das paginas
102
     *
103
     * @return void
104
     */
105
    public function creditsIntegratorFooter($message = '')
106
    {
107
        $this->creditos = trim($message);
108
    }
109
110
    /**
111
     *
112
     * @param string $font
113
     */
114
    public function setFontType(string $font = 'times')
115
    {
116
        $this->aFont['font'] = $font;
117
    }
118
119
    /**
120
     * Seta o tamanho da fonte
121
     *
122
     * @param int $size
123
     *
124
     * @return void
125
     */
126
    protected function setFontSize(int $size = 8)
127
    {
128
        $this->aFont['size'] = $size;
129
    }
130
131
    /**
132
     *
133
     * @param string $style
134
     */
135
    protected function setFontStyle(string $style = '')
136
    {
137
        $this->aFont['style'] = $style;
138
    }
139
140
    /**
141
     * Seta a orientação
142
     *
143
     * @param string $force
144
     * @param string $tpImp
145
     *
146
     * @return void
147
     */
148
    protected function setOrientationAndSize($force = null, $tpImp = null)
149
    {
150
        $this->orientacao = 'P';
151
        if (!empty($force)) {
152
            $this->orientacao = $force;
153
        } elseif (!empty($tpImp)) {
154
            if ($tpImp == '2') {
155
                $this->orientacao = 'L';
156
            } else {
157
                $this->orientacao = 'P';
158
            }
159
        }
160
        if (strtoupper($this->papel) == 'A4') {
161
            $this->maxW = 210;
162
            $this->maxH = 297;
163
        } else {
164
            $this->papel = 'legal';
165
            $this->maxW = 216;
166
            $this->maxH = 355;
167
        }
168
        if ($this->orientacao == 'L') {
169
            if (strtoupper($this->papel) == 'A4') {
170
                $this->maxH = 210;
171
                $this->maxW = 297;
172
            } else {
173
                $this->papel = 'legal';
174
                $this->maxH = 216;
175
                $this->maxW = 355;
176
            }
177
        }
178
        $this->wPrint = $this->maxW - $this->margesq * 2;
179
        $this->hPrint = $this->maxH - $this->margsup - 5;
180
    }
181
    
182
    protected function adjustImage($logo, $turn_bw = false)
183
    {
184
        if (substr($logo, 0, 24) !== 'data://text/plain;base64') {
185
            if (is_file($logo)) {
186
                $logo = 'data://text/plain;base64,'. base64_encode(file_get_contents($logo));
187
            } else {
188
                $logo = '';
189
            }
190
        }
191
        $logoInfo = getimagesize($logo);
192
        //1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order),
193
        //8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC,
194
        //14 = IFF, 15 = WBMP, 16 = XBM
195
        $type = $logoInfo[2];
196
        if ($type != '2' && $type != '3') {
197
            throw new Exception('O formato da imagem não é aceitável! Somente PNG ou JPG podem ser usados.');
198
        }
199
        if ($type == '3') { //3 = PNG
200
            $image = imagecreatefrompng($logo);
201
            if ($turn_bw) {
202
                imagefilter($image, IMG_FILTER_GRAYSCALE);
203
                //imagefilter($image, IMG_FILTER_CONTRAST, -100);
204
            }
205
            return $this->getImageStringFromObject($image);
206
        } elseif ($type == '2' && $turn_bw) {
207
            $image = imagecreatefromjpeg($logo);
208
            imagefilter($image, IMG_FILTER_GRAYSCALE);
209
            //imagefilter($image, IMG_FILTER_CONTRAST, -100);
210
            return $this->getImageStringFromObject($image);
211
        }
212
        return $logo;
213
    }
214
    
215
    private function getImageStringFromObject($image)
216
    {
217
        ob_start();
218
        imagejpeg($image, null, 100);
219
        imagedestroy($image);
220
        $logo = ob_get_contents(); // read from buffer
221
        ob_end_clean();
222
        return 'data://text/plain;base64,'.base64_encode($logo);
223
    }
224
}
225