Skip to content

Commit

Permalink
Merge pull request #78 from enricodelazzari/main
Browse files Browse the repository at this point in the history
ADD setEnv to Pdf
  • Loading branch information
freekmurze authored Aug 29, 2024
2 parents 5dc19fa + 047feff commit abe38b0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Pdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\PdfToText;

use Closure;
use Spatie\PdfToText\Exceptions\CouldNotExtractText;
use Spatie\PdfToText\Exceptions\PdfNotFound;
use Symfony\Component\Process\Process;
Expand All @@ -16,6 +17,8 @@ class Pdf

protected int $timeout = 60;

protected array $env = [];

public function __construct(?string $binPath = null)
{
$this->binPath = $binPath ?? '/usr/bin/pdftotext';
Expand Down Expand Up @@ -70,10 +73,11 @@ public function setTimeout($timeout) {
return $this;
}

public function text(): string
public function text(?Closure $callback = null): string
{
$process = new Process(array_merge([$this->binPath], $this->options, [$this->pdf, '-']));
$process->setTimeout($this->timeout);
$process = $callback ? $callback($process) : $process;
$process->run();
if (!$process->isSuccessful()) {
throw new CouldNotExtractText($process);
Expand All @@ -82,13 +86,13 @@ 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 = [], $timeout = 60): string
public static function getText(string $pdf, ?string $binPath = null, array $options = [], $timeout = 60, ?Closure $callback = null): string
{
return (new static($binPath))
->setOptions($options)
->setTimeout($timeout)
->setPdf($pdf)
->text()
->text($callback)
;
}
}
15 changes: 15 additions & 0 deletions tests/PdfToTextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Spatie\PdfToText\Exceptions\PdfNotFound;
use Spatie\PdfToText\Pdf;
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Process;

uses(PHPUnit\Framework\TestCase::class);

Expand Down Expand Up @@ -93,3 +94,17 @@
->setTimeout(-1)
->text()
)->throws(InvalidArgumentException::class);

it('can handle symfony process by callback', function () {
$text = (new Pdf('pdftotext'))
->setPdf($this->dummyPdf)
->text(fn (Process $process) => $process);

expect($text)->toBe($this->dummyPdfText);
});

it('can handle symfony process by callback using a static method', function () {
$text = Pdf::getText($this->dummyPdf, 'pdftotext', [], 60, fn (Process $process) => $process);

expect($text)->toBe($this->dummyPdfText);
});

0 comments on commit abe38b0

Please sign in to comment.