EditorFileReference.php in Drupal 8
File
core/modules/editor/src/Plugin/Filter/EditorFileReference.php
View source
<?php
namespace Drupal\editor\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\file\FileInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EditorFileReference extends FilterBase implements ContainerFactoryPluginInterface {
use DeprecatedServicePropertyTrait;
protected $deprecatedProperties = [
'entityManager' => 'entity.manager',
];
protected $entityRepository;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityRepositoryInterface $entity_repository) {
$this->entityRepository = $entity_repository;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity.repository'));
}
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 ($node
->hasAttribute('src')) {
$file = $this->entityRepository
->loadEntityByUuid('file', $uuid);
if ($file instanceof FileInterface) {
$node
->setAttribute('src', $file
->createFileUrl());
}
}
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;
}
}