You are here

block_token.module in Block Token 8

Same filename and directory in other branches
  1. 7 block_token.module

Defines necessary hooks and functions for block_token form.

File

block_token.module
View source
<?php

/**
 * @file
 * Defines necessary hooks and functions for block_token form.
 */
use Drupal\block\Entity\Block;
use Drupal\block\Entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
define('BLOCK_TOKEN_SEPARATOR', ':');

/**
 * Implements hook_help().
 */
function block_token_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.block_token':
      $filepath = dirname(__FILE__) . '/README.txt';
      $readme = file_get_contents($filepath);
      if (!isset($readme)) {
        return NULL;
      }
      if (\Drupal::moduleHandler()
        ->moduleExists('markdown')) {
        $filters = \Drupal::moduleHandler()
          ->invoke('markdown', 'filter_info');
        $info = $filters['filter_markdown'];
        if (function_exists($info['process callback'])) {
          $output = $info['process callback']($readme, NULL);
        }
        else {
          $output = '<pre>' . $readme . '</pre>';
        }
      }
      else {
        $output = '<pre>' . $readme . '</pre>';
      }
      return $output;
  }
}

/**
 * Renders the block.
 *
 * @param  string $bid
 *   Block Id.
 *
 * @return string
 *   Rendered block.
 */
function block_token_block_render($bid) {
  $block = Block::load($bid);
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
  return \Drupal::service('renderer')
    ->render($block_content);
}

/**
 * Blocks with tokens.
 *
 * @param string $token
 *   Token name.
 *
 * @return array|bool
 *   If token name provided boolean indicating whether it is on or not
 *   otherwise the list of blocks with tokens.
 */
function block_token_blocks($token = NULL) {
  static $block_token;
  if (is_null($block_token)) {
    $block_token = array();

    // Select all the name fields from the config table  starting with block.block.
    $blocks = \Drupal::database()
      ->select('config', 'b')
      ->fields('b', array(
      'name',
      'data',
    ))
      ->condition('name', \Drupal::database()
      ->escapeLike("block.block") . '%', 'LIKE')
      ->execute();
    foreach ($blocks as $block) {
      if (isset(unserialize($block->data)['third_party_settings']['block_token']['token_value'])) {
        $bid = explode('.', $block->name)[2];
        $block = Block::load($bid);
        $module = end($block
          ->getDependencies()['module']);
        $block_token[block_token_token_name($module, $bid)] = $block;
      }
    }
    if (!is_null($token)) {
      return !empty($block_token[$token]);
    }
  }
  return $block_token;
}

/**
 * Implements hook_token_info().
 */
function block_token_token_info() {
  $tokens = array();
  $blocks = block_token_blocks();
  foreach ($blocks as $token => $block) {
    $module = end($block
      ->getDependencies()['module']);
    $name = t('Block from module %module with id %delta', array(
      '%module' => $module,
      '%delta' => $block
        ->getOriginalId(),
    ));
    $tokens[$token] = array(
      'name' => $name,
      'description' => $name,
    );
  }
  return array(
    'types' => array(
      'block_token' => array(
        'name' => t("Block Token"),
        'description' => t("Tokens containing blocks."),
      ),
    ),
    'tokens' => array(
      'block_token' => $tokens,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function block_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ('block_token' == $type) {
    foreach ($tokens as $token => $original) {
      $replacement = '';
      if (block_token_blocks($token)) {
        list($module, $id) = explode(BLOCK_TOKEN_SEPARATOR, $token, 2);
        $replacement = block_token_block_render($id);
      }
      $replacements[$original] = $replacement;
    }
  }
  return $replacements;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function block_token_form_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (\Drupal::currentUser()
    ->hasPermission('administer block token')) {

    /** @var \Drupal\block\BlockInterface $block */
    $block = $form_state
      ->getFormObject()
      ->getEntity();

    // This will automatically be saved in the third party settings.
    $form['third_party_settings']['#tree'] = TRUE;
    $form['third_party_settings']['block_token']['token_value'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create the token for this block'),
      '#description' => t('Token string is not available until the block is saved.'),
      '#default_value' => $block
        ->getThirdPartySetting('block_token', 'token_value'),
    );
    $id = $form['id']['#default_value'];
    $module = $form['settings']['provider']['#value'];
    $token = block_token_token_name($module, $id);
    if ($token) {
      if (!$block
        ->getThirdPartySetting('block_token', 'token_value')) {

        // When token checkbox is not checked.
        $form['third_party_settings']['block_token']['token_value']['#description'] = t('Token will be @token', array(
          '@token' => sprintf('[block_token:%s]', $token),
        ));
      }
      else {
        $form['third_party_settings']['block_token']['token_value']['#description'] = t('Token is @token', array(
          '@token' => sprintf('[block_token:%s]', $token),
        ));
      }
    }
  }
}

/**
 * Creates the token string.
 *
 * @param string $module
 *   Module name.
 * @param string $block_id
 *   Block Id.
 *
 * @return string
 *   Token name.
 */
function block_token_token_name($module, $block_id) {
  return $module . BLOCK_TOKEN_SEPARATOR . $block_id;
}

/**
 * Route access callback
 */
function block_token_route_access() {

  // Admin: always.
  if (Drupal::currentUser()
    ->hasPermission('administer taxonomy')) {
    return AccessResult::allowed();
  }
  if (Drupal::currentUser()
    ->hasPermission('administer block token')) {
    return AccessResult::allowed();
  }
  return AccessResult::forbidden();
}

Functions

Namesort descending Description
block_token_blocks Blocks with tokens.
block_token_block_render Renders the block.
block_token_form_block_form_alter Implements hook_form_FORM_ID_alter().
block_token_help Implements hook_help().
block_token_route_access Route access callback
block_token_tokens Implements hook_tokens().
block_token_token_info Implements hook_token_info().
block_token_token_name Creates the token string.

Constants