1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PhpEpub\Converters; |
6
|
|
|
|
7
|
|
|
use PhpEpub\Exception; |
8
|
|
|
use PhpEpub\Util\FileSystemHelper; |
9
|
|
|
|
10
|
|
|
class CalibreAdapter implements ConverterInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var array<string, string> |
14
|
|
|
*/ |
15
|
|
|
private array $options; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* CalibreAdapter constructor. |
19
|
|
|
* |
20
|
|
|
* @param array<string, string> $options Optional command-line options for Calibre. |
21
|
|
|
*/ |
22
|
5 |
|
public function __construct(array $options = [], private readonly FileSystemHelper $helper = new FileSystemHelper()) |
23
|
|
|
{ |
24
|
5 |
|
$defaultOptions = [ |
25
|
5 |
|
'calibre_path' => '/usr/bin/ebook-convert', |
26
|
5 |
|
'extra_args' => '', |
27
|
5 |
|
]; |
28
|
|
|
|
29
|
5 |
|
$this->options = array_merge($defaultOptions, $options); |
30
|
|
|
} |
31
|
|
|
|
32
|
5 |
|
public function convert(string $inputFile, string $outputPath): void |
33
|
|
|
{ |
34
|
5 |
|
$calibrePath = $this->options['calibre_path']; |
35
|
|
|
|
36
|
5 |
|
if (! $this->helper->fileExists($calibrePath)) { |
37
|
1 |
|
throw new Exception('Calibre tool not found at path: ' . $calibrePath); |
38
|
|
|
} |
39
|
|
|
|
40
|
4 |
|
if (! $this->helper->fileExists($inputFile)) { |
41
|
1 |
|
throw new Exception("EPUB file not found: {$inputFile}"); |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
$command = sprintf( |
45
|
3 |
|
'%s %s %s %s', |
46
|
3 |
|
escapeshellcmd($calibrePath), |
47
|
3 |
|
escapeshellarg($inputFile), |
48
|
3 |
|
escapeshellarg($outputPath), |
49
|
3 |
|
$this->options['extra_args'] |
50
|
3 |
|
); |
51
|
|
|
|
52
|
|
|
// Execute the command |
53
|
3 |
|
$output = []; |
54
|
3 |
|
$returnVar = 0; |
55
|
3 |
|
$this->helper->exec($command, $output, $returnVar); |
56
|
|
|
|
57
|
3 |
|
if ($returnVar !== 0) { |
58
|
1 |
|
throw new Exception('Calibre conversion failed: ' . implode("\n", $output)); |
59
|
|
|
} |
60
|
|
|
|
61
|
2 |
|
if (! $this->helper->fileExists($outputPath) || $this->helper->fileSize($outputPath) === 0) { |
62
|
1 |
|
throw new Exception('Calibre conversion failed'); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|