You are here

public function CKEditorLinkFileToLinkitFilter::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/CKEditorLinkFileToLinkitFilter.php, line 76

Class

CKEditorLinkFileToLinkitFilter
Transforms <a href="/file/%"> tags to <a data-entity-substitution="media" …>.

Namespace

Drupal\media_migration\Plugin\migrate\process

Code

public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
  $value_is_array = is_array($value);
  $text = (string) ($value_is_array ? $value['value'] : $value);
  if (!preg_match(MediaMigration::PCRE_PATTERN_LINKIT_FILE_LINK, $text)) {
    return $value;
  }
  $html5 = new HTML5([
    'disable_html_ns' => TRUE,
  ]);

  // Compatibility for older HTML5 versions (e.g. in Drupal core 8.9.x).
  try {
    $dom = $html5
      ->parse('<html><body>' . $text . '</body></html>');
  } catch (\TypeError $e) {
    $text_stream = new StringInputStream('<html><body>' . $text . '</body></html>');
    $dom = $html5
      ->parse($text_stream);
  }
  foreach ($dom
    ->getElementsByTagName('a') as $node) {

    /** @var \DOMElement $node */
    $src = rawurldecode($node
      ->getAttribute('href'));
    $url_parts = parse_url($src);
    $path = $url_parts['path'] ?? '';
    if (strpos($path, '/file/') !== 0) {
      continue;
    }
    $file_entity_id = basename($path);
    if (!preg_match('/^\\d+$/', $file_entity_id)) {
      continue;
    }
    $media_uuid = $this->mediaUuidOracle
      ->getMediaUuid((int) $file_entity_id);

    // Add the additional attributes to allow the linkit filter to work.
    $node
      ->setAttribute('data-entity-substitution', 'media');
    $node
      ->setAttribute('data-entity-type', 'media');
    $node
      ->setAttribute('data-entity-uuid', $media_uuid);
  }
  $result = $html5
    ->saveHTML($dom->documentElement->firstChild->childNodes);
  if ($value_is_array) {
    $value['value'] = $result;
  }
  else {
    $value = $result;
  }
  return $value;
}