NetworkConnector::flushErrors()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 11
ccs 0
cts 10
cp 0
crap 6
rs 10
1
<?php
2
3
/**
4
 * This file is part of PhpAidc LabelPrinter package.
5
 *
6
 * © Appwilio (https://appwilio.com)
7
 * © JhaoDa (https://github.com/jhaoda)
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace PhpAidc\LabelPrinter\Connector;
16
17
use PhpAidc\LabelPrinter\Contract\Connector;
18
use PhpAidc\LabelPrinter\Exception\CouldNotConnectToPrinter;
19
20
final class NetworkConnector implements Connector
21
{
22
    /** @var string */
23
    private $host;
24
25
    /** @var int */
26
    private $port;
27
28
    /** @var int */
29
    private $timeout;
30
31
    /** @var resource */
32
    private $handle;
33
34
    /** @var array|null */
35
    private $lastError;
36
37
    public function __construct(string $host, int $port = 9100, int $timeout = 1)
38
    {
39
        $this->host = $host;
40
        $this->port = $port;
41
        $this->timeout = $timeout;
42
    }
43
44
    public function open(): void
45
    {
46
        if (\is_resource($this->handle)) {
47
            return;
48
        }
49
50
        $this->setErrorHandler();
51
52
        try {
53
            $this->handle = \stream_socket_client("tcp://{$this->host}:{$this->port}", $severity, $message, $this->timeout);
54
55
            $this->flushErrors();
56
57
            \stream_set_timeout($this->handle, $this->timeout, 0);
58
        } catch (\ErrorException $e) {
59
            throw CouldNotConnectToPrinter::becauseNetworkError($e->getMessage());
60
        }
61
    }
62
63
    public function write($data): int
64
    {
65
        $this->open();
66
67
        $this->setErrorHandler();
68
69
        $result = \fwrite($this->handle, $data, \strlen($data));
70
71
        $this->flushErrors();
72
73
        return $result;
74
    }
75
76
    public function read(int $length = 0)
77
    {
78
        $this->open();
79
80
        $result = '';
81
82
        while (true) {
83
            $this->setErrorHandler();
84
85
            $buffer = \fread($this->handle, 8192);
86
87
            $this->flushErrors();
88
89
            $result .= $buffer;
90
91
            if (\mb_strlen($buffer) < 8192) {
92
                break;
93
            }
94
        }
95
96
        return $result;
97
    }
98
99
    public function close(): void
100
    {
101
        if (\is_resource($this->handle)) {
102
            $this->setErrorHandler();
103
104
            \fclose($this->handle);
105
106
            $this->flushErrors();
107
108
            $this->handle = null;
109
        }
110
    }
111
112
    public function __destruct()
113
    {
114
        $this->close();
115
    }
116
117
    private function setErrorHandler(): void
118
    {
119
        $this->lastError = null;
120
121
        \set_error_handler(function ($severity, $message, $file, $line) {
122
            $this->lastError = \compact('severity', 'message', 'file', 'line');
123
        });
124
    }
125
126
    private function flushErrors(): void
127
    {
128
        \restore_error_handler();
129
130
        if ($this->lastError) {
131
            throw new \ErrorException(
132
                $this->lastError['message'],
133
                0,
134
                $this->lastError['severity'],
135
                $this->lastError['file'],
136
                $this->lastError['line']
137
            );
138
        }
139
    }
140
}
141