FileConnector   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 78.26%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 52
ccs 18
cts 23
cp 0.7826
rs 10
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __destruct() 0 3 1
A __construct() 0 3 1
A read() 0 5 1
A close() 0 6 2
A open() 0 10 3
A write() 0 5 1
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