function EditorFileReference::process
Same name in other branches
- 9 core/modules/editor/src/Plugin/Filter/EditorFileReference.php \Drupal\editor\Plugin\Filter\EditorFileReference::process()
- 8.9.x core/modules/editor/src/Plugin/Filter/EditorFileReference.php \Drupal\editor\Plugin\Filter\EditorFileReference::process()
- 10 core/modules/editor/src/Plugin/Filter/EditorFileReference.php \Drupal\editor\Plugin\Filter\EditorFileReference::process()
Overrides FilterInterface::process
File
-
core/
modules/ editor/ src/ Plugin/ Filter/ EditorFileReference.php, line 80
Class
- EditorFileReference
- Provides a filter to track images uploaded via a Text Editor.
Namespace
Drupal\editor\Plugin\FilterCode
public function process($text, $langcode) {
$result = new FilterProcessResult($text);
if (stristr($text, 'data-entity-type="file"') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
$processed_uuids = [];
foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) {
$uuid = $node->getAttribute('data-entity-uuid');
// If there is a 'src' attribute, set it to the file entity's current
// URL. This ensures the URL works even after the file location changes.
if ($node->hasAttribute('src')) {
$file = $this->entityRepository
->loadEntityByUuid('file', $uuid);
if ($file instanceof FileInterface) {
$node->setAttribute('src', $file->createFileUrl());
if ($node->nodeName == 'img') {
$image = $this->imageFactory
->get($file->getFileUri());
$width = $image->getWidth();
$height = $image->getHeight();
// Set dimensions to avoid content layout shift (CLS).
// @see https://web.dev/cls/
if ($width !== NULL && !$node->hasAttribute('width')) {
$node->setAttribute('width', (string) $width);
}
if ($height !== NULL && !$node->hasAttribute('height')) {
$node->setAttribute('height', (string) $height);
}
}
}
}
// Only process the first occurrence of each file UUID.
if (!isset($processed_uuids[$uuid])) {
$processed_uuids[$uuid] = TRUE;
$file = $this->entityRepository
->loadEntityByUuid('file', $uuid);
if ($file instanceof FileInterface) {
$result->addCacheTags($file->getCacheTags());
}
}
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.