EmbeddedImagesCollector.php in Dependency Calculation 8
File
src/EventSubscriber/DependencyCollector/EmbeddedImagesCollector.php
View source
<?php
namespace Drupal\depcalc\EventSubscriber\DependencyCollector;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\depcalc\DependencyCalculatorEvents;
use Drupal\depcalc\DependentEntityWrapper;
use Drupal\depcalc\Event\CalculateEntityDependenciesEvent;
use Drupal\file\Entity\File;
class EmbeddedImagesCollector extends BaseDependencyCollector {
protected $database;
protected $moduleHandler;
public function __construct(Connection $database, ModuleHandlerInterface $module_handler) {
$this->database = $database;
$this->moduleHandler = $module_handler;
}
public static function getSubscribedEvents() {
$events[DependencyCalculatorEvents::CALCULATE_DEPENDENCIES][] = [
'onCalculateDependencies',
];
return $events;
}
public function onCalculateDependencies(CalculateEntityDependenciesEvent $event) {
if (!$this->moduleHandler
->moduleExists('file')) {
return;
}
$entity = $event
->getEntity();
if (FALSE === $entity instanceof ContentEntityInterface) {
return;
}
$files = $this
->getAttachedFiles($entity, 'editor');
foreach ($files as $file) {
$this
->addDependency($event, $file);
}
}
protected function getAttachedFiles(EntityInterface $entity, string $module = 'file') : array {
$criteria = new Condition('AND');
$criteria
->condition('type', $entity
->getEntityTypeId())
->condition('count', '0', '>')
->condition('module', [
$module,
], 'in')
->condition('id', $entity
->id());
$rows = $this->database
->select('file_usage', 'f')
->fields('f', [
'fid',
])
->condition($criteria)
->execute()
->fetchAllAssoc('fid');
if (empty($rows)) {
return [];
}
$fids = array_keys($rows);
return File::loadMultiple($fids);
}
protected function addDependency(CalculateEntityDependenciesEvent $event, EntityInterface $entity) : void {
if ($event
->getStack()
->hasDependency($entity
->uuid())) {
return;
}
$entity_wrapper = new DependentEntityWrapper($entity);
$local_dependencies = [];
$entity_wrapper_dependencies = $this
->getCalculator()
->calculateDependencies($entity_wrapper, $event
->getStack(), $local_dependencies);
$this
->mergeDependencies($entity_wrapper, $event
->getStack(), $entity_wrapper_dependencies);
$event
->addDependency($entity_wrapper);
}
}