FileConnector::close()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
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 FileConnector implements Connector
21
{
22
    /** @var string */
23
    private $file;
24
25
    /** @var resource */
26
    private $handle;
27
28 1
    public function __construct(string $file)
29
    {
30 1
        $this->file = $file;
31 1
    }
32
33 1
    public function open(): void
34
    {
35 1
        if (\is_resource($this->handle)) {
36
            return;
37
        }
38
39 1
        $this->handle = \fopen($this->file, 'w+b');
40
41 1
        if ($this->handle === false) {
42
            throw CouldNotConnectToPrinter::becauseCannotOpenFile($this->file);
43
        }
44 1
    }
45
46 1
    public function close(): void
47
    {
48 1
        if (\is_resource($this->handle)) {
49 1
            \fclose($this->handle);
50
51 1
            $this->handle = null;
52
        }
53 1
    }
54
55 1
    public function write($data): int
56
    {
57 1
        $this->open();
58
59 1
        return \fwrite($this->handle, $data, \strlen($data));
60
    }
61
62
    public function read(int $length = 0)
63
    {
64
        $this->open();
65
66
        return \fread($this->handle, $length);
67
    }
68
69 1
    public function __destruct()
70
    {
71 1
        $this->close();
72 1
    }
73
}
74