|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace PhpEpub; |
|
6
|
|
|
|
|
7
|
|
|
use PhpEpub\Util\FileSystemHelper; |
|
8
|
|
|
use SimpleXMLElement; |
|
9
|
|
|
|
|
10
|
|
|
class EpubFile |
|
11
|
|
|
{ |
|
12
|
|
|
private ?string $tempDir = null; |
|
13
|
|
|
private readonly XmlParser $xmlParser; |
|
14
|
|
|
private readonly ZipHandler $zipHandler; |
|
15
|
|
|
private readonly Parser $parser; |
|
16
|
|
|
private ?Metadata $metadata = null; |
|
17
|
|
|
private ?Spine $spine = null; |
|
18
|
|
|
private ?SimpleXMLElement $opfXml = null; |
|
19
|
|
|
|
|
20
|
28 |
|
public function __construct(private readonly string $filePath) |
|
21
|
|
|
{ |
|
22
|
28 |
|
$this->zipHandler = new ZipHandler(); |
|
23
|
28 |
|
$this->xmlParser = new XmlParser(); |
|
24
|
28 |
|
$this->parser = new Parser($this->xmlParser); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
28 |
|
public function __destruct() |
|
28
|
|
|
{ |
|
29
|
28 |
|
if ($this->tempDir !== null && is_dir($this->tempDir)) { |
|
30
|
27 |
|
$helper = new FileSystemHelper(); |
|
31
|
27 |
|
$helper->deleteDirectory($this->tempDir); |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
27 |
|
public function load(): void |
|
36
|
|
|
{ |
|
37
|
27 |
|
$this->tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('epub_', true); |
|
38
|
27 |
|
if (! mkdir($this->tempDir) && ! is_dir($this->tempDir)) { |
|
39
|
|
|
throw new Exception("Failed to create temporary directory: {$this->tempDir}"); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
27 |
|
$this->zipHandler->extract($this->filePath, $this->tempDir); |
|
43
|
|
|
|
|
44
|
21 |
|
$opfFilePath = $this->parser->parse($this->tempDir); |
|
45
|
21 |
|
$opfFileFullPath = $this->tempDir . DIRECTORY_SEPARATOR . $opfFilePath; |
|
46
|
|
|
|
|
47
|
21 |
|
$this->opfXml = $this->xmlParser->parse($opfFileFullPath); |
|
48
|
|
|
|
|
49
|
21 |
|
$this->metadata = new Metadata($this->opfXml, $opfFileFullPath); |
|
50
|
21 |
|
$this->spine = new Spine($this->opfXml); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
15 |
|
public function save(?string $filePath = null): void |
|
54
|
|
|
{ |
|
55
|
15 |
|
if ($this->tempDir === null) { |
|
56
|
1 |
|
throw new Exception('EPUB file must be loaded before saving.'); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
14 |
|
if ($filePath === null) { |
|
60
|
7 |
|
$filePath = $this->filePath; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
14 |
|
$this->zipHandler->compress($this->tempDir, $filePath); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
7 |
|
public function getTempDir(): ?string |
|
67
|
|
|
{ |
|
68
|
7 |
|
return $this->tempDir; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
7 |
|
public function getMetadata(): ?Metadata |
|
72
|
|
|
{ |
|
73
|
7 |
|
return $this->metadata; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
7 |
|
public function getSpine(): ?Spine |
|
77
|
|
|
{ |
|
78
|
7 |
|
return $this->spine; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|