migrate_spip-1.0.0/modules/examples/src/Plugin/SpipRichText/MediaTacVideosBase.php
modules/examples/src/Plugin/SpipRichText/MediaTacVideosBase.php
<?php
declare(strict_types=1);
namespace Drupal\migrate_spip_examples\Plugin\SpipRichText;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\media\MediaInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base management for SPIP TarteAuCitron videos into media.
*/
abstract class MediaTacVideosBase extends MediaBase implements ContainerFactoryPluginInterface {
/**
* SPIP video provider.
*
* @var string
*/
const PROVIDER = '';
/**
* The current user service.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected AccountInterface $currentUser;
/**
* 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->currentUser = $container->get('current_user');
$instance->entityTypeManager = $container->get('entity_type.manager');
return $instance;
}
/**
* {@inheritdoc}
*/
public function apply(string $text): string {
// Without alignement management.
return $this->applyMediaAlignment($text, '');
}
/**
* {@inheritdoc}
*/
public function applyMediaAlignment(string $text, ?string $align = NULL): string {
// <tac_{provider}|video_id=>
if (!preg_match_all('#<tac_' . static::PROVIDER . '\|video_id=([^|>]+)' . ($align ? '\|' . $align : '') . '(?:.*)?>#sU', $text, $matches)) {
return $text;
}
foreach ($matches[1] as $index => $match) {
$replace = '';
if (!empty($match)) {
/** @var \Drupal\media\MediaInterface|null $media */
$medias = $this->entityTypeManager->getStorage('media')->loadByProperties([
'field_media_oembed_video' => $match,
]);
$media = reset($medias);
if (!$media) {
/** @var \Drupal\media\MediaInterface|null $media */
$media = $this->entityTypeManager->getStorage('media')->create([
'bundle' => 'video',
'uid' => $this->currentUser->id(),
'field_media_oembed_video' => [
'value' => $match,
],
]);
$media
->setName($this->getMediaName($media))
->setPublished()
->save();
}
$replace = $this->getMediaTag($media, $align);
}
$text = str_replace(
$matches[0][$index],
$replace,
$text
);
}
return $text;
}
/**
* Get media name.
*
* @param \Drupal\media\MediaInterface $media
* The media entity.
*
* @return string
* The media name.
*/
private function getMediaName(MediaInterface $media): string {
$defaultName = $media->getSource()->getMetadata($media, 'default_name');
if ($defaultName) {
return $defaultName;
}
return (string) $this->t('Video @url', [
'@url' => $media->get('field_media_oembed_video')->value,
]);
}
}
