diff --git a/src/Command/ConvertUploadsCommand.php b/src/Command/ConvertUploadsCommand.php new file mode 100644 index 0000000..5358925 --- /dev/null +++ b/src/Command/ConvertUploadsCommand.php @@ -0,0 +1,60 @@ +entityManager + ->getRepository(Upload::class) + ->findBy([ + 'type' => [Upload::TYPE_INVOICE, Upload::TYPE_CONTRACT], + ]); + + $progressBar = new ProgressBar($output, count($uploads)); + $progressBar->start(); + + foreach ($uploads as $upload) { + /** @var Upload $upload */ + $filepath = $this->uploadHandler->getUploadFilepath($upload); + try { + $targetFilepath = $this->sanitizer->sanitizeFile($filepath); + $upload + ->setFilename(basename($targetFilepath)) + ->setMimeType('application/pdf') + ; + } catch (\Throwable $e) { + } + + $progressBar->advance(); + } + + $this->entityManager->flush(); + $progressBar->finish(); + + return Command::SUCCESS; + } +} diff --git a/src/Service/Pdf/Sanitizer.php b/src/Service/Pdf/Sanitizer.php index 4915c40..12f9dc5 100644 --- a/src/Service/Pdf/Sanitizer.php +++ b/src/Service/Pdf/Sanitizer.php @@ -2,6 +2,7 @@ namespace App\Service\Pdf; +use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Process\Process; @@ -16,11 +17,16 @@ class Sanitizer /** * @throws \InvalidArgumentException + * @throws FileNotFoundException */ public function sanitizeFile(string $inputFilepath, ?string $targetFilepath = null, bool $backup = true): string { $filesystem = new Filesystem(); + if (false === $filesystem->exists($inputFilepath)) { + throw new FileNotFoundException(); + } + if (true === $backup) { $parts = pathinfo($inputFilepath); $backupFilename = sprintf('%s/%s.orig.%s', $parts['dirname'], $parts['filename'], $parts['extension']); @@ -32,7 +38,8 @@ class Sanitizer $pdfFilepath = null; if (null === $targetFilepath) { - $targetFilepath = $inputFilepath.'.pdf'; + $parts = pathinfo($inputFilepath); + $targetFilepath = sprintf('%s/%s.%s', $parts['dirname'], $parts['filename'], $parts['extension']); } if ('pdf' !== pathinfo($inputFilepath, PATHINFO_EXTENSION)) { @@ -51,7 +58,10 @@ class Sanitizer throw new \InvalidArgumentException('File could not be sanitized: '.$process->getErrorOutput()); } + $filesystem->remove($inputFilepath); + $inputFilepath = $pdfFilepath; + $targetFilepath.= '.pdf'; } $command = [ @@ -61,7 +71,7 @@ class Sanitizer '-dBATCH', '-dPreserveAnnots=false', '-sDEVICE=pdfwrite', - '-dCompatibilityLevel=1.4', + '-dCompatibilityLevel=1.5', '-sOutputFile='.$outputFilepath, '-f', $inputFilepath,