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

src/AbstractUserService.php
<?php

namespace Drupal\gamify;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\gamify\Traits\GamifyEntityLogTrait;
use Drupal\gamify\TypedData\Options\AbstractUserOptions as UserOpts;
use Psr\Log\LoggerInterface;

/**
 * Defines a class to build a listing of Argument entities.
 *
 * @ingroup gamify
 */
class AbstractUserService {

  use GamifyEntityLogTrait;

  /**
   * The current active database's master connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected Connection $database;

  /**
   * Drupal\Core\Entity\EntityTypeManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Drupal\Core\Session\AccountProxyInterface definition.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected AccountProxyInterface $currentUser;

  /**
   * Drupal\Core\Extension\ModuleHandlerInterface definition.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected ModuleHandlerInterface $moduleHandler;

  /**
   * Drupal\Core\Logger\LoggerChannelInterface definition.
   *
   * @var \Psr\Log\LoggerInterface|\Drupal\Core\Logger\LoggerChannelInterface
   */
  protected LoggerInterface $logger;

  /**
   * Constructs a new EvaluatingService object.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountProxyInterface $current_user, Connection $database, ModuleHandlerInterface $moduleHandler, LoggerChannelFactoryInterface $logger) {
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $current_user;
    $this->database = $database;
    $this->moduleHandler = $moduleHandler;
    $this->logger = $logger->get('gamify');
  }

  /**
   * Returns user from abstract type definition.
   *
   * @param string $type
   *   The type definition <current_user|entity_creator|involved_users>.
   * @param \Drupal\Core\Entity\EntityInterface|null $entity
   *   The entity to extract the creator from.
   * @param bool $return_user_entity
   *   If TRUE user entity is returned, else the user id is returned.
   *
   * @return \Drupal\user\UserInterface[]|array
   *   Returns the concrete user(s) that created or updated the entity.
   */
  public function getUsers(string $type, ?EntityInterface $entity = NULL, bool $return_user_entity = FALSE): array {
    $uids = [];
    if ($type == UserOpts::CURRENT_USER) {
      $uids = [$this->currentUser->id()];
    }
    elseif ($type == UserOpts::ENTITY_CREATOR && $entity) {
      $uids = $this->getEntityCreator($entity);
    }
    elseif ($type == UserOpts::PARENT_ENTITY_CREATOR && $entity) {
      $uids = $this->getParentEntityCreator($entity);
    }
    elseif ($type == UserOpts::INVOLVED_USERS && $entity) {
      $uids = $this->getInvolvedUsers($entity);
    }
    if (count($uids) && $return_user_entity) {
      try {
        /** @var \Drupal\user\UserInterface[] */
        return $this->entityTypeManager->getStorage('user')->loadMultiple($uids);
      }
      catch (InvalidPluginDefinitionException | PluginNotFoundException $e) {
        $this->logger->error($e->getMessage());
        return [];
      }
    }
    return $uids;
  }

  /**
   * Get the user that created the subject entity from userpoints log history.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   If FALSE the method returns the user_id, if TRUE the user object.
   *
   * @return array
   *   Returns the user that created the entity.
   */
  public function getEntityCreator(EntityInterface $entity): array {
    $user_id = NULL;
    try {
      $log_id = $this->getLogHashSearchStr('create', $entity);
      $results = $this->queryLog($log_id);
      if ($result = reset($results)) {
        $user_id = ($result->entity_type_id === 'user') ? $result->entity_id : NULL;
      }
      return ($user_id) ? [$user_id] : [];
    } catch (\Exception $exception) {
      $this->logger->warning($exception->getMessage());
      return [];
    }
  }

  /**
   * Get user that created parent entity of subject entity from UP log history.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   If FALSE the method returns the user_id, if TRUE the user object.
   *
   * @return array
   *   Returns the user that created the entity.
   */
  public function getParentEntityCreator(EntityInterface $entity): array {
    if ($parent_entity = $this->getParentEntity($entity)) {
      return $this->getEntityCreator($parent_entity);
    }
    return [];
  }

  /**
   * To resolve parent_entity_creator we need parent entity delivered here.
   *
   * For entities in a nested entity structure you may want address the parent
   * entity or the parent entity creator. If the entity has no method like
   * getParentEntity() you can use this hook to get it with custom code.
   * This is to be more flexible in building rules conditions and actions.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The inspected entity for parent entity.
   *
   * @return \Drupal\Core\Entity\EntityInterface|false
   *   The optional context of an entity e.g. parent entity.
   *
   * @see hook_gamify_get_ENTITY_TYPE_parent_entity()
   */
  protected function getParentEntity(EntityInterface $entity): ?EntityInterface {
    if (method_exists($entity, 'getParentEntity')) {
      $parent_entity = $entity->getParentEntity();
      if ($parent_entity instanceof EntityInterface) {
        return $parent_entity;
      }
    }
    $entity_type = $entity->getEntityTypeId();
    $parent_entities = $this->moduleHandler
      ->invokeAll("gamify_get_{$entity_type}_parent_entity", ['entity' => $entity]);
    return reset($parent_entities);
  }

  /**
   * Get the user that created an entity, given ba entity_type_id and entity_id.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   If FALSE the method returns the user_id, if TRUE the user object.
   *
   * @return \Drupal\user\UserInterface[]|array
   *   Returns the user that created the entity.
   *
   * @throws \Exception
   */
  public function getInvolvedUsers(EntityInterface $entity): array {
    $results = [];
    foreach (['create', 'update'] as $operation) {
      $log_search = $this->getLogHashSearchStr($operation, $entity);
      $results = array_merge($results, $this->queryLog($log_search));
    }
    $user_ids = [];
    foreach ($results as $result) {
      if ($result->entity_type_id === 'user' && !in_array($result->entity_id, $user_ids)) {
        $user_ids[] = $result->entity_id;
      }
    }
    return $user_ids;
  }

}

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

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