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

AbstractXMLResource   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 38
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getXMLReader() 0 3 1
A validateXMLReader() 0 9 2
A closeXMLReader() 0 4 1
A createXMLReader() 0 3 1
A __construct() 0 2 1
A __destruct() 0 3 1
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