improvements-2.x-dev/src/Plugin/Filter/TableWrapperFilter.php
src/Plugin/Filter/TableWrapperFilter.php
<?php
namespace Drupal\improvements\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\filter\Attribute\Filter;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\filter\Plugin\FilterInterface;
#[Filter(
id: 'table_wrapper_filter',
title: new TranslatableMarkup('Table wrapper'),
type: FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
description: new TranslatableMarkup('Wrap tables to div.'),
weight: 20,
)]
class TableWrapperFilter extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode): FilterProcessResult {
$result = new FilterProcessResult($text);
if (stripos($text, '<table') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//table') as $table) {
$table_wrapper = $dom->createElement('div');
$table_wrapper->setAttribute('class', 'table-wrapper');
$table->parentNode->replaceChild($table_wrapper, $table);
$table_wrapper->appendChild($table);
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
}
