FileSource::file()   A
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.105

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 9
nop 0
dl 0
loc 21
ccs 12
cts 14
cp 0.8571
crap 6.105
rs 9.2222
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 56
    public function __construct(string $filename)
19
    {
20 56
        $this->filename = $filename;
21 56
    }
22
23 56
    public function __destruct()
24
    {
25 56
        if ($this->handle) {
26
            try {
27 55
                fclose($this->handle);
28
            } catch (Throwable $e) {
29
                // ignore
30
            }
31
        }
32 56
    }
33
34
    /**
35
     * @return resource
36
     * @throws SourceException
37
     */
38 59
    protected function file()
39
    {
40 59
        if (!$this->handle) {
41 59
            $exception = null;
42
            try {
43 59
                $handle = fopen($this->filename, 'r');
44 58
                if ($handle === false) {
45
                    $error = error_get_last();
46
                    throw new \RuntimeException($error ? $error['message'] : 'fopen error');
47
                }
48 58
                $this->handle = $handle;
49 1
            } catch (Throwable $e) {
50 1
                $this->handle = null;
51 1
                $exception = $e;
52
            }
53 59
            if (!$this->handle) {
54 1
                throw new SourceException("Could not open file '{$this->filename}'", 0, $exception);
55
            }
56
        }
57
58 58
        return $this->handle;
59
    }
60
61 59
    protected function stream()
62
    {
63 59
        if (!$this->streamSource) {
64 59
            $this->streamSource = new StreamSource($this->file());
65
        }
66
67 58
        return $this->streamSource;
68
    }
69
70 56
    public function isEof(): bool
71
    {
72 56
        return $this->stream()->isEof();
73
    }
74
75 59
    public function read(int $bytes): string
76
    {
77 59
        return $this->stream()->read($bytes);
78
    }
79
80 55
    public function rewind(): void
81
    {
82 55
        $this->stream()->rewind();
83 55
    }
84
}
85