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

FileSource   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 90.63%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
c 1
b 0
f 0
dl 0
loc 74
ccs 29
cts 32
cp 0.9063
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 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