Skip to content
Snippets Groups Projects

Resolve #3459123 "Add basic tests"

Merged Scott Euser requested to merge issue/page_to_pdf-3459123:3459123-add-basic-tests into 1.0.x
Files
4
<?php
namespace Drupal\page_to_pdf_test\Plugin\PdfGenerator;
use Drupal\Core\File\Exception\FileException;
use Drupal\page_to_pdf\Plugin\PdfGenerator\DoppioPdfGenerator;
/**
* Provides a Test PDF Generator Service.
*
* @PdfGenerator(
* id = "test_pdf",
* label = @Translation("Test PDF"),
* )
*/
class TestPdfGenerator extends DoppioPdfGenerator {
/**
* {@inheritdoc}
*/
public function generatePdf(string $page_url, string $output_file_uri, array $options = []): void {
try {
// Instead of calling the actual API, directly save the mock PDF data.
$this->saveMockPdfToFile($output_file_uri);
}
catch (\Exception $e) {
$this->logger
->error($this->t("Mock PDF generation failed with exception: '@error_message'.", ["@error_message" => $e->getMessage()]));
}
}
/**
* Save mock PDF data to the given file.
*
* @param string $path
* Destination file path.
*/
protected function saveMockPdfToFile(string $path): void {
// Mock PDF content.
$pdf_data = <<<PDF
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Count 1 /Kids [3 0 R] >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>
endobj
4 0 obj
<< /Length 55 >>
stream
BT
/F1 24 Tf
100 700 Td
(This is a mock PDF file.) Tj
ET
endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
xref
0 6
0000000000 65535 f
0000000010 00000 n
0000000074 00000 n
0000000123 00000 n
0000000220 00000 n
0000000321 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
390
%%EOF
PDF;
// Create directory.
$directory = $this->fileSystem->dirname($path);
if (!$this->fileSystem->prepareDirectory($directory)) {
if (!$this->fileSystem->mkdir($directory)) {
throw new FileException(\sprintf('Could not create the directory %s.', $directory));
}
}
// Save the file.
if (file_exists($path) && !is_writable($path)) {
throw new FileException(\sprintf('The file %s is not writable.', $path));
}
if (!$this->fileSystem->saveData($pdf_data, $path)) {
throw new FileException(\sprintf('The file %s could not be saved.', $path));
}
}
}
Loading