migrate_spip-1.0.0/modules/examples/src/Plugin/SpipRichText/MediaBase.php
modules/examples/src/Plugin/SpipRichText/MediaBase.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\media\MediaInterface;
use Drupal\migrate_spip\SpipRichTextBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base management for SPIP medias.
*/
abstract class MediaBase extends SpipRichTextBase {
/**
* SPIP media alignement available.
*
* @var array
*/
const ALIGNS = [
'center',
'left',
'right',
];
/**
* 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}
*/
public function apply(string $text): string {
// Search medias with alignment.
foreach (static::ALIGNS as $align) {
$text = $this->applyMediaAlignment($text, $align);
}
// Search medias without alignment.
return $this->applyMediaAlignment($text);
}
/**
* Convert SPIP media for given alignment.
*
* @param string $text
* The plain text.
* @param string|null $align
* The media alignement to process.
*
* @return string
* The processed text.
*/
abstract protected function applyMediaAlignment(string $text, ?string $align = NULL): string;
/**
* Get Drupal media HTML tag.
*
* @param \Drupal\media\MediaInterface $media
* The media entity.
* @param string|null $align
* The media alignement.
*
* @return string
* The media HTML tag.
*/
protected function getMediaTag(MediaInterface $media, ?string $align = NULL): string {
$tag = '<drupal-media';
if ($align) {
$tag .= ' data-align="' . $align . '"';
}
return $tag . ' data-entity-type="media" data-entity-uuid="' .
$media->uuid() .
'"></drupal-media>';
}
}
