mustache_templates-8.x-1.0-beta4/modules/mustache_token/mustache_token.tokens.inc

modules/mustache_token/mustache_token.tokens.inc
<?php

/**
 * @file
 * Builds placeholder replacement tokens for iterating.
 */

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\mustache\Render\IterableMarkup;

/**
 * Implements hook_token_info().
 */
function mustache_token_token_info() {
  $info = [];
  // Iterateable tokens.
  $info['types']['iterate'] = [
    'name' => t('Iterate'),
    'description' => t('Iterate through data using <a href="https://git.drupalcode.org/project/mustache_templates/-/blob/2.0.x/README.md#32-the-mustache-logic-less-tokens-sub-module" target="_blank" rel="noopener noreferrer">Mustache syntax</a>.'),
  ];
  $info['tokens']['iterate']['loop'] = [
    'name' => t('Loop'),
    'description' => t('Loop through iterable data. Example: <em>&lt;h1&gt;To Do&lt;&#47;h1&gt;&lt;ul&gt;{{#iterate.loop.node.field_mytodolist}}&lt;li&gt;{{#first}}First step: {{/first}}{{^first}}Next step no. {{position}}: {{/first}}{{.}}{{#last}}&lt;&#47;li&gt;&lt;li&gt;... and take care of yourself.{{/last}}&lt;&#47;li&gt;{{/iterate.loop.node.field_mytodolist}}&lt;&#47;ul&gt;</em>'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['explode'] = [
    'name' => t('Explode'),
    'description' => t('Loop through text line by line. Example: <em>&lt;h1&gt;To Do&lt;&#47;h1&gt;&lt;ul&gt;{{#iterate.explode.node.body}}&lt;li&gt;{{#first}}First step: {{/first}}{{^first}}Next step no. {{position}}: {{/first}}{{.}}{{#last}}&lt;&#47;li&gt;&lt;li&gt;... and take care of yourself.{{/last}}&lt;&#47;li&gt;{{/iterate.explode.node.body}}&lt;&#47;ul&gt;</em>'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['first'] = [
    'name' => t('First item'),
    'description' => t('The first item of the iterable data.'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['last'] = [
    'name' => t('Last item'),
    'description' => t('The last item of the iterable data.'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['count'] = [
    'name' => t('Count'),
    'description' => t('Count the items of iterable data.'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['empty'] = [
    'name' => t('Empty'),
    'description' => t('Whether the iterable data is empty ("Empty") or not ("Not empty").'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['sum'] = [
    'name' => t('Sum'),
    'description' => t('Sum of iterable data values.'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['min'] = [
    'name' => t('Minimum'),
    'description' => t('The minimum of iterable data values.'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['max'] = [
    'name' => t('Maximum'),
    'description' => t('The maximum of iterable data values.'),
    'dynamic' => TRUE,
  ];
  $info['tokens']['iterate']['avg'] = [
    'name' => t('Average'),
    'description' => t('The average of iterable data values.'),
    'dynamic' => TRUE,
  ];

  /** @var \Drupal\mustache\Plugin\MustacheMagicManager $magic_manager */
  $magic_manager = \Drupal::service('plugin.manager.mustache.magic');
  foreach ($magic_manager->getDefinitions() as $definition) {
    $info['types'][$definition['id']] = [
      'name' => $definition['label'],
      'description' => t('Using <a href="https://git.drupalcode.org/project/mustache_templates/-/blob/2.0.x/README.md#32-the-mustache-logic-less-tokens-sub-module" target="_blank" rel="noopener noreferrer">Mustache syntax</a>.'),
    ];
    $info['tokens'][$definition['id']]['?'] = [
      'name' => $definition['label'],
      'description' => $definition['description'],
    ];
  }

  return $info;
}

/**
 * Implements hook_tokens().
 */
function mustache_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'iterate') {
    /** @var \Drupal\mustache\MustacheTokenIterate $token_iterate */
    $token_iterate = \Drupal::service('mustache.token_iterate');
    foreach ($tokens as $name => $original) {
      $token_keys = explode(':', $name);
      $op = array_shift($token_keys);
      if (empty($token_keys)) {
        continue;
      }
      $target = $token_iterate->getIterableTarget($token_keys, $data, $options, $bubbleable_metadata);
      foreach ($token_keys as $token_key) {
        if (!isset($target[$token_key])) {
          $target = IterableMarkup::create();
          break;
        }
        $target = $target[$token_key];
      }

      if (in_array($op, [
        'avg', 'sum', 'min', 'max', '_avg', '_sum', '_min', '_max',
      ])) {
        $target_values = [];
        foreach ($target as $value) {
          if ($value instanceof IterableMarkup) {
            $separator = $value->separator;
            $value = (string) $value;
            $target_values = array_merge($target_values, explode($separator, $value));
          }
          elseif (is_iterable($value)) {
            foreach ($value as $k => $v) {
              if (is_int($k)) {
                $target_values[] = $v;
              }
              else {
                $target_values[$k] = $v;
              }
            }
          }
          elseif (is_object($value) && method_exists($value, '__toString')) {
            $target_values[] = (string) $value;
          }
          else {
            $target_values[] = $value;
          }
        }
      }

      switch ($op) {

        case '_loop':
        case 'loop':
          $replacements[$original] = $target;
          break;

        case '_first':
        case 'first':
          if ($first = reset($target->items)) {
            $replacements[$original] = $first;
          }
          break;

        case '_last':
        case 'last':
          if ($last = end($target->items)) {
            $replacements[$original] = $last;
          }
          break;

        case '_count':
        case 'count':
          $replacements[$original] = count($target->items);
          break;

        case '_empty':
        case 'empty':
          $replacements[$original] = empty($target->items) ? t('Empty') : t('Not empty');
          break;

        case '_avg':
        case '_sum':
        case 'avg':
        case 'sum':
          $sum = NULL;
          foreach ($target_values as $v) {
            if (is_numeric($v)) {
              $sum = (float) $sum;
              $sum += (float) $v;
            }
            elseif (is_string($v)) {
              $sum = (float) $sum;
              $sum += strlen($v);
            }
          }
          if ($sum !== NULL) {
            if (floor($sum) == $sum) {
              $sum = (int) $sum;
            }
            if ($op == 'avg' && ($count = count($target_values))) {
              $sum /= $count;
              $sum = number_format($sum, 2);
            }
            $replacements[$original] = $sum;
          }
          break;

        case '_min':
        case 'min':
          $min = NULL;
          foreach ($target_values as $v) {
            if (is_numeric($v)) {
              $min = $min === NULL || $min > $v ? $v : $min;
            }
            elseif (is_string($v)) {
              $min = $min === NULL || $min > strlen($v) ? strlen($v) : $min;
            }
          }
          if ($min !== NULL) {
            if (floor($min) == $min) {
              $min = (int) $min;
            }
            $replacements[$original] = $min;
          }
          break;

        case '_max':
        case 'max':
          $max = NULL;
          foreach ($target_values as $v) {
            if (is_numeric($v)) {
              $max = $max === NULL || $max < $v ? $v : $max;
            }
            elseif (is_string($v)) {
              $max = $max === NULL || $max < strlen($v) ? strlen($v) : $max;
            }
          }
          if ($max !== NULL) {
            if (floor($max) == $max) {
              $max = (int) $max;
            }
            $replacements[$original] = $max;
          }
          break;

        case '_explode':
        case 'explode':
          $target->separator = PHP_EOL;
          $string_value = str_replace(['<br>', '<br />', '<br/>', '<p>', '</p>'], PHP_EOL, (string) $target);
          $separators = mb_strpos($string_value, PHP_EOL) !== FALSE ? PHP_EOL : ",";
          $target = IterableMarkup::create();
          $option = strtok($string_value, $separators);
          while ($option !== FALSE) {
            $option = trim((string) $option);
            if ($option !== '') {
              $target[] = IterableMarkup::create([], $option, $target);
            }
            $option = strtok($separators);
          }
          $replacements[$original] = $target;
          break;

      }
    }
  }

  return $replacements;
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc