You are here

function nopremium_entity_view_mode_alter in Node Option Premium 8

Implements entity_view_mode_alter().

File

./nopremium.module, line 113
Hook implementations.

Code

function nopremium_entity_view_mode_alter(&$view_mode, EntityInterface $entity, $context) {

  /** @var \Drupal\Core\Session\AccountInterface $user */
  $user = \Drupal::currentUser();

  /** @var \Drupal\Core\Config\ImmutableConfig $config */
  $config = \Drupal::config('nopremium.settings');

  /** @var \Drupal\nopremium\NodeOptionPremiumHelperInterface $helper */
  $helper = \Drupal::service('nopremium.helper');

  // Check if premium access applies for the current view mode.
  $view_modes_config = $config
    ->get('view_modes');
  if (empty($view_modes_config)) {

    // No premium view modes configured. If the current view mode is *not* the
    // teaser view mode, the current view mode is premium.
    $view_mode_applies = $view_mode != $config
      ->get('teaser_view_mode');
  }
  else {

    // Premium view modes are configured. Check if the current view mode is a
    // premium one.
    $view_mode_applies = !empty($view_modes_config[$view_mode]);
  }
  if ($view_mode_applies && $entity
    ->getEntityTypeId() == 'node' && !$helper
    ->hasFullAccess($entity, $user)) {

    // Store the original view mode. This is data is later used to:
    // - Set the template variable 'page' to TRUE, in case the view mode was
    //   'full';
    // - Determine if the premium message should be shown.
    // @see nopremium_node_view()
    // @see nopremium_preprocess_node()
    $entity->original_view_mode = $view_mode;

    // Override the current view mode.
    $view_mode = $config
      ->get('teaser_view_mode');
  }
}