gamify-1.1.x-dev/src/AlertBuilderService.php

src/AlertBuilderService.php
<?php

namespace Drupal\gamify;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\eca\Token\TokenInterface;
use Drupal\gamify\Entity\GamifyAlert;
use Drupal\gamify\UserPointsLogService as LogService;
use Drupal\user\UserInterface;
use Drupal\userpoints\Service\UserPointsServiceInterface;

/**
 * Service description.
 */
class AlertBuilderService {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Drupal\Core\Entity\EntityStorageInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected EntityStorageInterface $templateStore;

  /**
   * Drupal\Core\Entity\EntityStorageInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected EntityStorageInterface $alertStore;

  /**
   * Drupal\userpoints\Service\UserPointsService definition.
   *
   * @var \Drupal\userpoints\Service\UserPointsServiceInterface
   */
  protected UserPointsServiceInterface $userpointsService;

  /**
   * The ECA-related token services.
   *
   * @var \Drupal\eca\Token\TokenInterface
   */
  protected TokenInterface $tokenServices;

  /**
   * Replacement paaterns for formatted strings.
   *
   * @var array
   */
  protected array $replacers = [];

  /**
   * Constructs an AlertBuilderService object.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   *   Thrown if the entity type doesn't exist.
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   *   Thrown if the storage handler couldn't be loaded.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, UserPointsServiceInterface $userpoints_service, TokenInterface $token_services) {
    $this->entityTypeManager = $entity_type_manager;
    $this->userpointsService = $userpoints_service;
    $this->tokenServices = $token_services;
    $this->templateStore = $this->entityTypeManager->getStorage('alert_template');
    $this->alertStore = $this->entityTypeManager->getStorage('gamify_alert');
  }

  /**
   * Create new gamify_alert from alert_template.
   *
   * @param string $template_id
   *   The template id to use for alert.
   * @param \Drupal\user\UserInterface $user
   *   The addressed user for the alert.
   * @param string $datareport
   *   Overwrites for template values.
   *   Following values can be overwritten:
   *   - label: string value (may include replace tokens).
   *   - message:  string value (may include replace tokens).
   *   - type: string (see \Drupal\gamify\TypedData\Options\AlertTypeOptions).
   *   - data_report: HTML containing data tables or similar.
   *   - inform_user: bool.
   *   - inform_moderator: bool.
   *   - requires_confirmation: bool.
   */
  public function createAlertFromTemplate(string $template_id, UserInterface $user, string $datareport = ''): void {
    try {
      $template = $this->templateStore->load($template_id);
      $label = $this->tokenServices->replaceClear($template->label());

      $msg = $template->get('message');
      $msg = (is_array($msg)) ? $msg['value'] : $msg;
      $msg = $this->tokenServices->replaceClear($msg);

      $alert = GamifyAlert::create([
        'status' => TRUE,
        'label' => $label,
        'message' => [
          'value' => $msg,
          'format' => 'restricted_html',
        ],
        'data_report' => [
          'value' => $datareport,
          'format' => 'data_report',
        ],
        'type' => $template->get('type'),
        'target_uid' => $user->id(),
        'inform_moderator' => $template->get('inform_moderator'),
        'inform_user' => $template->get('inform_user'),
        'requires_confirmation' => $template->get('requires_confirmation'),
      ]);
      $alert->save();
    }
    catch (\Exception $e) {
      \Drupal::logger('gamify')->error('Alert template %template not found / Could not create Alert for user %user. Further information: @msg', [
        '%template' => $template_id,
        '%user' => "{$user->getAccountName()} ({$user->id()})",
        '@msg' => $e->getMessage(),
      ]);
    }
  }

  /**
   * Returns array with default user replacements.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user entity to receive replacement patterns.
   * @param array $add_replacer
   *   Additional set of custom replacers.
   */
  protected function setReplacers(UserInterface $user, array $add_replacer = []): void {
    $values = [
      'user_id' => $user->id(),
      'user_name' => $user->getAccountName(),
      'user_roles' => implode(', ', $user->getRoles()),
      'user_points' => $this->userpointsService->getPoints($user, LogService::DEFAULT_POINT_TYPE),
    ];
    foreach ($values as $key => $value) {
      $values["@$key"] = $value;
      $values["%$key"] = "<em>$value</em>";
      unset($values[$key]);
    }
    $values = array_merge($values, $add_replacer);
    $this->replacers = $values;
  }

  /**
   * Replaces formatted patterns in the given string.
   *
   * @param string $string
   *   String template with placeholders.
   *
   * @return string
   *   Formatted string with replaced placeholders.
   */
  protected function replace(string $string): string {
    $needles = array_keys($this->replacers);
    return (string) str_replace($needles, $this->replacers, $string);
  }

}

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

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