Skip to content
Snippets Groups Projects
Commit 056ccf7a authored by wizonesolutions's avatar wizonesolutions Committed by Kevin Kaland
Browse files

Issue #2922465 by wizonesolutions: Make backend plugins reusable

parent 3e992f6f
No related branches found
Tags 8.x-4.5
No related merge requests found
Showing
with 533 additions and 41 deletions
...@@ -15,7 +15,7 @@ services: ...@@ -15,7 +15,7 @@ services:
# entities into a context...well, it might in the future. # entities into a context...well, it might in the future.
fillpdf.context_manager: fillpdf.context_manager:
class: Drupal\fillpdf\Service\FillPdfContextManager class: Drupal\fillpdf\Service\FillPdfContextManager
arguments: ['@entity.manager'] arguments: ['@entity_type.manager']
plugin.manager.fillpdf_action.processor: plugin.manager.fillpdf_action.processor:
class: Drupal\fillpdf\Plugin\FillPdfActionPluginManager class: Drupal\fillpdf\Plugin\FillPdfActionPluginManager
...@@ -49,3 +49,10 @@ services: ...@@ -49,3 +49,10 @@ services:
class: Drupal\fillpdf\InputHelper class: Drupal\fillpdf\InputHelper
arguments: ["@config.factory", "@plugin.manager.fillpdf_backend"] arguments: ["@config.factory", "@plugin.manager.fillpdf_backend"]
# I really wanted to call this one Backend, but then the machine name wouldn't
# work out. Oh well...I don't totally like BackendService, but it's generic
# enough to not be TOO confusing. It kind of invokves the thought of a
# Symfony service, but it's probably clear enough given the context.
plugin.manager.fillpdf_backend_service:
class: Drupal\fillpdf\Plugin\BackendServiceManager
parent: default_plugin_manager
<?php
namespace Drupal\fillpdf\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines a FillPDF BackendService item annotation object.
*
* @see \Drupal\fillpdf\Plugin\BackendServiceManager
* @see plugin_api
*
* @Annotation
*/
class BackendService extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The label of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $label;
}
<?php
namespace Drupal\fillpdf;
/**
* Represents a mapping between a PDF field and a merge value (a value with
* which to fill in the field). This is a barebones base class intended to be
* subclassed and enhanced with additional properties and getter methods.
*
* FieldMapping objects are immutable; replace the value by calling the
* constructor again if the value needs to change.
*/
abstract class FieldMapping {
/**
* @var mixed
*
* The primary value of the mapping.
*/
protected $data;
public function __construct($data) {
$this->data = $data;
}
public function getData() {
return $this->data;
}
}
<?php
namespace Drupal\fillpdf\FieldMapping;
use Drupal\fillpdf\FieldMapping;
class ImageFieldMapping extends FieldMapping {
/**
* @var string
*
* The common extension (jpg, png, or gif) corresponding to the type of image
* data sent through.
*/
protected $extension;
/**
* @param $data
* @param $extension
*
* @throws \InvalidArgumentException
*/
public function __construct($data, $extension) {
parent::__construct($data);
if (!in_array($extension, ['jpg', 'png', 'gif'])) {
throw new \InvalidArgumentException('Extension must be one of: jpg, png, gif.');
}
}
/**
* @return string
*/
public function getExtension() {
return $this->extension;
}
}
<?php
namespace Drupal\fillpdf\FieldMapping;
use Drupal\fillpdf\FieldMapping;
final class TextFieldMapping extends FieldMapping {
/**
* @var string
*/
protected $data;
public function __construct($data) {
// Ensure data is a string.
parent::__construct((string) $data);
}
/**
* @return string
*/
public function getData() {
return parent::getData();
}
}
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
namespace Drupal\fillpdf; namespace Drupal\fillpdf;
/** /**
* Defines the required interface for all FillPDF Backend plugins. * Defines the required interface for all FillPDF BackendService plugins.
* *
* @package Drupal\fillpdf * @package Drupal\fillpdf
* *
......
<?php
namespace Drupal\fillpdf\Plugin;
use Drupal\Component\Plugin\PluginBase;
/**
* Base class for FillPDF BackendService plugins.
*/
abstract class BackendServiceBase extends PluginBase implements BackendServiceInterface {
// Add common methods and abstract methods for your plugin type here.
}
<?php
namespace Drupal\fillpdf\Plugin;
use Drupal\Component\Plugin\PluginInspectionInterface;
/**
* Defines an interface for FillPDF BackendService plugins.
*/
interface BackendServiceInterface extends PluginInspectionInterface {
/**
* Parse a PDF and return a list of its fields.
*
* @param string $pdf
* The PDF whose fields are going to be parsed. This should be the contents
* of a PDF loaded with something like file_get_contents() or equivalent.
* @return array An array of arrays containing metadata about
* the fields in the PDF. These can be iterated over and saved by the
* caller.
*/
public function parse($pdf);
/**
* Accept an array of PDF field keys and field
* values and populate the PDF using them.
*
* @param string $pdf The PDF into which to merge the field values specified
* in the mapping.
* @param array $field_mappings FieldMapping[]
* An array of FieldMapping-derived objects mapping PDF field keys to the
* values with which they should be replaced. Strings are also acceptable
* and converted to TextFieldMapping objects.
*
* Example array:
*
* @code
* [
* 'Foo' => new TextFieldMapping('bar'),
* 'Foo2' => new TextFieldMapping('bar2'),
* 'Image1' => new ImageFieldMapping(base64_encode(file_get_contents($image)), 'jpg'),
* ]
* @endcode
* @param array $options
* Additional options, usually relating to plugin-specific functionality.
* @return string The raw file contents of the new PDF; the caller has to
* handle saving or serving the file accordingly.
*/
public function merge($pdf, array $field_mappings, array $options);
}
<?php
namespace Drupal\fillpdf\Plugin;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
/**
* Provides the FillPDF BackendService plugin manager.
*/
class BackendServiceManager extends DefaultPluginManager {
/**
* Constructs a new BackendServiceManager object.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler to invoke the alter hook with.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/BackendService', $namespaces, $module_handler, 'Drupal\fillpdf\Plugin\BackendServiceInterface', 'Drupal\fillpdf\Annotation\BackendService');
$this->alterInfo('fillpdf_fillpdf_backend_info');
$this->setCacheBackend($cache_backend, 'fillpdf_fillpdf_backend_plugins');
}
}
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
namespace Drupal\fillpdf\Service; namespace Drupal\fillpdf\Service;
use Drupal\Core\Entity\EntityManagerInterface; use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\fillpdf\FillPdfContextManagerInterface; use Drupal\fillpdf\FillPdfContextManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
class FillPdfContextManager implements FillPdfContextManagerInterface { class FillPdfContextManager implements FillPdfContextManagerInterface {
/** @var EntityManagerInterface $entityManager */ /** @var EntityTypeManagerInterface $entityTypeManager */
protected $entityManager; protected $entityTypeManager;
public function __construct(EntityManagerInterface $entity_manager) { public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityManager = $entity_manager; $this->entityTypeManager = $entity_type_manager;
} }
public static function create(ContainerInterface $container) { public static function create(ContainerInterface $container) {
...@@ -26,8 +26,7 @@ class FillPdfContextManager implements FillPdfContextManagerInterface { ...@@ -26,8 +26,7 @@ class FillPdfContextManager implements FillPdfContextManagerInterface {
$entities = []; $entities = [];
foreach ($context['entity_ids'] as $entity_type => $entity_ids) { foreach ($context['entity_ids'] as $entity_type => $entity_ids) {
// @todo: Switch to using EntityTypeManagerInterface in 8.0.0-rc3 $type_controller = $this->entityTypeManager->getStorage($entity_type);
$type_controller = $this->entityManager->getStorage($entity_type);
$entity_list = $type_controller->loadMultiple($entity_ids); $entity_list = $type_controller->loadMultiple($entity_ids);
if (!empty($entity_list)) { if (!empty($entity_list)) {
......
<?php
namespace Drupal\fillpdf_test\Plugin\BackendService;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\State\StateInterface;
use Drupal\fillpdf\Plugin\BackendServiceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* @BackendService(
* id = "test",
* label = @Translation("FillPDF Test Backend Service"),
* )
*/
class Test extends BackendServiceBase implements ContainerFactoryPluginInterface {
/**
* @var StateInterface
*/
protected $state;
public function __construct(array $configuration, $plugin_id, $plugin_definition, StateInterface $state) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->configuration = $configuration;
$this->state = $state;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration, $plugin_id, $plugin_definition,
$container->get('state')
);
}
/**
* {@inheritdoc}
*/
public function parse($pdf) {
return static::getParseResult();
}
/**
* {@inheritdoc}
*/
public function merge($pdf, array $field_mappings, array $options) {
$this->state->set('fillpdf_test.last_populated_metadata', array(
'field_mapping' => $field_mappings,
'options' => $options,
));
return file_get_contents(drupal_get_path('module', 'fillpdf_test') . '/files/fillpdf_test_v3.pdf');
}
public static function getParseResult() {
return [
0 => [
'name' => 'ImageField',
'value' => '',
'type' => 'Pushbutton',
],
1 => [
'name' => 'Button',
'value' => '',
'type' => 'Pushbutton',
],
2 => [
'name' => 'TextField',
'value' => '',
'type' => 'Text',
],
];
}
}
...@@ -46,7 +46,26 @@ class TestFillPdfBackend implements FillPdfBackendPluginInterface, ContainerFact ...@@ -46,7 +46,26 @@ class TestFillPdfBackend implements FillPdfBackendPluginInterface, ContainerFact
* @inheritdoc * @inheritdoc
*/ */
public function parse(FillPdfFormInterface $fillpdf_form) { public function parse(FillPdfFormInterface $fillpdf_form) {
$return = [ return static::getParseResult();
}
/**
* @inheritdoc
*/
public function populateWithFieldData(FillPdfFormInterface $pdf_form, array $field_mapping, array $context) {
// Not really populated, but that isn't our job.
$populated_pdf = file_get_contents(drupal_get_path('module', 'fillpdf_test') . '/files/fillpdf_test_v3.pdf');
$this->state->set('fillpdf_test.last_populated_metadata', [
'field_mapping' => $field_mapping,
'context' => $context,
]);
return $populated_pdf;
}
public static function getParseResult() {
return [
0 => [ 0 => [
'name' => 'ImageField', 'name' => 'ImageField',
'value' => '', 'value' => '',
...@@ -63,23 +82,6 @@ class TestFillPdfBackend implements FillPdfBackendPluginInterface, ContainerFact ...@@ -63,23 +82,6 @@ class TestFillPdfBackend implements FillPdfBackendPluginInterface, ContainerFact
'type' => 'Text', 'type' => 'Text',
], ],
]; ];
return $return;
}
/**
* @inheritdoc
*/
public function populateWithFieldData(FillPdfFormInterface $pdf_form, array $field_mapping, array $context) {
// Not really populated, but that isn't our job.
$populated_pdf = file_get_contents(drupal_get_path('module', 'fillpdf_test') . '/files/fillpdf_test_v3.pdf');
$this->state->set('fillpdf_test.last_populated_metadata', array(
'field_mapping' => $field_mapping,
'context' => $context,
));
return $populated_pdf;
} }
} }
...@@ -9,7 +9,6 @@ use Drupal\Tests\fillpdf\Traits\TestFillPdfTrait; ...@@ -9,7 +9,6 @@ use Drupal\Tests\fillpdf\Traits\TestFillPdfTrait;
/** /**
* Ensure Edit links for PDFs at /admin/structure/fillpdf function correctly. * Ensure Edit links for PDFs at /admin/structure/fillpdf function correctly.
* *
* @requires module fillpdf_test
* @group fillpdf * @group fillpdf
*/ */
class AdminIdTest extends BrowserTestBase { class AdminIdTest extends BrowserTestBase {
......
...@@ -8,8 +8,22 @@ use Drupal\Tests\BrowserTestBase; ...@@ -8,8 +8,22 @@ use Drupal\Tests\BrowserTestBase;
*/ */
abstract class FillPdfTestBase extends BrowserTestBase { abstract class FillPdfTestBase extends BrowserTestBase {
/**
* @var \Drupal\Core\Session\AccountInterface
*/
protected $adminUser;
public static $modules = ['node', 'image', 'field_ui', 'image_module_test', 'fillpdf_test'];
protected function setUp() { protected function setUp() {
parent::setUp(); parent::setUp();
// Create Basic page and Article node types.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
}
$this->adminUser = $this->drupalCreateUser(['access content', 'access administration pages', 'administer site configuration', 'administer content types', 'administer node fields', 'administer nodes', 'create article content', 'edit any article content', 'delete any article content', 'administer image styles', 'administer node display']);
$this->drupalLogin($this->adminUser);
} }
} }
...@@ -9,7 +9,6 @@ use Drupal\Tests\BrowserTestBase; ...@@ -9,7 +9,6 @@ use Drupal\Tests\BrowserTestBase;
* Tests the main FillPDF upload form. * Tests the main FillPDF upload form.
* *
* @group fillpdf * @group fillpdf
* @requires module fillpdf
*/ */
class OverviewFormTest extends BrowserTestBase { class OverviewFormTest extends BrowserTestBase {
......
...@@ -6,9 +6,15 @@ use Drupal\Component\Utility\UrlHelper; ...@@ -6,9 +6,15 @@ use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Url; use Drupal\Core\Url;
use Drupal\file\Entity\File; use Drupal\file\Entity\File;
use Drupal\fillpdf\Entity\FillPdfForm; use Drupal\fillpdf\Entity\FillPdfForm;
use Drupal\fillpdf\FieldMapping\ImageFieldMapping;
use Drupal\fillpdf\FieldMapping\TextFieldMapping;
use Drupal\fillpdf_test\Plugin\FillPdfBackend\TestFillPdfBackend;
use Drupal\node\Entity\Node; use Drupal\node\Entity\Node;
use Drupal\simpletest\Tests\BrowserTest;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\fillpdf\Traits\TestFillPdfTrait; use Drupal\Tests\fillpdf\Traits\TestFillPdfTrait;
use Drupal\Tests\image\Functional\ImageFieldTestBase; use Drupal\Tests\image\Functional\ImageFieldTestBase;
use Drupal\Tests\image\Kernel\ImageFieldCreationTrait;
use Drupal\Tests\TestFileCreationTrait; use Drupal\Tests\TestFileCreationTrait;
use Drupal\user\Entity\Role; use Drupal\user\Entity\Role;
use Drupal\webform\Entity\Webform; use Drupal\webform\Entity\Webform;
...@@ -18,14 +24,13 @@ use Drupal\webform\Entity\WebformSubmission; ...@@ -18,14 +24,13 @@ use Drupal\webform\Entity\WebformSubmission;
* Tests entity and Webform image stamping. * Tests entity and Webform image stamping.
* *
* @group fillpdf * @group fillpdf
* @requires module fillpdf_test
*/ */
class PdfPopulationTest extends ImageFieldTestBase { class PdfPopulationTest extends FillPdfTestBase {
use ImageFieldCreationTrait;
use TestFileCreationTrait; use TestFileCreationTrait;
use TestFillPdfTrait; use TestFillPdfTrait;
static public $modules = ['fillpdf_test'];
protected $profile = 'minimal'; protected $profile = 'minimal';
protected $testNodeId; protected $testNodeId;
...@@ -40,7 +45,14 @@ class PdfPopulationTest extends ImageFieldTestBase { ...@@ -40,7 +45,14 @@ class PdfPopulationTest extends ImageFieldTestBase {
$this->createImageField('field_fillpdf_test_image', 'article'); $this->createImageField('field_fillpdf_test_image', 'article');
$files = $this->getTestFiles('image'); $files = $this->getTestFiles('image');
$image = reset($files); $image = reset($files);
$this->testNode = Node::load($this->uploadNodeImage($image, 'field_fillpdf_test_image', 'article', 'FillPDF Test Image')); $this->testNode = Node::load(
$this->uploadNodeImage(
$image,
'field_fillpdf_test_image',
'article',
'FillPDF Test Image'
)
);
// Test with a node. // Test with a node.
$this->uploadTestPdf(); $this->uploadTestPdf();
...@@ -98,7 +110,6 @@ class PdfPopulationTest extends ImageFieldTestBase { ...@@ -98,7 +110,6 @@ class PdfPopulationTest extends ImageFieldTestBase {
$expected_file_hash, $expected_file_hash,
'Hashed filename matches known hash.' 'Hashed filename matches known hash.'
); );
self::assertEquals( self::assertEquals(
$populate_result['field_mapping']['fields']['ImageField'], $populate_result['field_mapping']['fields']['ImageField'],
"{image}{$node_file->getFileUri()}", "{image}{$node_file->getFileUri()}",
...@@ -111,16 +122,33 @@ class PdfPopulationTest extends ImageFieldTestBase { ...@@ -111,16 +122,33 @@ class PdfPopulationTest extends ImageFieldTestBase {
// Create a test submission for our Contact form. // Create a test submission for our Contact form.
$contact_form = Webform::load('fillpdf_contact'); $contact_form = Webform::load('fillpdf_contact');
$contact_form_test_route = Url::fromRoute('entity.webform.test', ['webform' => $contact_form->id()]); $contact_form_test_route = Url::fromRoute('entity.webform.test_form', ['webform' => $contact_form->id()]);
$this->drupalPostForm($contact_form_test_route, [], t('Send message')); $this->drupalPostForm($contact_form_test_route, [], t('Send message'));
// Load the submission. // Load the submission.
$submission = WebformSubmission::load($this->getLastSubmissionId($contact_form)); $submission = WebformSubmission::load($this->getLastSubmissionId($contact_form));
// Get the field definitions for the form that was created and configure $fillpdf_form2_fields = $this->container->get('fillpdf.entity_helper')
// them.
$fields = $this->container->get('fillpdf.entity_helper')
->getFormFields($fillpdf_form2); ->getFormFields($fillpdf_form2);
$expected_fields = TestFillPdfBackend::getParseResult();
$expected_keys = [];
$actual_keys = [];
foreach ($fillpdf_form2_fields as $fillpdf_form2_field) {
$actual_keys[] = $fillpdf_form2_field->pdf_key->value;
}
foreach ($expected_fields as $expected_field) {
$expected_keys[] = $expected_field['name'];
}
// Sort the arrays before comparing.
sort($expected_keys);
sort($actual_keys);
$differences = array_diff($expected_keys, $actual_keys);
self::assertEmpty($differences, 'Parsed fields and fields in fixture match.');
// Configure the fields for the next test.
$fields = $fillpdf_form2_fields;
/** @var \Drupal\fillpdf\Entity\FillPdfFormField $field */ /** @var \Drupal\fillpdf\Entity\FillPdfFormField $field */
foreach ($fields as $field) { foreach ($fields as $field) {
switch ($field->pdf_key->value) { switch ($field->pdf_key->value) {
...@@ -176,6 +204,44 @@ class PdfPopulationTest extends ImageFieldTestBase { ...@@ -176,6 +204,44 @@ class PdfPopulationTest extends ImageFieldTestBase {
"{image}{$submission_file->getFileUri()}", "{image}{$submission_file->getFileUri()}",
'URI in metadata matches expected URI.' 'URI in metadata matches expected URI.'
); );
// Test plugin APIs directly to make sure third-party consumers can use
// them.
$bsm = $this->container->get('plugin.manager.fillpdf_backend_service');
/** @var \Drupal\fillpdf_test\Plugin\BackendService\Test $backend_service */
$backend_service = $bsm->createInstance('test');
// Test the parse method.
$original_pdf = file_get_contents($this->getTestPdfPath());
$parsed_fields = $backend_service->parse($original_pdf);
$actual_keys = [];
foreach ($parsed_fields as $parsed_field) {
$actual_keys[] = $parsed_field['name'];
}
// Sort the arrays before comparing.
sort($expected_keys);
sort($actual_keys);
$differences = array_diff($expected_keys, $actual_keys);
self::assertEmpty($differences, 'Parsed fields from plugin and fields in fixture match.');
// Test the merge method. We'd normally pass in values for $fields and
// $options, but since this is a stub anyway, there isn't much point.
// @todo: Test deeper using the State API.
$merged_pdf = $backend_service->merge($original_pdf, [
'Foo' => new TextFieldMapping('bar'),
'Foo2' => new TextFieldMapping('bar2'),
'Image1' => new ImageFieldMapping(file_get_contents($image->uri), 'png'),
], []);
self::assertEquals($original_pdf, $merged_pdf);
$merge_state = $this->container->get('state')
->get('fillpdf_test.last_populated_metadata');
// Check that fields are set as expected.
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.');
} }
/** /**
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
namespace Drupal\Tests\fillpdf\Traits; namespace Drupal\Tests\fillpdf\Traits;
use Drupal\node\NodeInterface;
trait TestFillPdfTrait { trait TestFillPdfTrait {
protected function configureBackend() { protected function configureBackend() {
...@@ -24,11 +26,9 @@ trait TestFillPdfTrait { ...@@ -24,11 +26,9 @@ trait TestFillPdfTrait {
} }
protected function uploadTestPdf() { protected function uploadTestPdf() {
/** @var \Drupal\Core\File\FileSystem $file_system */
$file_system = $this->container->get('file_system');
// Upload a test file. // Upload a test file.
$edit = array( $edit = array(
'files[upload_pdf]' => $file_system->realpath(drupal_get_path('module', 'fillpdf') . '/tests/modules/fillpdf_test/files/fillpdf_test_v3.pdf'), 'files[upload_pdf]' => $this->getTestPdfPath(),
); );
$this->drupalPostForm('admin/structure/fillpdf', $edit, 'Upload'); $this->drupalPostForm('admin/structure/fillpdf', $edit, 'Upload');
$this->assertSession()->statusCodeEquals(200); $this->assertSession()->statusCodeEquals(200);
...@@ -49,4 +49,52 @@ trait TestFillPdfTrait { ...@@ -49,4 +49,52 @@ trait TestFillPdfTrait {
return reset($max_fid_after_result); return reset($max_fid_after_result);
} }
/**
* @param $file_system
* @return mixed
*/
protected function getTestPdfPath() {
/** @var \Drupal\Core\File\FileSystem $file_system */
$file_system = $this->container->get('file_system');
return $file_system->realpath(drupal_get_path('module', 'fillpdf') . '/tests/modules/fillpdf_test/files/fillpdf_test_v3.pdf');
}
/**
* Upload an image to a node.
*
* This is a fixed version of this method. The one from core is currently
* broken.
*
* @todo: Keep an eye on https://www.drupal.org/project/drupal/issues/2863626
* and consider switching back to that when it's done.
*
* @see \Drupal\Tests\image\Functional\ImageFieldTestBase::uploadNodeImage()
*
* @param $image
* A file object representing the image to upload.
* @param $field_name
* Name of the image field the image should be attached to.
* @param $type
* The type of node to create.
* @param $alt
* The alt text for the image. Use if the field settings require alt text.
*/
public function uploadNodeImage($image, $field_name, $type, $alt = '') {
$edit = [
'title[0][value]' => $this->randomMachineName(),
];
$edit['files[' . $field_name . '_0]'] = drupal_realpath($image->uri);
$edit['status[value]'] = NodeInterface::PUBLISHED;
$this->drupalPostForm('node/add/' . $type, $edit, t('Save'));
if ($alt) {
// Add alt text.
$this->drupalPostForm(NULL, [$field_name . '[0][alt]' => $alt], t('Save'));
}
// Retrieve ID of the newly created node from the current URL.
$matches = [];
preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
return isset($matches[1]) ? $matches[1] : FALSE;
}
} }
<?php
namespace Drupal\Tests\fillpdf\Unit\FieldMapping;
use Drupal\fillpdf\FieldMapping\ImageFieldMapping;
use Drupal\Tests\UnitTestCase;
/**
* @group fillpdf
* @covers \Drupal\fillpdf\FieldMapping\ImageFieldMapping
*/
class ImageFieldMappingTest extends UnitTestCase {
public function test__construct() {
// Test valid and invalid instantiations.
$image_field_mapping = new ImageFieldMapping('Dummy image', 'jpg');
self::assertInstanceOf(ImageFieldMapping::class, $image_field_mapping);
$this->setExpectedException(\InvalidArgumentException::class);
new ImageFieldMapping('Dummy image', 'bmp');
}
}
<?php
namespace Drupal\Tests\fillpdf\Unit\FieldMapping;
use Drupal\fillpdf\FieldMapping\TextFieldMapping;
use Drupal\Tests\UnitTestCase;
/**
* @group fillpdf
* @covers \Drupal\fillpdf\FieldMapping\TextFieldMapping
*/
class TextFieldMappingTest extends UnitTestCase {
public function test__construct() {
// Test valid and invalid instantiations.
$text_field_mapping = new TextFieldMapping('Dummy text');
self::assertInstanceOf(TextFieldMapping::class, $text_field_mapping, 'Instantiation works.');
}
public function testGetData() {
$text_field_mapping = new TextFieldMapping('Dummy text');
self::assertInternalType('string', $text_field_mapping->getData(), 'Data returned as string.');
// Test conversion to string.
$null_text_field_mapping = new TextFieldMapping(NULL);
self::assertInternalType('string', $null_text_field_mapping->getData(), 'Conversion to string from null works.');
self::assertEquals($null_text_field_mapping->getData(), '');
$int_text_field_mapping = new TextFieldMapping(1234567890);
self::assertInternalType('string', $int_text_field_mapping->getData(), 'Conversion to string from integer works.');
self::assertEquals($int_text_field_mapping->getData(), '1234567890');
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment