You are here

social_like.module in Open Social 8

The social_like module.

File

modules/social_features/social_like/social_like.module
View source
<?php

/**
 * @file
 * The social_like module.
 */
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_entity_view_alter().
 */
function social_like_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  if ($display
    ->getComponent('like_and_dislike')) {

    // Check if the current user has permission
    // if not, hide the like and dislike.
    if (!\Drupal::currentUser()
      ->hasPermission('view like widget')) {
      unset($build['like_and_dislike']);
    }
    else {
      $build['#attached']['library'][] = 'core/drupal.dialog.ajax';
    }
  }
}

/**
 * Implements hook_views_pre_render().
 */
function social_like_views_pre_render(ViewExecutable $view) {

  // Set the amount of likes as the title.
  if ($view
    ->id() == 'who_liked_this_entity') {
    $view
      ->setTitle(t('@amount like(s)', [
      '@amount' => $view->total_rows,
    ]));
  }
}

/**
 * Implements hook_entity_insert().
 */
function social_like_entity_insert(EntityInterface $entity) {
  if ($entity
    ->getEntityTypeId() == 'vote') {
    social_like_invalidate_cache($entity);
  }
}

/**
 * Implements hook_entity_delete().
 */
function social_like_entity_delete(EntityInterface $entity) {
  if ($entity
    ->getEntityTypeId() == 'vote') {
    social_like_invalidate_cache($entity);
  }
}

/**
 * Implements social_like_invalidate_cache().
 */
function social_like_invalidate_cache(EntityInterface $entity) {
  $cache_tag = [
    $entity
      ->getEntityTypeId() . ':' . $entity
      ->id(),
    'config:views.view.who_liked_this_entity',
  ];
  Cache::invalidateTags($cache_tag);
}

/**
 * Implements hook_preprocess().
 */
function social_like_preprocess_like_and_dislike_icons(&$variables) {
  $bundle = $variables['entity_type'];
  if ($variables['entity_type'] === 'node') {
    $bundle = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->load($variables['entity_id'])
      ->bundle();
  }
  $variables['modal_title'] = t('Members who liked this @content', [
    '@content' => $bundle,
  ]);
}