1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Spaghetti\XLSXParser; |
4
|
|
|
|
5
|
|
|
use Iterator; |
6
|
|
|
use Spaghetti\XLSXParser\Exception\InvalidIndexException; |
7
|
|
|
|
8
|
|
|
use function array_keys; |
9
|
|
|
use function array_search; |
10
|
|
|
use function array_values; |
11
|
|
|
use function is_int; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @internal |
15
|
|
|
*/ |
16
|
|
|
final class XLSX implements Contracts\XLSXInterface |
17
|
|
|
{ |
18
|
|
|
private ?Relationships $relationships = null; |
19
|
|
|
private ?SharedStrings $sharedStrings = null; |
20
|
|
|
private ?Styles $styles = null; |
21
|
|
|
private ?Transformer\Value $valueTransformer = null; |
22
|
|
|
private ?array $worksheetPaths = null; |
23
|
|
|
|
24
|
|
|
public function __construct(private readonly Archive $archive) |
25
|
|
|
{ |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function getWorksheets(): array |
29
|
|
|
{ |
30
|
|
|
return array_keys(array: $this->getWorksheetPaths()); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function getRows(int $index): Iterator |
34
|
|
|
{ |
35
|
|
|
return new RowIterator(valueTransformer: $this->getValueTransformer(), path: $this->archive->extract(filePath: array_values(array: $this->getWorksheetPaths())[$index]), ); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function getIndex(string $name): int |
39
|
|
|
{ |
40
|
|
|
$result = array_search(needle: $name, haystack: $this->getWorksheets(), strict: true); |
41
|
|
|
|
42
|
|
|
return match (is_int(value: $result)) { |
43
|
|
|
true => $result, |
44
|
|
|
default => throw new InvalidIndexException(name: $name), |
45
|
|
|
}; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function getRelationships(): Relationships |
49
|
|
|
{ |
50
|
|
|
return $this->relationships ??= new Relationships(path: $this->archive->extract(filePath: 'xl/_rels/workbook.xml.rels')); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function getValueTransformer(): Transformer\Value |
54
|
|
|
{ |
55
|
|
|
return $this->valueTransformer ??= new Transformer\Value(sharedStrings: $this->getSharedStrings(), styles: $this->getStyles()); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function getSharedStrings(): SharedStrings |
59
|
|
|
{ |
60
|
|
|
return $this->sharedStrings ??= new SharedStrings(path: $this->archive->extract(filePath: $this->getRelationships()->getSharedStringsPath())); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function getWorksheetPaths(): array |
64
|
|
|
{ |
65
|
|
|
return $this->worksheetPaths ??= (new Worksheet(path: $this->archive->extract(filePath: 'xl/workbook.xml')))->getWorksheetPaths(relationships: $this->getRelationships()); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function getStyles(): Styles |
69
|
|
|
{ |
70
|
|
|
return $this->styles ??= new Styles(path: $this->archive->extract(filePath: $this->getRelationships()->getStylesPath())); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|