You are here

public function Tracker::updateEntity in Menu Entity Index 8

Updates database tracking for new or updated entities.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The updated host entity.

Overrides TrackerInterface::updateEntity

File

src/Tracker.php, line 471

Class

Tracker
Tracks menu links and their referenced entities.

Namespace

Drupal\menu_entity_index

Code

public function updateEntity(EntityInterface $entity) {

  // Process menu links only.
  if ($entity
    ->getEntityTypeId() !== 'menu_link_content') {
    return;
  }

  // Process menu links in tracked menus only.
  if (!in_array($entity
    ->getMenuName(), $this
    ->getTrackedMenus())) {
    return;
  }

  // Delete any existing references for this host entity from db.
  if (!$entity
    ->isNew()) {
    $this
      ->deleteEntity($entity);
  }
  $targets = [];

  // Get a route match object for the target path of the menu link, so that we
  // can get a parameter bag.
  try {
    $url = $entity
      ->getUrlObject();
    if (!$url
      ->isExternal()) {
      $url
        ->setOption('absolute', TRUE);
    }
    $url = $url
      ->toString();
  } catch (\InvalidArgumentException $e) {
    return;
  }
  $route_request = $this
    ->getRequestForUrl($url);
  if ($route_request) {
    $route_match = RouteMatch::createFromRequest($route_request);
    $parameters = $route_match
      ->getParameters();

    // Check, if any parameters are content entities, that we want to track.
    foreach ($parameters as $parameter) {
      if ($parameter instanceof ContentEntityInterface) {
        if (in_array($parameter
          ->getEntityTypeId(), $this
          ->getTrackedEntityTypes())) {

          // This is a target entity we want to track.
          if (!$this
            ->isEntityTranslatable($parameter)) {
            $targets[] = $parameter;
          }
          else {
            if ($this
              ->isEntityTranslatable($entity)) {
              $targets[] = $parameter
                ->hasTranslation($entity
                ->language()
                ->getId()) ? $parameter
                ->getTranslation($entity
                ->language()
                ->getId()) : $parameter;
            }
            else {
              foreach ($parameter
                ->getTranslationLanguages() as $language) {
                if ($entity
                  ->language()
                  ->getId() === $language
                  ->getId()) {
                  $targets[] = $parameter
                    ->getTranslation($entity
                    ->language()
                    ->getId());
                }
              }
            }
          }
        }
      }
    }
  }

  // Add new records to database, if any.
  if (count($targets) > 0) {
    $this
      ->addEntityTargets($entity, $targets);
  }
}