spaghettisolutions /
xlsx-parser
| 1 | <?php declare(strict_types = 1); |
||
| 2 | |||
| 3 | namespace Spaghetti\XLSXParser; |
||
| 4 | |||
| 5 | use Spaghetti\XLSXParser\Exception\InvalidXLSXFileException; |
||
| 6 | use Throwable; |
||
| 7 | use XMLReader; |
||
| 8 | |||
| 9 | /** |
||
| 10 | * @internal |
||
| 11 | */ |
||
| 12 | abstract class AbstractXMLResource |
||
| 13 | { |
||
| 14 | private ?XMLReader $xml = null; |
||
| 15 | |||
| 16 | public function __construct(private readonly string $path) |
||
| 17 | { |
||
| 18 | } |
||
| 19 | |||
| 20 | public function __destruct() |
||
| 21 | { |
||
| 22 | $this->closeXMLReader(); |
||
| 23 | } |
||
| 24 | |||
| 25 | protected function getXMLReader(): XMLReader |
||
| 26 | { |
||
| 27 | return $this->xml ??= $this->createXMLReader(); |
||
| 28 | } |
||
| 29 | |||
| 30 | protected function createXMLReader(): XMLReader |
||
| 31 | { |
||
| 32 | return $this->validateXMLReader(xml: new XMLReader()); |
||
| 33 | } |
||
| 34 | |||
| 35 | protected function closeXMLReader(): void |
||
| 36 | { |
||
| 37 | $this->xml?->close(); |
||
| 38 | $this->xml = null; |
||
| 39 | } |
||
| 40 | |||
| 41 | private function validateXMLReader(XMLReader $xml): XMLReader |
||
| 42 | { |
||
| 43 | try { |
||
| 44 | @$xml->open(uri: $this->path); |
||
|
0 ignored issues
–
show
|
|||
| 45 | $xml->read(); |
||
| 46 | } catch (Throwable $throwable) { |
||
| 47 | throw new InvalidXLSXFileException(path: $this->path, previous: $throwable); |
||
| 48 | } |
||
| 49 | |||
| 50 | return $xml; |
||
| 51 | } |
||
| 52 | } |
||
| 53 |
If you suppress an error, we recommend checking for the error condition explicitly: