Passed
Pull Request — master (#4)
by Chad
08:38
created

FileSource   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
c 1
b 0
f 0
dl 0
loc 74
ccs 27
cts 30
cp 0.9
rs 10
wmc 15

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A read() 0 3 1
A file() 0 21 6
A rewind() 0 3 1
A __destruct() 0 6 3
A isEof() 0 3 1
A stream() 0 7 2
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
    }
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
    }
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
    }
84
}
85