-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPdf.php
More file actions
75 lines (60 loc) · 1.99 KB
/
Pdf.php
File metadata and controls
75 lines (60 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/*
* This file is part of the Klipper package.
*
* (c) François Pluchino <francois.pluchino@klipper.dev>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Klipper\Component\PdfGenerator;
use Symfony\Component\Filesystem\Filesystem;
/**
* @author François Pluchino <francois.pluchino@klipper.dev>
*/
class Pdf implements PdfInterface
{
private GeneratorInterface $generator;
private Filesystem $filesystem;
private string $tempDirectory;
public function __construct(
GeneratorInterface $generator,
?string $tempDirectory = null,
?Filesystem $filesystem = null
) {
$this->generator = $generator;
$this->tempDirectory = $tempDirectory ?? sys_get_temp_dir();
$this->filesystem = $filesystem ?: new Filesystem();
}
public function generate(string $originPath, ?string $targetPath = null, array $options = []): \SplFileInfo
{
return $this->generator->generate($originPath, $targetPath, $options);
}
/**
* @throws
*/
public function generateFromContent(string $content, ?string $targetPath = null, array $options = []): \SplFileInfo
{
$filename = $this->getUniqueFilename();
try {
$this->filesystem->dumpFile($filename, $content);
$pdfFile = $this->generate($filename, $targetPath, $options);
$this->filesystem->remove($filename);
} catch (\Throwable $e) {
$this->filesystem->remove($filename);
throw $e;
}
return $pdfFile;
}
private function getUniqueFilename(): string
{
do {
$filename = md5(time().mt_rand()).'.html';
} while (!$this->isUniqueName($filename));
return $this->tempDirectory.'/'.$filename;
}
private function isUniqueName(string $filename): bool
{
return !$this->filesystem->exists($this->tempDirectory.'/'.$filename);
}
}