function EntityLinks::process
Same name and namespace in other branches
- 11.x core/modules/filter/src/Plugin/Filter/EntityLinks.php \Drupal\filter\Plugin\Filter\EntityLinks::process()
Performs the filter processing.
Parameters
string $text: The text string to be filtered.
string $langcode: The language code of the text to be filtered.
Return value
\Drupal\filter\FilterProcessResult The filtered text, wrapped in a FilterProcessResult object, and possibly with associated assets, cacheability metadata and placeholders.
Overrides FilterInterface::process
File
-
core/
modules/ filter/ src/ Plugin/ Filter/ EntityLinks.php, line 46
Class
- EntityLinks
- Provides the Entity Links filter.
Namespace
Drupal\filter\Plugin\FilterCode
public function process($text, $langcode) : FilterProcessResult {
$result = new FilterProcessResult($text);
if (!str_contains($text, 'data-entity-type') && !str_contains($text, 'data-entity-uuid')) {
return $result;
}
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
// Note: this filter only processes links (<a href>) to Files, not
// tags with a File as a source (e.g. <img src>).
// @see \Drupal\editor\Plugin\Filter\EditorFileReference
foreach ($xpath->query('//a[@data-entity-type and @data-entity-uuid]') as $element) {
/** @var \DOMElement $element */
try {
// Load the appropriate translation of the linked entity.
$entity_type = $element->getAttribute('data-entity-type');
$uuid = $element->getAttribute('data-entity-uuid');
// Skip empty attributes to prevent loading of non-existing
// content type.
if ($entity_type === '' || $uuid === '') {
continue;
}
$entity = $this->entityRepository
->loadEntityByUuid($entity_type, $uuid);
if ($entity) {
// @todo Consider using \Drupal\Core\Entity\EntityRepositoryInterface::getTranslationFromContext() after https://drupal.org/i/3061761 is fixed.
if ($entity instanceof TranslatableInterface && $entity->hasTranslation($langcode)) {
$entity = $entity->getTranslation($langcode);
}
$url = $this->getUrl($entity);
// Parse link href as URL, extract query and fragment from it.
$href_url = parse_url($element->getAttribute('href'));
$anchor = empty($href_url["fragment"]) ? '' : '#' . $href_url["fragment"];
$query = empty($href_url["query"]) ? '' : '?' . $href_url["query"];
$element->setAttribute('href', $url->getGeneratedUrl() . $query . $anchor);
// The processed text now depends on:
$result->addCacheableDependency($url)
->addCacheableDependency($entity);
}
$element->removeAttribute('data-entity-type');
$element->removeAttribute('data-entity-uuid');
$element->removeAttribute('data-entity-metadata');
} catch (\Exception $e) {
Error::logException('filter', $e);
}
}
$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.