You are here

public function EntityReferenceFieldDependencyCollector::onCalculateDependencies in Dependency Calculation 8

Calculates the referenced entities.

Parameters

\Drupal\depcalc\Event\CalculateEntityDependenciesEvent $event: The dependency calculation event.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/EventSubscriber/DependencyCollector/EntityReferenceFieldDependencyCollector.php, line 34

Class

EntityReferenceFieldDependencyCollector
Subscribes to dependency collection to extract referenced entities.

Namespace

Drupal\depcalc\EventSubscriber\DependencyCollector

Code

public function onCalculateDependencies(CalculateEntityDependenciesEvent $event) {
  $entity = $event
    ->getEntity();
  if ($entity instanceof ContentEntityInterface) {
    $fields = FieldExtractor::getFieldsFromEntity($entity, [
      $this,
      'fieldCondition',
    ]);
    foreach ($fields as $field) {
      foreach ($field as $item) {
        if (!$item->entity) {
          $sub_entity = \Drupal::entityTypeManager()
            ->getStorage($field
            ->getFieldDefinition()
            ->getSetting('target_type'))
            ->load($item
            ->getValue()['target_id']);
          if (is_null($sub_entity)) {
            continue;
          }
          $item->entity = $sub_entity;
        }
        $item_entity_wrapper = new DependentEntityWrapper($item->entity);
        $local_dependencies = [];
        $this
          ->mergeDependencies($item_entity_wrapper, $event
          ->getStack(), $this
          ->getCalculator()
          ->calculateDependencies($item_entity_wrapper, $event
          ->getStack(), $local_dependencies));
        $event
          ->addDependency($item_entity_wrapper);
      }
    }
  }
}