Passed
Push — spaghetti ( fcb196...2528e5 )
by simpletoimplement
02:19
created

AbstractXMLResource::validateXMLReader()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 9
rs 10
1
<?php declare(strict_types = 1);
2
3
namespace Spaghetti\XLSXParser;
4
5
use InvalidArgumentException;
6
use Throwable;
7
use XMLReader;
8
9
use function sprintf;
10
11
/**
12
 * @internal
13
 */
14
abstract class AbstractXMLResource
15
{
16
    private ?XMLReader $xml = null;
17
18
    public function __construct(private readonly string $path)
19
    {
20
    }
21
22
    public function __destruct()
23
    {
24
        $this->closeXMLReader();
25
    }
26
27
    protected function getXMLReader(): XMLReader
28
    {
29
        return $this->xml ??= $this->createXMLReader();
30
    }
31
32
    protected function createXMLReader(): XMLReader
33
    {
34
        return $this->validateXMLReader(xml: new XMLReader());
35
    }
36
37
    protected function closeXMLReader(): void
38
    {
39
        $this->xml?->close();
40
        $this->xml = null;
41
    }
42
43
    private function validateXMLReader(XMLReader $xml): XMLReader
44
    {
45
        try {
46
            $xml->open(uri: $this->path);
47
        } catch (Throwable $throwable) {
48
            throw new InvalidArgumentException(message: sprintf('Not a XLSX file: %s', $this->path), previous: $throwable);
49
        }
50
51
        return $xml;
52
    }
53
}
54