Completed
Push — master ( 6c638d...8dc2ed )
by Roberto
08:46 queued 06:45
created

Bematech::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Posprint\Printers;
4
5
/**
6
 * Bematech class for POS printer
7
 * Model: MP 4200TH
8
 *
9
 * @category   NFePHP
10
 * @package    Posprint
11
 * @copyright  Copyright (c) 2016
12
 * @license    http://www.gnu.org/licenses/lesser.html LGPL v3
13
 * @author     Roberto L. Machado <linux.rlm at gmail dot com>
14
 * @link       http://github.com/nfephp-org/posprint for the canonical source repository
15
 */
16
17
use Posprint\Printers\DefaultPrinter;
18
use Posprint\Printers\PrinterInterface;
19
20
final class Bematech extends DefaultPrinter implements PrinterInterface
21
{
22
    
23
    
24
    /**
25
     * List all available code pages.
26
     *
27
     * @var array
28
     */
29
    protected $aCodePage = array(
30
        'CP437' => array('conv' => '437', 'table' => '3', 'desc' => 'PC437: USA, Standard Europe'),
31
        'CP850' => array('conv' => '850', 'table' => '2', 'desc' => 'PC850: Multilingual'),
32
        'CP858' => array('conv' => '858', 'table' => '5', 'desc' => 'PC858: Multilingual'),
33
        'CP860' => array('conv' => '860', 'table' => '4', 'desc' => 'PC860: Portuguese'),
34
        'CP864' => array('conv' => '864', 'table' => '7', 'desc' => 'PC864: Arabic'),
35
        'CP866' => array('conv' => '866', 'table' => '6', 'desc' => 'PC866: Cyrillic'),
36
        'UTF8'  => array('conv' => 'UTF8', 'table' => '8', 'desc' => 'UTF-8: Unicode')
37
    );
38
    
39
    /**
40
     * List all avaiable fonts
41
     *
42
     * @var array
43
     */
44
    protected $aFont = array(0 => 'C', 1 => 'D');
45
    
46
    
47 1
    public function __construct(ConnectorInterface $conn = null)
48
    {
49 1
        parent::__construct($conn);
50
        
51 1
    }
52
53
    /**
54
     * initialize printer
55
     * Clears the data in the print buffer and resets the printer modes to
56
     * the modes that were in effect when the power was turned on.
57
     */
58
    public function initialize()
59
    {
60
        parent::initialize();
61
        $this->setCodePage('CP850');
62
        $this->setPrintMode('ESCPOS');
63
        $this->setRegionPage('LATIN');
64
        //clear Emphasized, Double height, Double width and select font C
65
        $this->defaultFont('C');
66
        $this->buffer->write(self::ESC . '!' . chr(1));
67
    }
68
    
69
    /**
70
     * Select printer mode and code page to 850
71
     *
72
     * @param string $mode
73
     */
74
    public function setPrintMode($mode = 'ESCPOS')
75
    {
76
        //default ESC/POS
77
        $this->printerMode = 'ESCPOS';
78
        if ($mode == 'ESCBEMA') {
79
            $this->printerMode = 'ESCBEMA';
80
        }
81
        //select mode ESCPOS or ESCBEMA
82
        $this->buffer->write(self::GS . chr(249) . chr(32) . $nmode);
0 ignored issues
show
Bug introduced by
The variable $nmode 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...
83
    }
84
    
85
    /**
86
     * Set expanded mode.
87
     *
88
     * @param int $size qualquer valor ativa e null desativa
89
     */
90
    public function setExpanded($size = null)
91
    {
92
        $mode = array_keys($this->aFont, $this->font, true);
93
        if ($this->boldMode) {
94
                $mode += 8;
95
        }
96
        if (! isnull($size)) {
97
            $mode = array_keys($this->aFont, $this->font, true);
98
            //double width and double height
99
            $mode += (16+32);
100
        }
101
        $this->buffer->write(self::ESC . '!' . $mode);
102
    }
103
    
104
    /**
105
     * Set condensed mode.
106
     * Will change Font do D
107
     */
108
    public function setCondensed()
109
    {
110
        $this->setExpanded();
111
        $this->setFont('D');
112
    }
113
    
114
    /**
115
     * Imprime o QR Code
116
     *
117
     * @param string $data   Dados a serem inseridos no QRCode
118
     * @param string $level  Nivel de correção L,M,Q ou H
119
     * @param int    $modelo modelo de QRCode 0 QRCode ou 1 microQR
120
     * @param int    $wmod   largura da barra 3 ~ 16
121
     */
122
    public function barcodeQRCode($data = '', $level = 'M', $modelo = 0, $wmod = 4)
123
    {
124
        $aModels = array();
125
        //essa matriz especifica o numero máximo de caracteres alfanumericos que o
126
        //modelo de QRCode suporta dependendo no nivel de correção.
127
        //Cada matriz representa um nivel de correção e cada uma das 40 posições nessas
128
        //matrizes indicam o numero do modelo do QRCode e o numero máximo de caracteres
129
        //alfamunéricos suportados
130
        //Quanto maior o nivel de correção menor é a quantidade de caracteres suportada
131
        $aModels[0]=[25,47,77,114,154,195,224,279,335,395,468,535,619,667,
132
            758,854,938,1046,1153,1249,1352,1460,1588,1704,1853,1990,2132,
133
            2223,2369,2520,2677,2840,3009,3183,3351,3537,3729,3927,4087,4296];
134
        $aModels[1]=[20,38,61,90,122,154,178,221,262,311,366,419,483,528,600,
135
            656,734,816,909,970,1035,1134,1248,1326,1451,1542,1637,1732,1839,
136
            1994,2113,2238,2369,2506,2632,2780,2894,3054,3220,3391];
137
        $aModels[2]=[16,29,47,67,87,108,125,157,189,221,259,296,352,376,426,
138
            470,531,574,644,702,742,823,890,963,1041,1094,1172,1263,1322,1429,
139
            1499,1618,1700,1787,1867,1966,2071,2181,2298,2420];
140
        $aModels[3]=[10,20,35,50,64,84,93,122,143,174,200,227,259,283,321,365,
141
            408,452,493,557,587,640,672,744,779,864,910,958,1016,1080,1150,1226,
142
            1307,1394,1431,1530,1591,1658,1774,1852];
143
        //n1 Error correction level (data restoration)
144
        switch ($level) {
145
            case 'L':
146
                $n1 = 0;
147
                break;
148
            case "M":
149
                $n1 = 1;
150
                break;
151
            case "Q":
152
                $n1 = 2;
153
                break;
154
            case "H":
155
                $n1 = 3;
156
                break;
157
            default:
158
                $n1 = 0;
159
        }
160
        if ($modelo != 0 && $modelo != 1) {
161
            $modelo = 0;
162
        }
163
        //se for mucroQR sua capacidade é bem reduzida
164
        if ($modelo == 1) {
165
            $aModels[0] = [6,14,21];
166
            $aModels[1] = [5,11,18];
167
            $aModels[2] = [0,0,13];
168
            $aModels[3] = [0,0,0];
169
        }
170
        //n2 Module/cell size in pixels MSB 1 ≤ module size ≤ 127 LSB 0 QR or 1 MicroQR
171
        $n2 = $wmod << 1;//shift 1 é o mesmo que multiplicar por 2
172
        $n2 += $modelo;//seleciona QRCode ou microQR
173
        //comprimento da mensagem
174
        $length = strlen($data);
175
        //seleciona matriz de modelos aplicavel pelo nivel de correção
176
        $am = $aModels[$n1];
177
        $i = 0;
178
        $flag = false;
179
        foreach ($am as $size) {
180
            //verifica se o tamanho maximo é maior ou igual ao comprimento da mensagem
181
            if ($size >= $length) {
182
                $flag = true;
183
                break;
184
            }
185
            $i++;
186
        }
187
        if (! $flag) {
188
            throw new InvalidArgumentException(
189
                'O numero de caracteres da mensagem é maior que a capacidade do QRCode'
190
            );
191
        }
192
        //n3 Version QRCode
193
        //depende do comprimento dos dados e do nivel de correção
194
        $n3 = ($i + 1);
195
        //n4 Encoding modes
196
        //0 – Numeric only              Max. 7,089 characters
197
        //1 – Alphanumeric              Max. 4,296 characters
198
        //2 – Binary (8 bits)           Max. 2,953 bytes
199
        //3 – Kanji, full-width Kana    Max. 1,817 characters
200
        $n4 = 1;//sempre será 1 apenas caracteres alfanumericos nesse caso
201
        //n5 e n6 Indicate the number of bytes that will be coded, where total = n5 + n6 x 256,
202
        //and total must be less than 7089.
203
        $n6 = intval($length / 256);
204
        $n5 = ($length % 256);
205
        $this->buffer->write(self::GS."kQ" . chr($n1) . chr($n2) . chr($n3) . chr($n4) . chr($n5) . chr($n6) . $data);
206
    }
207
    
208
    /**
209
     * GS v0 m xL xH yL yH d1 ... dk
210
     *
211
     * @param string $filename
212
     * @param intger $width
213
     * @param integer $height
214
     * @param integer $size resolution relation
215
     * @throws RuntimeException
216
     */
217
    public function putImage($filename = '', $width = null, $height = null, $size = 0)
218
    {
219
        try {
220
            $img = new Graphics($filename, $width, $height);
221
        } catch (RuntimeException $e) {
0 ignored issues
show
Bug introduced by
The class Posprint\Printers\RuntimeException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
222
            throw new RuntimeException($e->getMessage());
223
        } catch (InvalidArgumentException $e) {
0 ignored issues
show
Bug introduced by
The class Posprint\Printers\InvalidArgumentException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
224
            throw new RuntimeException($e->getMessage());
225
        }
226
        $size = self::validateInteger($size, 0, 3, 0);
227
        //get xL xH yL yH
228
        $imgHeader = self::dataHeader(array($img->getWidth(), $img->getHeight()), true);
0 ignored issues
show
Unused Code introduced by
$imgHeader 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...
229
        //send graphics command to printer
230
        $this->buffer->write(self::GS.'v0'.chr($size).$header.$img->getRasterImage());
0 ignored issues
show
Bug introduced by
The variable $header does not exist. Did you mean $imgHeader?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
231
    }
232
}
233