Files
myep-team/src/Service/Pdf/Sanitizer.php
T

86 lines
2.3 KiB
PHP

<?php
namespace App\Service\Pdf;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
class Sanitizer
{
public function __construct(
private readonly string $binGs,
private readonly string $binConvert,
private readonly string $tempDir,
) {
}
/**
* @throws \InvalidArgumentException
*/
public function sanitizeFile(string $inputFilepath, ?string $targetFilepath = null, bool $backup = true): string
{
$filesystem = new Filesystem();
if (true === $backup) {
$parts = pathinfo($inputFilepath);
$backupFilename = sprintf('%s/%s.orig.%s', $parts['dirname'], $parts['filename'], $parts['extension']);
$filesystem->copy($inputFilepath, $backupFilename);
}
$tempFilename = sha1($inputFilepath);
$outputFilepath = $this->tempDir.'/'.$tempFilename;
$pdfFilepath = null;
if (null === $targetFilepath) {
$targetFilepath = $inputFilepath.'.pdf';
}
if ('pdf' !== pathinfo($inputFilepath, PATHINFO_EXTENSION)) {
$pdfFilepath = $outputFilepath.'.pdf';
$command = [
$this->binConvert,
$inputFilepath,
$pdfFilepath,
];
$process = new Process($command);
$process->run();
if (false === $process->isSuccessful()) {
throw new \InvalidArgumentException('File could not be sanitized: '.$process->getErrorOutput());
}
$inputFilepath = $pdfFilepath;
}
$command = [
$this->binGs,
'-dNOPAUSE',
'-dQUIET',
'-dBATCH',
'-dPreserveAnnots=false',
'-sDEVICE=pdfwrite',
'-dCompatibilityLevel=1.4',
'-sOutputFile='.$outputFilepath,
'-f',
$inputFilepath,
];
$process = new Process($command);
$process->run();
if (false === $process->isSuccessful()) {
throw new \InvalidArgumentException('File could not be sanitized: '.$process->getErrorOutput());
}
$filesystem->rename($outputFilepath, $targetFilepath, true);
if (null !== $pdfFilepath) {
$filesystem->remove($pdfFilepath);
}
return $targetFilepath;
}
}