You are here

function easy_email_commerce_tokens in Easy Email 2.0.x

Implements hook_tokens().

File

modules/easy_email_commerce/easy_email_commerce.module, line 116

Code

function easy_email_commerce_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {

  /** @var \Drupal\Core\Render\RendererInterface $renderer */
  $renderer = \Drupal::service('renderer');

  /** @var \Drupal\commerce_order\OrderTotalSummaryInterface $order_total_summary */
  $order_total_summary = \Drupal::service('commerce_order.order_total_summary');
  $profile_view_builder = \Drupal::entityTypeManager()
    ->getViewBuilder('profile');
  $has_shipping = \Drupal::moduleHandler()
    ->moduleExists('commerce_shipping');
  if ($has_shipping) {
    $order_shipment_summary = \Drupal::service('commerce_shipping.order_shipment_summary');
  }
  $token_template_by_entity_type = easy_email_commerce_template_by_token();
  $replacements = [];
  foreach ($token_template_by_entity_type as $entity_type => $token_templates) {
    if ($type === $entity_type && !empty($data[$entity_type])) {
      foreach ($tokens as $name => $original) {
        if (isset($token_templates[$name])) {
          $build = [
            '#theme' => $token_templates[$name]['template'],
            '#' . $entity_type => $data[$entity_type],
          ];
          if ($entity_type === 'commerce_order') {
            $build['#totals'] = $order_total_summary
              ->buildTotals($data[$entity_type]);
          }
          if ($billing_profile = $data[$entity_type]
            ->getBillingProfile()) {
            $build['#billing_information'] = $profile_view_builder
              ->view($billing_profile);
          }
          if ($has_shipping) {
            $build['#shipping_information'] = $order_shipment_summary
              ->build($data[$entity_type]);
          }
          $vars = [
            'order_entity' => $data[$entity_type],
          ];
          commerce_payment_preprocess_commerce_order($vars);
          $build['#payment_method'] = $vars['payment_method'];
          $replacements[$original] = $renderer
            ->renderRoot($build);
        }
      }
    }
  }
  return $replacements;
}