You are here

twig_field.module in Twig Field 8

Primary module hooks for Twig field module.

File

twig_field.module
View source
<?php

/**
 * @file
 * Primary module hooks for Twig field module.
 */
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\twig_field\Plugin\Field\FieldWidget\TwigWidget;

/**
 * Returns default Twig context.
 *
 * @return array
 *   Twig context.
 */
function twig_field_default_context() {
  $context = [];
  $theme = \Drupal::theme()
    ->getActiveTheme();
  $context['theme'] = $theme
    ->getName();
  $context['theme_directory'] = $theme
    ->getPath();
  $context['base_path'] = base_path();
  $context['front_page'] = Url::fromRoute('<front>');
  $context['is_front'] = \Drupal::service('path.matcher')
    ->isFrontPage();
  $context['language'] = \Drupal::languageManager()
    ->getCurrentLanguage();
  $user = \Drupal::currentUser();
  $context['is_admin'] = $user
    ->hasPermission('access administration pages');
  $context['logged_in'] = $user
    ->isAuthenticated();
  return $context;
}

/**
 * Implements hook_entity_field_access().
 */
function twig_field_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account) {
  if ($operation == 'edit' && $field_definition
    ->getType() == 'twig') {
    return AccessResult::forbiddenIf(!$account
      ->hasPermission('access twig fields'))
      ->addCacheContexts([
      'user.permissions',
    ]);
  }
  return AccessResult::neutral();
}

/**
 * Implements hook_codemirror_editor_assets_alter().
 */
function twig_field_codemirror_editor_assets_alter(array &$assets) {

  // Ensure that the following language modes are always available.
  $assets['js'][] = 'mode/xml/xml.min.js';
  $assets['js'][] = 'mode/javascript/javascript.min.js';
  $assets['js'][] = 'mode/css/css.min.js';
  $assets['js'][] = 'mode/twig/twig.min.js';
}

/**
 * Implements hook_codemirror_mode_info_alter().
 */
function twig_field_codemirror_mode_info_alter(array &$modes) {

  // Make sure that following modes are always loaded.
  foreach (TwigWidget::REQUIRED_CODEMIRROR_MODES as $mode) {
    $modes[$mode]['usage'][] = 'twig_field';
  }
}