forked from Padam87/RasterizeBundle
/
Rasterizer.php
105 lines (85 loc) · 2.53 KB
/
Rasterizer.php
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace Padam87\RasterizeBundle;
use Symfony\Component\Stopwatch\Stopwatch;
class Rasterizer
{
/**
* @var ConfigHelper
*/
protected $configHelper;
/**
* @var Stopwatch
*/
protected $stopwatch;
/**
* @param ConfigHelper $configHelper
* @param Stopwatch $stopwatch
*/
public function __construct(ConfigHelper $configHelper, Stopwatch $stopwatch = null)
{
$this->configHelper = $configHelper;
$this->stopwatch = $stopwatch;
}
/**
* @param string $html
* @param array $arguments
* @param string $uniqueId
*
* @return string
*/
public function rasterize($html, $arguments = array(), $uniqueId = "")
{
if ($uniqueId === "") {
$uniqueId = uniqid("rasterize-");
}
if ($this->stopwatch instanceof Stopwatch) {
$this->stopwatch->start($uniqueId);
}
$input = $this->configHelper->getInputFilePath($uniqueId);
$fh = fopen($input, 'w');
fwrite($fh, $html);
fclose($fh);
$output = $this->rasterizeUrl($this->configHelper->getOutputFileUrl($uniqueId), $arguments, $uniqueId);
unlink($input);
return $output;
}
/**
* @param $url
* @param array $arguments
* @param string $uniqueId
*
* @throws \Exception
*
* @return string
*/
public function rasterizeUrl($url, $arguments = array(), $uniqueId = "")
{
if ($uniqueId === "") {
$uniqueId = uniqid("rasterize-");
}
if ($this->stopwatch instanceof Stopwatch) {
if ($this->stopwatch->isStarted($uniqueId)) {
$this->stopwatch->lap($uniqueId);
} else {
$this->stopwatch->start($uniqueId);
}
}
$process = $this->configHelper->buildProcess($url, $uniqueId, $arguments);
$exitCode = $process->run();
if ($exitCode != 0) {
throw new \Exception(sprintf(
"Rasterize script failed.\nCommandLine: %s\nExitCode: %d\nErrorOutput: %s",
$process->getCommandLine(),
$process->getExitCode(),
$process->getErrorOutput()
));
}
if ($this->stopwatch instanceof Stopwatch) {
$this->stopwatch->stop($uniqueId);
}
$output = $this->configHelper->getOutputFilePath($uniqueId);
$content = file_get_contents($output);
unlink($output);
return $content;
}
}