tex/src/BaseCompiler.php

99 lines
3.0 KiB
PHP

<?php
namespace Zoomyboy\Tex;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Log;
abstract class BaseCompiler implements Responsable
{
protected File $file;
public function compile(Document $document): self
{
$this->prepareForCompilation($document);
$contents = $document->renderBody();
file_put_contents("{$this->file->getPath()}/{$document->filename()}", $contents);
if ($document->template()) {
$templatePath = $document->template()->fullPath();
exec('rsync -av '.escapeshellarg($templatePath).'/ '.escapeshellarg($this->file->getPath()));
}
exec($this->command($document), $output, $returnVar);
if (0 !== $returnVar) {
Log::error('Compilation failed', ['body' => $contents, 'output' => $output, 'dir' => $this->file->getPath(), 'command' => $this->command($document)]);
throw (new CompilerException('Compilation failed.'))->setOutput($output);
}
$this->refreshFile();
if (!$this->file->isFile()) {
Log::error('Compilation failed', ['body' => $contents, 'output' => $output, 'dir' => $this->file->getPath(), 'command' => $this->command($document)]);
throw (new CompilerException('Compilation failed.'))->setOutput($output);
}
return $this;
}
public function storeAs(string $directory, string $name, string $disk): string
{
$contents = $this->file->getContent();
Storage::disk($disk)->put($directory.'/'.$name, $contents);
$this->cleanup();
return $directory.'/'.$name;
}
public function storeIn(string $directory, string $disk): string
{
return $this->storeAs($directory, $this->file->getFilename(), $disk);
}
public function toResponse($request)
{
return response()->file($this->file->getRealPath(), [
'Content-Type' => 'application/pdf',
'Content-Disposition' => "inline; filename=\"{$this->file->getFilename()}\"",
]);
}
public function getPath(): string
{
return $this->file->getRealPath();
}
protected function prepareForCompilation(Document $document): void
{
$workDir = '/tmp/'.Str::random(32);
mkdir($workDir, 0777, true);
$this->file = new File($workDir.'/'.$document->compiledFilename(), false);
}
private function refreshFile(): void
{
$this->file = new File($this->file->getPathname(), false);
}
private function command(Document $document): string
{
return collect([
'cd '.escapeshellarg($this->file->getPath()),
$document->getEngine()->binary().' --halt-on-error '.escapeshellarg($document->filename()),
$document->getEngine()->binary().' --halt-on-error '.escapeshellarg($document->filename()),
])->implode(' && ');
}
private function cleanup(): void
{
exec('rm -R '.$this->file->getPath());
}
}