EpubFile   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 96.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
eloc 31
c 1
b 0
f 0
dl 0
loc 69
ccs 29
cts 30
cp 0.9667
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A save() 0 11 3
A getSpine() 0 3 1
A load() 0 16 3
A getTempDir() 0 3 1
A __destruct() 0 5 3
A getMetadata() 0 3 1
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