3 namespace Drupal\editor\Plugin\Filter;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8 use Drupal\filter\FilterProcessResult;
9 use Drupal\filter\Plugin\FilterBase;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
13 * Provides a filter to track images uploaded via a Text Editor.
15 * Generates file URLs and associates the cache tags of referenced files.
18 * id = "editor_file_reference",
19 * title = @Translation("Track images uploaded via a Text Editor"),
20 * description = @Translation("Ensures that the latest versions of images uploaded via a Text Editor are displayed."),
21 * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
24 class EditorFileReference extends FilterBase implements ContainerFactoryPluginInterface {
27 * An entity manager object.
29 * @var \Drupal\Core\Entity\EntityManagerInterface
31 protected $entityManager;
34 * Constructs a \Drupal\editor\Plugin\Filter\EditorFileReference object.
36 * @param array $configuration
37 * A configuration array containing information about the plugin instance.
38 * @param string $plugin_id
39 * The plugin_id for the plugin instance.
40 * @param mixed $plugin_definition
41 * The plugin implementation definition.
42 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
43 * An entity manager object.
45 public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager) {
46 $this->entityManager = $entity_manager;
47 parent::__construct($configuration, $plugin_id, $plugin_definition);
53 static public function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
58 $container->get('entity.manager')
65 public function process($text, $langcode) {
66 $result = new FilterProcessResult($text);
68 if (stristr($text, 'data-entity-type="file"') !== FALSE) {
69 $dom = Html::load($text);
70 $xpath = new \DOMXPath($dom);
71 $processed_uuids = [];
72 foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) {
73 $uuid = $node->getAttribute('data-entity-uuid');
75 // If there is a 'src' attribute, set it to the file entity's current
76 // URL. This ensures the URL works even after the file location changes.
77 if ($node->hasAttribute('src')) {
78 $file = $this->entityManager->loadEntityByUuid('file', $uuid);
80 $node->setAttribute('src', file_url_transform_relative(file_create_url($file->getFileUri())));
84 // Only process the first occurrence of each file UUID.
85 if (!isset($processed_uuids[$uuid])) {
86 $processed_uuids[$uuid] = TRUE;
88 $file = $this->entityManager->loadEntityByUuid('file', $uuid);
90 $result->addCacheTags($file->getCacheTags());
94 $result->setProcessedText(Html::serialize($dom));