You are here

public function BackendProxy::merge in FillPDF 8.4

Same name and namespace in other branches
  1. 5.0.x src/Service/BackendProxy.php \Drupal\fillpdf\Service\BackendProxy::merge()

Throws

\Drupal\Component\Plugin\Exception\PluginException

Overrides BackendProxyInterface::merge

File

src/Service/BackendProxy.php, line 59

Class

BackendProxy
BackendProxy service.

Namespace

Drupal\fillpdf\Service

Code

public function merge(FillPdfFormInterface $fillPdfForm, array $entities, array $mergeOptions = []) : string {
  $config = $this->configFactory
    ->get('fillpdf.settings');
  $form_replacements = FillPdfMappingHelper::parseReplacements($fillPdfForm->replacements->value);
  $mergeOptions += [
    'fid' => $fillPdfForm
      ->id(),
    'sample' => FALSE,
    'flatten' => TRUE,
  ];

  // Populate mappings array.
  $fieldMappings = [];
  foreach ($fillPdfForm
    ->getFormFields() as $pdf_key => $field) {
    if ($mergeOptions['sample']) {
      $fieldMappings[$pdf_key] = new TextFieldMapping("<{$pdf_key}>");
    }
    else {
      $options = [];

      // Our pdftk backend doesn't support image stamping, so at least for
      // this backend we already know which type of content we can expect.
      $options['content'] = $config
        ->get('backend') === 'pdftk' ? 'text' : '';

      // Prepare transformations with field-level replacements taking
      // precedence over form-level replacements.
      $options['replacements'] = FillPdfMappingHelper::parseReplacements($field->replacements->value) + $form_replacements;

      // Add prefix and suffix.
      $options['prefix'] = $field->prefix->value;
      $options['suffix'] = $field->suffix->value;

      // Resolve tokens.
      $text = count($field->value) ? $field->value->value : '';
      $fieldMappings[$pdf_key] = $this->tokenResolver
        ->replace($text, $entities, $options);
    }
  }

  // Now load the backend plugin.

  /** @var \Drupal\fillpdf\FillPdfBackendPluginInterface|\Drupal\fillpdf\Plugin\PdfBackendInterface $backend */
  $backend = $this->backendManager
    ->createInstance($config
    ->get('backend'), $config
    ->get());

  // @todo: Emit event (or call alter hook?) before populating PDF.
  // Rename fillpdf_merge_fields_alter() to fillpdf_populate_fields_alter().

  /** @var \Drupal\file\FileInterface $templateFile */
  $templateFile = File::load($fillPdfForm->file->target_id);
  $mergedPdf = $backend
    ->mergeFile($templateFile, $fieldMappings, $mergeOptions);
  if (!is_string($mergedPdf)) {

    // Make sure we return a string as not to get an error. The underlying
    // backend will already have set more detailed errors.
    $mergedPdf = '';
  }
  return $mergedPdf;
}