You are here

public function MediaWysiwygFilter::transform in Media Migration 8

Performs the associated process.

Parameters

mixed $value: The value to be transformed.

\Drupal\migrate\MigrateExecutableInterface $migrate_executable: The migration in which this process is being executed.

\Drupal\migrate\Row $row: The row from the source to process. Normally, just transforming the value is adequate but very rarely you might need to change two columns at the same time or something like that.

string $destination_property: The destination property currently worked on. This is only used together with the $row above.

Return value

string|array The newly transformed value.

Overrides ProcessPluginBase::transform

File

src/Plugin/migrate/process/MediaWysiwygFilter.php, line 148

Class

MediaWysiwygFilter
Processes [[{"type":"media","fid":"1234",...}]] tokens in content.

Namespace

Drupal\media_migration\Plugin\migrate\process

Code

public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
  if (!MediaMigration::embedTokenDestinationFilterPluginIsValid(MediaMigration::getEmbedTokenDestinationFilterPlugin())) {
    throw new MigrateException("The embed token's destination filter plugin ID is invalid.");
  }
  $pattern = '/\\[\\[\\s*(?<tag_info>\\{.+\\})\\s*\\]\\]/sU';
  if (defined(JsonDecode::class . '::ASSOCIATIVE')) {
    $decoder = new JsonDecode([
      JsonDecode::ASSOCIATIVE => TRUE,
    ]);
  }
  else {
    $decoder = new JsonDecode(TRUE);
  }
  $entity_type_id = explode(':', $this->migration
    ->getDestinationConfiguration()['plugin'])[1];
  $source_identifier = [];
  foreach ($row
    ->getSourceIdValues() as $source_id_key => $source_id_value) {
    $source_identifier[] = "{$source_id_key} {$source_id_value}";
  }
  $source_identifier = implode(', ', $source_identifier);
  $value_is_array = is_array($value);
  $text = (string) ($value_is_array ? $value['value'] : $value);
  $text = preg_replace_callback($pattern, function ($matches) use ($decoder, $entity_type_id, $source_identifier) {

    // Replace line breaks with a single space for valid JSON.
    $matches['tag_info'] = preg_replace('/\\s+/', ' ', $matches['tag_info']);
    try {
      $tag_info = $decoder
        ->decode($matches['tag_info'], JsonEncoder::FORMAT);
      if (!is_array($tag_info) || !array_key_exists('fid', $tag_info)) {
        return $matches[0];
      }

      // Find matching view mode.
      if ($this->configuration['view_mode_matching']) {
        foreach ($this->configuration['view_mode_matching'] as $key => $match) {
          if ($key == $tag_info['view_mode'] ?? NULL) {
            $tag_info['view_mode'] = $match;
          }
        }
      }
      $embed_metadata = [
        'id' => $tag_info['fid'],
        'view_mode' => $tag_info['view_mode'] ?? 'default',
      ];
      $source_attributes = !empty($tag_info['attributes']) ? $tag_info['attributes'] : [];

      // Add alt and title overrides.
      foreach ([
        'alt',
        'title',
      ] as $attribute_name) {
        if (!empty($source_attributes[$attribute_name])) {
          $embed_metadata[$attribute_name] = $source_attributes[$attribute_name];
        }
      }

      // Add alignment.
      if (!empty($source_attributes['class']) && is_string($source_attributes['class'])) {
        $alignment_map = [
          'media-wysiwyg-align-center' => 'center',
          'media-wysiwyg-align-left' => 'left',
          'media-wysiwyg-align-right' => 'right',
        ];
        $classes_array = array_unique(explode(' ', preg_replace('/\\s{2,}/', ' ', trim($source_attributes['class']))));
        foreach ($alignment_map as $original => $replacement) {
          if (in_array($original, $classes_array, TRUE)) {
            $embed_metadata['data-align'] = $replacement;
            break;
          }
        }
      }
      return $this
        ->getEmbedCode($embed_metadata) ?? $matches[0];
    } catch (NotEncodableValueException $e) {

      // There was an error decoding the JSON.
      $this
        ->messenger()
        ->addWarning(sprintf('The following media_wysiwyg token in %s %s does not have valid JSON: %s', $entity_type_id, $source_identifier, $matches[0]));
      return $matches[0];
    } catch (\LogicException $e) {
      return $matches[0];
    }
  }, $text);

  // Update fid and token in regex /file/{fid}/download?token={token}.
  if ($this->configuration['file_migrations']) {
    $pattern = '#\\/file\\/([0-9]*)\\/download\\?token=([a-zA-Z0-9]*)#';
    $replacement_template = '/file/%s/download?token=%s';
    $text = preg_replace_callback($pattern, function ($matches) use ($replacement_template) {
      $oldId = $matches[1];
      $newId = $this
        ->findDestId($oldId, $this->configuration['file_migrations']);
      $newToken = '';
      try {
        $reflector = new \ReflectionClass('Drupal\\file_entity\\Entity\\FileEntity');
        if ($reflector
          ->hasMethod('getDownloadToken') && ($file = File::load($newId))) {
          $newToken = $file
            ->getDownloadToken();
        }
      } catch (\ReflectionException $e) {
      }
      return sprintf($replacement_template, $newId, $newToken);
    }, $text);
  }
  if ($value_is_array) {
    $value['value'] = $text;
  }
  else {
    $value = $text;
  }
  return $value;
}