Skip to content

Commit

Permalink
Chnages for col style
Browse files Browse the repository at this point in the history
  • Loading branch information
Sahil Sharma committed Nov 6, 2024
1 parent ab201ca commit c10720a
Showing 1 changed file with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class BasicTextEnhancer extends ResourceFieldEnhancerBase {
protected function doUndoTransform($data, Context $context) {
if ($data) {
$data = $this->replaceUnicodeWhitespace($data);
$data = $this->addTableStylesToProcessed($data);
}
return $data;
}
Expand Down Expand Up @@ -82,4 +83,66 @@ public function replaceUnicodeWhitespace(array $data) {
return $data;
}

public function addTableStylesToProcessed(&$data) {
// Check if 'value' and 'processed' keys exist in $data.
if (isset($data['value']) && isset($data['processed'])) {
// Load 'value' and 'processed' HTML as DOM objects for manipulation.
$valueDom = new \DOMDocument();
$processedDom = new \DOMDocument();

// Suppress warnings for malformed HTML in $value and $processed.
libxml_use_internal_errors(true);
$valueDom->loadHTML($data['value']);
$processedDom->loadHTML($data['processed']);
libxml_clear_errors();

// Get <table> elements from both value and processed DOMs.
$valueTables = $valueDom->getElementsByTagName('table');
$processedTables = $processedDom->getElementsByTagName('table');

// Apply data attributes if there are tables in both DOMs.
if ($valueTables->length > 0 && $processedTables->length > 0) {
// Process each <col> element in both DOMs.
$valueTable = $valueTables->item(0);
$processedTable = $processedTables->item(0);
$valueCols = $valueTable->getElementsByTagName('col');
$processedCols = $processedTable->getElementsByTagName('col');

for ($i = 0; $i < min($valueCols->length, $processedCols->length); $i++) {
$valueCol = $valueCols->item($i);
$processedCol = $processedCols->item($i);

if ($valueCol->hasAttribute('style')) {
// Parse the style attribute.
$styleValue = $valueCol->getAttribute('style');
$styles = explode(';', $styleValue);

foreach ($styles as $style) {
$style = trim($style);
if (!empty($style)) {
list($property, $value) = explode(':', $style, 2);
$property = trim($property);
$value = trim($value);

// Sanitize the property name for a valid data attribute.
$dataAttribute = 'data-' . str_replace([' ', '_'], '-', strtolower($property));
$processedCol->setAttribute($dataAttribute, $value);
}
}
}
}
}

// Extract only the inner HTML of the <body> tag, avoiding extra tags.
$processedBodyContent = '';
foreach ($processedDom->getElementsByTagName('body')->item(0)->childNodes as $node) {
$processedBodyContent .= $processedDom->saveHTML($node);
}

// Update the 'processed' field with modified HTML.
$data['processed'] = $processedBodyContent;
}
return $data;
}

}

0 comments on commit c10720a

Please sign in to comment.