Completed
Push — master ( f0e6e1...5d896c )
by Carlos C
04:06 queued 02:35
created

PdfToText::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3.0261
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\CfdiToPdf;
6
7
use PhpCfdi\CfdiToPdf\Utils\ShellExec;
8
9
/**
10
 * Extract the contents of a pdf file using pdftotext (apt-get install poppler-utils)
11
 */
12
class PdfToText
13
{
14
    private $pdftotext;
15
16 1
    public function __construct(string $pathPdfToText = '')
17
    {
18 1
        if ('' === $pathPdfToText) {
19 1
            $pathPdfToText = (string) shell_exec('which pdftotext');
20 1
            if ('' === $pathPdfToText) {
21
                throw new \RuntimeException('pdftotext command was not found');
22
            }
23
        }
24 1
        $this->pdftotext = $pathPdfToText;
25 1
    }
26
27
    /**
28
     * @param string $filename
29
     * @return string[] file contents
30
     */
31 1
    public function extract(string $filename): array
32
    {
33 1
        $shellExec = ShellExec::run($this->buildCommand($filename));
34 1
        if (0 !== $shellExec->exitStatus()) {
35
            throw new \RuntimeException("Running pdftotext exit with error (exit status: {$shellExec->exitStatus()})");
36
        }
37 1
        return $shellExec->output();
38
    }
39
40 1
    public function buildCommand(string $pdfFile): string
41
    {
42 1
        return escapeshellcmd($this->pdftotext) . ' -eol unix -raw -q ' . escapeshellarg($pdfFile) . ' -';
43
    }
44
}
45