Skip to content

Instantly share code, notes, and snippets.

@DASPRiD
Created April 10, 2018 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DASPRiD/266b5535a283d47cab20dea23f4bf85a to your computer and use it in GitHub Desktop.
Save DASPRiD/266b5535a283d47cab20dea23f4bf85a to your computer and use it in GitHub Desktop.
<?php
declare(strict_types = 1);
namespace Project\Infrastructure\Pdf;
use Project\Infrastructure\Pdf\Exception\FopException;
final class PdfGenerator
{
/**
* @var string
*/
public $fopPath;
/**
* @var string
*/
private $baseDirectory;
public function __construct(string $fopPath, string $baseDirectory)
{
$this->fopPath = $fopPath;
$this->baseDirectory = realpath($baseDirectory);
}
public function __invoke(string $xml, string $templateFilename) : string
{
$xslPath = implode('/', [$this->baseDirectory, $templateFilename]);
$command = sprintf(
'%s -xml - -xsl %s -pdf - -c %s',
escapeshellcmd($this->fopPath),
escapeshellarg($xslPath),
escapeshellarg(implode('/', [$this->baseDirectory, 'fop.xml']))
);
$descriptorSpecs = [
['pipe', 'r'],
['pipe', 'w'],
['pipe', 'w'],
];
$process = proc_open(
$command,
$descriptorSpecs,
$pipes,
$this->baseDirectory
);
if (! is_resource($process)) {
throw FopException::fromProcessCreateFailure();
}
fwrite($pipes[0], $xml);
fclose($pipes[0]);
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$stderr = '';
$stdout = '';
while (! feof($pipes[1]) || ! feof($pipes[2])) {
if (! feof($pipes[1])) {
$stdout .= stream_get_contents($pipes[1]);
}
if (! feof($pipes[2])) {
$stderr .= stream_get_contents($pipes[2]);
}
}
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode > 0) {
throw FopException::fromRunError($command, $stderr);
}
return $stdout;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment