Completed
Push — master ( fd4537...c5f7b8 )
by Roberto
06:16 queued 03:11
created

Buffer::friendlyBinary()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 16
rs 8.8571
cc 5
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace Posprint\Connectors;
4
5
/**
6
 * Class Buffer 
7
 * In principle, the entire assembly of RAW commands must be made for this buffer
8
 * that will be used later for sending to the appropriate connector set by calling class
9
 * this is necessary to make to enable:
10
 *    1 - debug the assembly of commands
11
 *    2 - allow the use of qz.io for printing by using a browser and a cloud server
12
 *
13
 * @category   NFePHP
14
 * @package    Posprint
15
 * @copyright  Copyright (c) 2015
16
 * @license    http://www.gnu.org/licenses/lesser.html LGPL v3
17
 * @author     Roberto L. Machado <linux.rlm at gmail dot com>
18
 * @link       http://github.com/nfephp-org/posprint for the canonical source repository
19
 */
20
21
use Posprint\Connectors\ConnectorInterface;
22
23
final class Buffer implements ConnectorInterface
24
{
25
    private $ctrlCodes = [
26
       ' [NUL] ' => 0, //Nulo
27
       ' [EOT] ' => 4, //EOT fim da transmissão
28
       ' [ENQ] ' => 5, //ENQ colocar na fila Pedido de status 1
29
       ' [BEL] ' => 7, //BEL sinal sonoro
30
       ' [HT] ' => 9, //tabulação horizontal
31
       ' [LF] ' => 10, //Inicia a impressão e avança uma linha
32
       ' [VT] ' => 11, //tabulação vertical
33
       ' [FF] ' => 12, //avança pagina
34
       ' [CR] ' => 13, //retorno de carro
35
       ' [SO] ' => 14, //SO Inicia modo expandido
36
       ' [SI] ' => 15, //Seleciona modo condensado
37
       ' [DLE] ' => 16, //Data Link Escape
38
       ' [DC1] ' => 17, //DC1 Inicia modo enfatizado
39
       ' [DC2] ' => 18, //DC2 Cancela modo condensado
40
       ' [DC3] ' => 19, //DC3 Cancela modo enfatizado
41
       ' [DC4] ' => 20, //DC4 Controle de dispositivo 4 Inicia modo normal
42
       ' [SYN] ' => 22, //Sincronismo 
43
       ' [CAN] ' => 24, //CAN Cancela linha enviada
44
       ' [EM] ' => 25, //Avança 4 linhas
45
       ' [ESC] ' => 27, //escape 
46
       ' [FS] ' => 28, //FS
47
       ' [GS] ' => 29, //GS
48
       ' [DEL] ' => 127 //Cancela último caracter
49
    ];
50
    
51
    /**
52
     * Buffer of accumulated raw data.
53
     * @var array
54
     */
55
    private $buffer = null;
56
    
57
    /**
58
     * Create new print connector
59
     * and set $buffer property as empty array
60
     */
61
    public function __construct()
62
    {
63
        $this->buffer = array();
64
    }
65
66
    /**
67
     * Destruct print connection
68
     */
69
    public function __destruct()
70
    {
71
        $this->close();
72
    }
73
74
    /**
75
     * Send data to buffer porperty
76
     * 
77
     * @param string $data
78
     */
79
    public function write($data)
80
    {
81
        $this->buffer[] = $data;
82
    }
83
84
    /**
85
     * Finalize printer connection
86
     * and clear buffer property
87
     */
88
    public function close()
89
    {
90
        $this->buffer = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $buffer.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
91
    }
92
    
93
    /**
94
     * Return the accumulated raw data that has been sent to this buffer.
95
     * 
96
     * @param bool $retArray Enable return as array, otherwise will return a string
97
     * @return string|array
98
     */
99
    public function getDataBinary($retArray = true)
100
    {
101
        if (! $retArray) {
102
            return implode($this->buffer);
103
        }
104
        return $this->buffer;
105
    }
106
    
107
    /**
108
     * Return the data buffer in base64-encoded for transmission over TCP/IP,
109
     * specifically for use qz.io or other similar system.
110
     * 
111
     * @param boolean $retArray Enable return as array, otherwise will return a string
112
     * @return array|string
113
     */
114
    public function getDataBase64($retArray = true)
115
    {
116
        foreach($this->buffer as $linha) {
117
            $lbuff[] = base64_encode($linha);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$lbuff was never initialized. Although not strictly required by PHP, it is generally a good practice to add $lbuff = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
118
        }
119
        if (! $retArray) {
120
            return implode("\n",$lbuff);
0 ignored issues
show
Bug introduced by
The variable $lbuff 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...
121
        }
122
        return $lbuff;
123
    }
124
    
125
    /**
126
     * Returns the buffer data in JSON format
127
     * for use with the java ajax
128
     * It must be tested because there may be binary data
129
     * that can not travel on GET or POST requests over TCP/IP
130
     * 
131
     * @param bool $retArray Enable return as array, otherwise will return a string
132
     * @return string
133
     */
134
    public function getDataJson($retArray = true)
135
    {
136
        return json_encode($this->getDataBinary($retArray));
137
    }
138
    
139
    /**
140
     * getDataReadable
141
     * Return buffer data converted into a readable string.
142
     * For testing and debbuging only, this format should not be sent to printer
143
     * 
144
     * @param bool $retArray Enable return as array, otherwise will return a string
145
     * @return string|array
146
     */
147
    public function getDataReadable($retArray = true)
148
    {
149
        $ret = array();
150
        foreach ($this->buffer as $data) {
151
            $ret[] = $this->friendlyBinary($data);
152
        }
153
        if (! $retArray) {
154
            $ret = implode("\n", $ret);
155
        }
156
        return $ret;
157
    }
158
159
    /**
160
     * Converts unprintable characters in screen-printing characters
161
     * used for debugging purpose only
162
     * 
163
     * @param string $input
164
     * @return string
165
     */
166
    protected function friendlyBinary($input)
167
    {
168
        // Print out binary data with PHP \x00 escape codes,
169
        // for builting test cases.
170
        $chars = str_split($input);
171
        foreach ($chars as $index => $byte) {
172
            $code = ord($byte);
173
            $key = array_search($code, $this->ctrlCodes, true);
174
            if ($key !== false) {
175
                $chars[$index] = $key;
176
            } elseif ($code < 32 || $code > 126) {
177
                $chars[$index] = "\\x" . bin2hex($byte);
178
            }
179
        }
180
        return implode($chars);
181
    }
182
}
183