You are here

abstract class EntityUsageTrackBase in Entity Usage 8.3

Same name and namespace in other branches
  1. 8 src/EntityUsageTrackBase.php \Drupal\entity_usage\EntityUsageTrackBase
  2. 8.2 src/EntityUsageTrackBase.php \Drupal\entity_usage\EntityUsageTrackBase

Base implementation for track plugins.

Hierarchy

Expanded class hierarchy of EntityUsageTrackBase

5 files declare their use of EntityUsageTrackBase
BlockField.php in src/Plugin/EntityUsage/Track/BlockField.php
DynamicEntityReference.php in src/Plugin/EntityUsage/Track/DynamicEntityReference.php
EntityReference.php in src/Plugin/EntityUsage/Track/EntityReference.php
Link.php in src/Plugin/EntityUsage/Track/Link.php
TextFieldEmbedBase.php in src/Plugin/EntityUsage/Track/TextFieldEmbedBase.php

File

src/EntityUsageTrackBase.php, line 19

Namespace

Drupal\entity_usage
View source
abstract class EntityUsageTrackBase extends PluginBase implements EntityUsageTrackInterface, ContainerFactoryPluginInterface {

  /**
   * The usage tracking service.
   *
   * @var \Drupal\entity_usage\EntityUsage
   */
  protected $usageService;

  /**
   * Entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The Entity Update config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * The EntityRepository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * Plugin constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\entity_usage\EntityUsage $usage_service
   *   The usage tracking service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The EntityTypeManager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The EntityFieldManager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The EntityRepositoryInterface service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityUsage $usage_service, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, EntityRepositoryInterface $entity_repository) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->configuration += $this
      ->defaultConfiguration();
    $this->usageService = $usage_service;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->config = $config_factory
      ->get('entity_usage.settings');
    $this->entityRepository = $entity_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_usage.usage'), $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('config.factory'), $container
      ->get('entity.repository'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getId() {
    return $this->pluginDefinition['id'];
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() {
    return $this->pluginDefinition['label'];
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->pluginDefinition['description'] ?: '';
  }

  /**
   * {@inheritdoc}
   */
  public function getApplicableFieldTypes() {
    return $this->pluginDefinition['field_types'] ?: [];
  }

  /**
   * {@inheritdoc}
   */
  public function trackOnEntityCreation(EntityInterface $top_entity) {
    if (!$this
      ->isApplicable($top_entity)) {
      return;
    }
    $targets = $this
      ->getAllBottomLevelTargets($top_entity);
    $top_vid = $top_entity instanceof RevisionableInterface && $top_entity
      ->getRevisionId() ? $top_entity
      ->getRevisionId() : 0;
    foreach ($targets as $target_type_and_id) {
      list($target_type, $target_id) = explode("|", $target_type_and_id);
      $this->usageService
        ->registerUsage($target_id, $target_type, $top_entity
        ->id(), $top_entity
        ->getEntityTypeId(), $top_entity
        ->language()
        ->getId(), $top_vid);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function trackOnEntityUpdate(EntityInterface $top_entity, EntityInterface $original) {
    if (!$this
      ->isApplicable($top_entity)) {
      return;
    }
    $top_vid = $top_entity instanceof RevisionableInterface && $top_entity
      ->getRevisionId() ? $top_entity
      ->getRevisionId() : 0;
    $current_targets = $this
      ->getAllBottomLevelTargets($top_entity);

    // If we are creating a new revision, we only care about writing the
    // current targets to the DB.
    if ($original instanceof RevisionableInterface && $top_vid > $original
      ->getRevisionId()) {
      foreach ($current_targets as $target_type_and_id) {
        list($target_type, $target_id) = explode('|', $target_type_and_id);
        $this->usageService
          ->registerUsage($target_id, $target_type, $top_entity
          ->id(), $top_entity
          ->getEntityTypeId(), $top_entity
          ->language()
          ->getId(), $top_vid);
      }
    }
    else {
      $original_targets = $this
        ->getAllBottomLevelTargets($original);
      $added_ids = array_diff($current_targets, $original_targets);
      $removed_ids = array_diff($original_targets, $current_targets);
      foreach ($added_ids as $added_entity) {
        list($target_type, $target_id) = explode('|', $added_entity);
        $this->usageService
          ->registerUsage($target_id, $target_type, $top_entity
          ->id(), $top_entity
          ->getEntityTypeId(), $top_entity
          ->language()
          ->getId(), $top_vid);
      }
      foreach ($removed_ids as $removed_entity) {
        list($target_type, $target_id) = explode('|', $removed_entity);
        $this->usageService
          ->deleteUsage($target_id, $target_type, $top_entity
          ->id(), $top_entity
          ->getEntityTypeId(), $top_entity
          ->language()
          ->getId(), $top_vid);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getReferencingFields(EntityInterface $source_entity, array $field_types) {
    $source_entity_type_id = $source_entity
      ->getEntityTypeId();
    $all_fields_on_bundle = $this->entityFieldManager
      ->getFieldDefinitions($source_entity_type_id, $source_entity
      ->bundle());
    $referencing_fields_on_bundle = [];
    foreach ($all_fields_on_bundle as $field_name => $field) {
      if (in_array($field
        ->getType(), $field_types)) {
        $referencing_fields_on_bundle[$field_name] = $field;
      }
    }
    if (!$this->config
      ->get('track_enabled_base_fields')) {
      foreach ($referencing_fields_on_bundle as $key => $referencing_field_on_bundle) {
        if ($referencing_field_on_bundle
          ->getFieldStorageDefinition()
          ->isBaseField()) {
          unset($referencing_fields_on_bundle[$key]);
        }
      }
    }
    return $referencing_fields_on_bundle;
  }

  /**
   * Calculates all bottom-level targets for a given entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The source entity.
   * @param array $targets
   *   (optional) For internal use only.
   *
   * @return array
   *   An indexed array of bottom-level target entities that are referenced by
   *   the passed-in entity, or by any middle-level entity that is referenced
   *   by it.
   */
  protected function getAllBottomLevelTargets(EntityInterface $entity, array $targets = []) {
    if (!$entity instanceof FieldableEntityInterface) {
      return $targets;
    }
    $trackable_field_types = $this
      ->getApplicableFieldTypes();
    $fields = array_keys($this
      ->getReferencingFields($entity, $trackable_field_types));
    foreach ($fields as $field_name) {
      if ($entity
        ->hasField($field_name) && !$entity->{$field_name}
        ->isEmpty()) {

        /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
        foreach ($entity->{$field_name} as $field_item) {
          $target_entities = $this
            ->getTargetEntities($field_item);
          foreach ($target_entities as $target_type_and_id) {
            if (substr_count($target_type_and_id, '|') === 2) {
              list($target_type, , $target_revision_id) = explode("|", $target_type_and_id);
              $target_entity = $this->entityTypeManager
                ->getStorage($target_type)
                ->loadRevision($target_revision_id);
            }
            else {
              list($target_type, $target_id) = explode("|", $target_type_and_id);
              $target_entity = $this->entityTypeManager
                ->getStorage($target_type)
                ->load($target_id);
            }
            if (EntityUsageSourceLevel::isBottomLevel($target_entity)) {
              $targets[] = $target_type_and_id;
            }
            else {
              $targets = array_merge($targets, $this
                ->getAllBottomLevelTargets($target_entity, $targets));
            }
          }
        }
      }
    }
    return array_unique($targets);
  }

  /**
   * Detects whether this plugin should act on a particular entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity we are interested in.
   *
   * @return bool
   *   TRUE if this entity has at least one field this plugin can track, or
   *   FALSE otherwise.
   */
  protected function isApplicable(EntityInterface $entity) {
    if (!$entity instanceof FieldableEntityInterface) {
      return FALSE;
    }
    $trackable_field_types = $this
      ->getApplicableFieldTypes();
    $fields = array_keys($this
      ->getReferencingFields($entity, $trackable_field_types));
    foreach ($fields as $field_name) {
      if ($entity
        ->hasField($field_name)) {
        return TRUE;
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityUsageTrackBase::$config protected property The Entity Update config.
EntityUsageTrackBase::$entityFieldManager protected property Entity field manager service.
EntityUsageTrackBase::$entityRepository protected property The EntityRepository service.
EntityUsageTrackBase::$entityTypeManager protected property Entity type manager service.
EntityUsageTrackBase::$usageService protected property The usage tracking service.
EntityUsageTrackBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 1
EntityUsageTrackBase::defaultConfiguration public function
EntityUsageTrackBase::getAllBottomLevelTargets protected function Calculates all bottom-level targets for a given entity.
EntityUsageTrackBase::getApplicableFieldTypes public function Returns the field types this plugin is capable of tracking. Overrides EntityUsageTrackInterface::getApplicableFieldTypes
EntityUsageTrackBase::getDescription public function Returns the tracking method description. Overrides EntityUsageTrackInterface::getDescription
EntityUsageTrackBase::getId public function Returns the tracking method unique id. Overrides EntityUsageTrackInterface::getId
EntityUsageTrackBase::getLabel public function Returns the tracking method label. Overrides EntityUsageTrackInterface::getLabel
EntityUsageTrackBase::getReferencingFields public function Retrieve fields of the given types on an entity. Overrides EntityUsageTrackInterface::getReferencingFields
EntityUsageTrackBase::isApplicable protected function Detects whether this plugin should act on a particular entity.
EntityUsageTrackBase::trackOnEntityCreation public function Track usage updates on the creation of entities. Overrides EntityUsageTrackInterface::trackOnEntityCreation
EntityUsageTrackBase::trackOnEntityUpdate public function Track usage updates on the edition of entities. Overrides EntityUsageTrackInterface::trackOnEntityUpdate
EntityUsageTrackBase::__construct public function Plugin constructor. Overrides PluginBase::__construct 1
EntityUsageTrackInterface::getTargetEntities public function Retrieve the target entity(ies) from a field item value. 5
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.