1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jaybizzle\DocToText; |
4
|
|
|
|
5
|
|
|
use Jaybizzle\DocToText\Exceptions\CouldNotExtractText; |
6
|
|
|
use Jaybizzle\DocToText\Exceptions\DocNotFound; |
7
|
|
|
use Symfony\Component\Process\Process; |
8
|
|
|
|
9
|
|
|
class Doc |
10
|
|
|
{ |
11
|
|
|
protected $doc; |
12
|
|
|
|
13
|
|
|
protected $binPath; |
14
|
|
|
|
15
|
|
|
protected $options = []; |
16
|
|
|
|
17
|
|
|
public function __construct(string $binPath = null) |
18
|
|
|
{ |
19
|
|
|
$this->binPath = $binPath ?? '/usr/bin/antiword'; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function setDoc(string $doc): self |
23
|
|
|
{ |
24
|
|
|
if (!is_readable($doc)) { |
25
|
|
|
throw new DocNotFound(sprintf('could not find or read doc `%s`', $doc)); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$this->doc = $doc; |
29
|
|
|
|
30
|
|
|
return $this; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function setOptions(array $options): self |
34
|
|
|
{ |
35
|
|
|
$mapper = function (string $content): array { |
36
|
|
|
$content = trim($content); |
37
|
|
|
if ('-' !== ($content[0] ?? '')) { |
38
|
|
|
$content = '-'.$content; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
return explode(' ', $content, 2); |
42
|
|
|
}; |
43
|
|
|
|
44
|
|
|
$reducer = function (array $carry, array $option): array { |
45
|
|
|
return array_merge($carry, $option); |
46
|
|
|
}; |
47
|
|
|
|
48
|
|
|
$this->options = array_reduce(array_map($mapper, $options), $reducer, []); |
49
|
|
|
|
50
|
|
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function text(): string |
54
|
|
|
{ |
55
|
|
|
$process = new Process(array_merge([$this->binPath], $this->options, [$this->doc])); |
56
|
|
|
$process->run(); |
57
|
|
|
if (!$process->isSuccessful()) { |
58
|
|
|
throw new CouldNotExtractText($process); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return trim($process->getOutput(), " \t\n\r\0\x0B\x0C"); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public static function getText(string $doc, string $binPath = null, array $options = []): string |
65
|
|
|
{ |
66
|
|
|
return (new static($binPath)) |
67
|
|
|
->setOptions($options) |
68
|
|
|
->setDoc($doc) |
69
|
|
|
->text(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|