Skip to content

Commit

Permalink
Merge pull request #54 from jbraband/add-process-timeout
Browse files Browse the repository at this point in the history
add timeout config for Symfony Process call
  • Loading branch information
freekmurze authored Jul 14, 2022
2 parents b6d8bcd + f0d78ec commit 8eca492
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Pdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ class Pdf

protected array $options = [];

protected int $timeout = 60;

public function __construct(?string $binPath = null)
{
$this->binPath = $binPath ?? '/usr/bin/pdftotext';
Expand Down Expand Up @@ -65,9 +67,15 @@ protected function parseOptions(array $options): array
return array_reduce(array_map($mapper, $options), $reducer, []);
}

public function setTimeout($timeout) {
$this->timeout = $timeout;
return $this;
}

public function text(): string
{
$process = new Process(array_merge([$this->binPath], $this->options, [$this->pdf, '-']));
$process->setTimeout($this->timeout);
$process->run();
if (!$process->isSuccessful()) {
throw new CouldNotExtractText($process);
Expand All @@ -76,10 +84,11 @@ public function text(): string
return trim($process->getOutput(), " \t\n\r\0\x0B\x0C");
}

public static function getText(string $pdf, ?string $binPath = null, array $options = []): string
public static function getText(string $pdf, ?string $binPath = null, array $options = [], $timeout = 60): string
{
return (new static($binPath))
->setOptions($options)
->setTimeout($timeout)
->setPdf($pdf)
->text()
;
Expand Down
12 changes: 12 additions & 0 deletions tests/PdfToTextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Spatie\PdfToText\Exceptions\CouldNotExtractText;
use Spatie\PdfToText\Exceptions\PdfNotFound;
use Spatie\PdfToText\Pdf;
use Symfony\Component\Process\Exception\InvalidArgumentException;

class PdfToTextTest extends TestCase
{
Expand Down Expand Up @@ -135,4 +136,15 @@ public function it_allows_for_options_to_be_added_programatically_without_overri
$this->assertStringNotContainsString("This is page 1", $text);
$this->assertStringNotContainsString("This is page 3", $text);
}

/** @test */
public function it_will_throw_an_exception_when_timeout_is_a_negative_number()
{
$this->expectException(InvalidArgumentException::class);

$text = (new Pdf($this->pdftotextPath))
->setPdf($this->dummyPdf)
->setTimeout(-1)
->text();
}
}

0 comments on commit 8eca492

Please sign in to comment.