View source
<?php
namespace Drupal\Tests\fillpdf\Functional;
use Drupal\file\Entity\File;
use Drupal\fillpdf\Component\Utility\FillPdf;
use Drupal\fillpdf\Entity\FillPdfForm;
use Drupal\fillpdf\FieldMapping\ImageFieldMapping;
use Drupal\fillpdf\FieldMapping\TextFieldMapping;
use Drupal\fillpdf_test\Plugin\FillPdfBackend\TestFillPdfBackend;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
use Drupal\user\Entity\Role;
if (!trait_exists('\\Drupal\\Tests\\taxonomy\\Traits\\TaxonomyTestTrait')) {
class_alias('\\Drupal\\Tests\\taxonomy\\Functional\\TaxonomyTestTrait', '\\Drupal\\Tests\\taxonomy\\Traits\\TaxonomyTestTrait');
}
class PdfPopulationTest extends FillPdfTestBase {
use TaxonomyTestTrait;
public static $modules = [
'filter',
'taxonomy',
];
protected $testVocabulary;
protected function setUp() {
parent::setUp();
$existing_user_roles = $this->adminUser
->getRoles(TRUE);
$role_to_modify = Role::load(end($existing_user_roles));
$this
->grantPermissions($role_to_modify, [
'administer image styles',
'use text format restricted_html',
]);
$this->testVocabulary = $this
->createVocabulary();
$this
->configureFillPdf();
}
public function testPdfPopulation() {
$this
->uploadTestPdf('fillpdf_test_v3.pdf');
$this
->assertSession()
->pageTextContains('New FillPDF form has been created.');
$fillpdf_form = FillPdfForm::load($this
->getLatestFillPdfForm());
$fillpdf_form->replacements = 'Hello & how are you?|Hello & how is it going?';
$fillpdf_form
->save();
FillPdfTestBase::mapFillPdfFieldsToEntityFields('node', $fillpdf_form
->getFormFields());
$node = $this
->createNode([
'title' => 'Hello & how are you?',
'type' => 'article',
'body' => [
[
'value' => "<p>PDF form fields don't accept <em>any</em> HTML.</p>",
'format' => 'restricted_html',
],
],
]);
$url = $this->linkManipulator
->generateLink([
'fid' => $fillpdf_form
->id(),
'entity_ids' => [
'node' => [
$node
->id(),
],
],
]);
$this
->drupalGet($url);
$populate_result = $this->container
->get('state')
->get('fillpdf_test.last_populated_metadata');
self::assertEquals('Hello & how are you doing?', $populate_result['field_mapping']['fields']['TextField1'], 'PDF is populated with the title of the node with all HTML stripped.');
self::assertEquals("PDF form fields don't accept any HTML.\n", $populate_result['field_mapping']['fields']['TextField2'], 'PDF is populated with the node body. HTML is stripped but a newline
replaces the <p> tags.');
}
public function testSamplePdf() {
$this
->uploadTestPdf('fillpdf_test_v3.pdf');
$fillpdf_form = FillPdfForm::load($this
->getLatestFillPdfForm());
$url = $this->linkManipulator
->generateLink([
'fid' => $fillpdf_form
->id(),
'sample' => 1,
]);
$this
->drupalGet($url);
$populate_result = $this->container
->get('state')
->get('fillpdf_test.last_populated_metadata');
self::assertEquals('<TextField1>', $populate_result['field_mapping']['fields']['TextField1'], 'Sample field mapped properly.');
}
public function testImageStamping() {
$this
->uploadTestPdf('fillpdf_test_v3.pdf');
$this
->assertSession()
->pageTextContains('New FillPDF form has been created.');
$fillpdf_form = FillPdfForm::load($this
->getLatestFillPdfForm());
$testCases = [
'node' => 'article',
'taxonomy_term' => $this->testVocabulary
->id(),
'user' => 'user',
];
foreach ($testCases as $entity_type => $bundle) {
$this
->createImageField('field_fillpdf_test_image', $entity_type, $bundle);
$storage = \Drupal::entityTypeManager()
->getStorage($entity_type);
$entity = $storage
->load($this
->createImageFieldEntity($this->testImage, 'field_fillpdf_test_image', $entity_type, $bundle, 'FillPDF Test image'));
FillPdfTestBase::mapFillPdfFieldsToEntityFields($entity_type, $fillpdf_form
->getFormFields());
$url = $this->linkManipulator
->generateLink([
'fid' => $fillpdf_form
->id(),
'entity_ids' => [
$entity_type => [
$entity
->id(),
],
],
]);
$this
->drupalGet($url);
$populate_result = $this->container
->get('state')
->get('fillpdf_test.last_populated_metadata');
$file = File::load($entity->field_fillpdf_test_image->target_id);
self::assertArrayHasKey('ImageField', $populate_result['field_mapping']['images'], "{$entity_type} isn't populated with an image.");
self::assertEquals($populate_result['field_mapping']['images']['ImageField']['data'], base64_encode(file_get_contents($file
->getFileUri())), 'Encoded image matches known image.');
$path_info = pathinfo($file
->getFileUri());
$expected_file_hash = md5($path_info['filename']) . '.' . $path_info['extension'];
self::assertEquals($populate_result['field_mapping']['images']['ImageField']['filenamehash'], $expected_file_hash, 'Hashed filename matches known hash.');
self::assertEquals($populate_result['field_mapping']['fields']['ImageField'], "{image}{$file->getFileUri()}", 'URI in metadata matches expected URI.');
}
}
public function testPluginApi() {
$this
->uploadTestPdf('fillpdf_test_v3.pdf');
$fillpdf_form = FillPdfForm::load($this
->getLatestFillPdfForm());
$actual_keys = [];
foreach (array_keys($fillpdf_form
->getFormFields()) as $pdf_key) {
$actual_keys[] = $pdf_key;
}
sort($actual_keys);
$expected_keys = [];
foreach (TestFillPdfBackend::getParseResult() as $expected_field) {
$expected_keys[] = $expected_field['name'];
}
sort($expected_keys);
$this
->assertCount(5, $expected_keys);
$this
->assertCount(4, $actual_keys);
$differences = array_diff($expected_keys, $actual_keys);
self::assertEmpty($differences, 'Parsed fields are in fixture match.');
$backend_service = $this->backendServiceManager
->createInstance('test');
$original_pdf = file_get_contents($this
->getTestPdfPath('fillpdf_test_v3.pdf'));
$actual_keys = [];
foreach ($backend_service
->parse($original_pdf) as $parsed_field) {
$actual_keys[] = $parsed_field['name'];
}
sort($actual_keys);
$this
->assertCount(5, $expected_keys);
$this
->assertCount(5, $actual_keys);
$differences = array_diff($expected_keys, $actual_keys);
self::assertEmpty($differences, 'Parsed fields from plugin are in fixture match.');
$merged_pdf = $backend_service
->merge($original_pdf, [
'Foo' => new TextFieldMapping('bar'),
'Foo2' => new TextFieldMapping('bar2'),
'Image1' => new ImageFieldMapping(file_get_contents($this->testImage
->getFileUri()), 'png'),
], []);
self::assertEquals($original_pdf, $merged_pdf);
$merge_state = $this->container
->get('state')
->get('fillpdf_test.last_populated_metadata');
self::assertInstanceOf(TextFieldMapping::class, $merge_state['field_mapping']['Foo'], 'Field "Foo" was mapped to a TextFieldMapping object.');
self::assertInstanceOf(TextFieldMapping::class, $merge_state['field_mapping']['Foo2'], 'Field "Foo2" was mapped to a TextFieldMapping object.');
self::assertInstanceOf(ImageFieldMapping::class, $merge_state['field_mapping']['Image1'], 'Field "Image1" was mapped to an ImageFieldMapping object.');
}
public function testProxyMerge() {
$this
->uploadTestPdf('fillpdf_test_v3.pdf');
$fillpdf_form = FillPdfForm::load($this
->getLatestFillPdfForm());
$merge_proxy = $this->container
->get('fillpdf.backend_proxy');
$original_pdf = file_get_contents($this
->getTestPdfPath('fillpdf_test_v3.pdf'));
FillPdfTestBase::mapFillPdfFieldsToEntityFields('node', $fillpdf_form
->getFormFields());
$node = $this
->createNode([
'title' => 'Hello & how are you?',
'type' => 'article',
'body' => [
[
'value' => "<p>PDF form fields don't accept <em>any</em> HTML.</p>",
'format' => 'restricted_html',
],
],
]);
$entities['node'] = [
$node
->id() => $node,
];
$merged_pdf = $merge_proxy
->merge($fillpdf_form, $entities);
self::assertEquals($original_pdf, $merged_pdf);
$merge_state = $this->container
->get('state')
->get('fillpdf_test.last_populated_metadata');
self::assertInternalType('array', $merge_state, 'Test backend was used.');
self::assertArrayHasKey('field_mapping', $merge_state, 'field_mapping key from test backend is present.');
self::assertArrayHasKey('context', $merge_state, 'context key from test backend is present.');
self::assertEquals('Hello & how are you doing?', $merge_state['field_mapping']['fields']['TextField1']);
self::assertEquals("PDF form fields don't accept any HTML.\n", $merge_state['field_mapping']['fields']['TextField2']);
}
public function testMergeLocalService() {
$this
->configureLocalServiceBackend();
$config = $this->container
->get('config.factory')
->get('fillpdf.settings');
if (!FillPdf::checkLocalServiceEndpoint($this->container
->get('http_client'), $config)) {
throw new \PHPUnit_Framework_SkippedTestError('FillPDF LocalServer unavailable, so skipping test.');
}
$this
->backendTest();
}
public function testMergePdftk() {
$this
->configureFillPdf([
'backend' => 'pdftk',
]);
if (!FillPdf::checkPdftkPath()) {
throw new \PHPUnit_Framework_SkippedTestError('pdftk not available, so skipping test.');
}
$this
->backendTest();
}
protected function backendTest() {
$this
->uploadTestPdf('fillpdf_Ŧäßð_v3â.pdf');
$fillpdf_form = FillPdfForm::load($this
->getLatestFillPdfForm());
$fields = $fillpdf_form
->getFormFields();
FillPdfTestBase::mapFillPdfFieldsToEntityFields('node', $fields);
$node = $this
->createNode([
'title' => 'Test',
'type' => 'article',
]);
$url = $this->linkManipulator
->generateLink([
'fid' => $fillpdf_form
->id(),
'entity_ids' => [
'node' => [
$node
->id(),
],
],
]);
$this
->drupalGet($url);
$maybe_pdf = $this
->getSession()
->getPage()
->getContent();
static::assertEquals('application/pdf', $this
->getMimeType($maybe_pdf));
$this
->drupalGet('<front>');
$this
->assertSession()
->pageTextNotContains('Merging the FillPDF Form failed');
}
}