You are here

function facebookshare_node_view in Facebook Share 8

Same name and namespace in other branches
  1. 7 facebookshare.module \facebookshare_node_view()

Implements hook_ENTITY_TYPE_view().

File

./facebookshare.module, line 28
Adds a button to a node to share on a user's Facebook stream.

Code

function facebookshare_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $config = \Drupal::config('facebookshare.settings');
  $settings = $config
    ->get();

  // Make sure we're on the right content type.
  if (in_array($entity
    ->getType(), $settings['facebookshare_types'])) {
    if ($view_mode == 'teaser' || $view_mode == 'full') {
      if (\Drupal::currentUser()
        ->hasPermission('access facebookshare')) {

        // Retrieve the location where we should show it.
        $location = $settings['facebookshare_location'];

        // Check if the current $view_mode has content to show.
        if ($view_mode == 'teaser' && !empty($location['teasers']) || $view_mode == 'full' && !empty($location['content'])) {

          // Retrieve the weight and url of the button.
          $url = Url::fromRoute('entity.node.canonical', array(
            'node' => $entity
              ->id(),
          ), array(
            'absolute' => TRUE,
          ));
          $weight = Html::escape($settings['facebookshare_weight']);

          // Add and theme the button.
          $build['facebookshare'] = array(
            '#theme' => 'facebookshare',
            '#url' => $url,
            '#weight' => is_numeric($weight) ? (int) $weight : -10,
            '#attached' => array(
              'library' => array(
                'facebookshare/facebookshare',
              ),
            ),
            '#cache' => array(
              'tags' => array(
                'config:facebookshare.settings',
              ),
            ),
          );
        }
      }
    }
  }
}