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): void { $contents = $this->file->getContent(); Storage::disk($disk)->put($name, $contents); } public function storeIn(string $directory, string $disk): string { $contents = $this->file->getContent(); Storage::disk($disk)->put($directory.'/'.$this->file->getFilename(), $contents); return $this->file->getFilename(); } 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(' && '); } }