You are here

function flag_entity_view_alter in Flag 8.4

Implements hook_entity_view_alter().

Alters node contextual links placeholder id to contain flag metadata, so that contextual links cache considers flags granularity.

File

./flag.module, line 428
The Flag module.

Code

function flag_entity_view_alter(&$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $entity_type = $entity
    ->getEntityTypeId();
  if (isset($build['#contextual_links'][$entity_type])) {

    /** @var \Drupal\flag\FlagService $flag_service */
    $flag_service = \Drupal::service('flag');

    // Get all possible flags for this entity type.
    $flags = $flag_service
      ->getAllFlags($entity_type, $entity
      ->bundle());
    foreach ($flags as $flag) {
      $flag_type_plugin = $flag
        ->getFlagTypePlugin();

      // Make sure we're dealing with an entity flag type.
      if (!$flag_type_plugin instanceof EntityFlagType) {
        continue;
      }

      // Only apply metadata to contextual links if plugin is enabled
      if (!$flag_type_plugin
        ->showContextualLink()) {
        continue;
      }
      $action = 'flag';
      if ($flag
        ->isFlagged($entity)) {
        $action = 'unflag';
      }
      $flag_keys[] = $flag
        ->id() . '-' . $action;
    }
    if (!empty($flag_keys)) {
      $build['#contextual_links'][$entity_type]['metadata']['flag_keys'] = implode(',', $flag_keys);
    }
  }
}