migrate_spip-1.0.0/modules/examples/src/Plugin/SpipRichText/LinksInternalMediaDocuments.php
modules/examples/src/Plugin/SpipRichText/LinksInternalMediaDocuments.php
<?php
declare(strict_types=1);
namespace Drupal\migrate_spip_examples\Plugin\SpipRichText;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\migrate_spip\Attribute\SpipRichText;
use Drupal\migrate_spip\SpipRichTextBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Manage SPIP internal links for media documents.
*
* Need to be executed after medias and links.
*/
#[SpipRichText(
id: 'links_internal_media_documents',
label: new TranslatableMarkup('Links internal media documents'),
weight: -5,
)]
final class LinksInternalMediaDocuments extends SpipRichTextBase implements ContainerFactoryPluginInterface {
/**
* The database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected Connection $connection;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected EntityTypeManagerInterface $entityTypeManager;
/**
* {@inheritdoc}
*/
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition
): static {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->connection = $container->get('database');
$instance->entityTypeManager = $container->get('entity_type.manager');
return $instance;
}
/**
* {@inheritdoc}
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function apply(string $text): string {
/*
* Search "doc123" SPIP internal links.
*
* Consider that you have previously migrated SPIP sections
* to media using a "media_documents" migration task.
*
* @see migrate_spip_plus
*/
if (
!preg_match_all('#href="(\s*doc\s*(\d+)\s*)"#s', $text, $matches) ||
!$this->connection->schema()->tableExists('migrate_map_media_documents')
) {
return $text;
}
foreach ($matches[2] as $index => $match) {
$url = '#';
$destId1 = $this->connection->select('migrate_map_media_documents', 'mmd')
->condition('mmd.sourceid1', $match)
->fields('mmd', ['destid1'])
->execute()
->fetchField();
if ($destId1) {
/** @var \Drupal\media\MediaInterface|null $media */
$media = $this->entityTypeManager->getStorage('media')
->load((int) $destId1);
if ($media) {
/** @var \Drupal\file\FileInterface[] $files */
$files = $media->get('field_media_file')->referencedEntities();
$url = reset($files)->createFileUrl();
}
}
$text = str_replace(
$matches[1][$index],
$url,
$text
);
}
return $text;
}
}
