Passed
Push — master ( 5f22ed...091071 )
by Mikhail
03:13
created

FileSource::__destruct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
crap 3.1406
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace JsonDecodeStream\Source;
5
6
use JsonDecodeStream\Exception\SourceException;
7
use Throwable;
8
9
class FileSource implements SourceInterface
10
{
11
    /** @var string */
12
    protected $filename;
13
    /** @var resource|null */
14
    protected $handle;
15
    /** @var StreamSource|null */
16
    protected $streamSource;
17
18 48
    public function __construct(string $filename)
19
    {
20 48
        $this->filename = $filename;
21 48
    }
22
23 48
    public function __destruct()
24
    {
25 48
        if ($this->handle) {
26
            try {
27 47
                fclose($this->handle);
28
            } catch (Throwable $e) {
29
                // ignore
30
            }
31
        }
32 48
    }
33
34
    /**
35
     * @return resource
36
     * @throws SourceException
37
     */
38 51
    protected function file()
39
    {
40 51
        if (!$this->handle) {
41 51
            $exception = null;
42
            try {
43 51
                $handle = fopen($this->filename, 'r');
44 50
                if (!$handle) {
0 ignored issues
show
introduced by
$handle is of type false|resource, thus it always evaluated to false.
Loading history...
45
                    $error = error_get_last();
46
                    throw new \RuntimeException($error ? $error['message'] : 'fopen error');
47
                }
48 50
                $this->handle = $handle;
49 1
            } catch (Throwable $e) {
50 1
                $this->handle = null;
51 1
                $exception = $e;
52
            }
53 51
            if (!$this->handle) {
54 1
                throw new SourceException("Could not open file '{$this->filename}'", 0, $exception);
55
            }
56
        }
57
58 50
        return $this->handle;
59
    }
60
61 51
    protected function stream()
62
    {
63 51
        if (!$this->streamSource) {
64 51
            $this->streamSource = new StreamSource($this->file());
65
        }
66
67 50
        return $this->streamSource;
68
    }
69
70 48
    public function isEof(): bool
71
    {
72 48
        return $this->stream()->isEof();
73
    }
74
75 51
    public function read(int $bytes): string
76
    {
77 51
        return $this->stream()->read($bytes);
78
    }
79
80 47
    public function rewind(): void
81
    {
82 47
        $this->stream()->rewind();
83 47
    }
84
}
85