You are here

class RecentKanbanActivities in Content Planner 8

Provides a user block for Content Planner Dashboard.

Plugin annotation


@DashboardBlock(
  id = "recent_kanban_activities",
  name = @Translation("Recent Kanban Activities")
)

Hierarchy

Expanded class hierarchy of RecentKanbanActivities

File

modules/content_kanban/src/Plugin/DashboardBlock/RecentKanbanActivities.php, line 27

Namespace

Drupal\content_kanban\Plugin\DashboardBlock
View source
class RecentKanbanActivities extends DashboardBlockBase {

  /**
   * An integer representing the default query limit.
   *
   * @var int
   */
  protected $defaultLimit = 10;

  /**
   * The date formatter object.
   *
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $dateFormatter;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, DateFormatterInterface $date_formatter) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('date.formatter'));
  }

  /**
   * {@inheritdoc}
   */
  public function getConfigSpecificFormFields(FormStateInterface &$form_state, Request &$request, array $block_configuration) {
    $form = [];
    $limit_default_value = $this
      ->getCustomConfigByKey($block_configuration, 'limit', $this->defaultLimit);

    // Limit.
    $form['limit'] = [
      '#type' => 'number',
      '#title' => t('Quantity'),
      '#required' => TRUE,
      '#default_value' => $limit_default_value,
    ];
    $user_picture_field_exists = !\Drupal::config('field.field.user.user.user_picture')
      ->isNew();
    $show_user_thumb_default_value = $limit_default_value = $this
      ->getCustomConfigByKey($block_configuration, 'show_user_thumb', 0);
    $form['show_user_thumb'] = [
      '#type' => 'checkbox',
      '#title' => t('Show thumbnail image of User image'),
      '#description' => t('This option is only available, if the User account has the "user_picture" field. See Account configuration.'),
      '#disabled' => !$user_picture_field_exists,
      '#default_value' => $show_user_thumb_default_value,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    // Get config.
    $config = $this
      ->getConfiguration();

    // Get limit.
    $limit = $this
      ->getCustomConfigByKey($config, 'limit', $this->defaultLimit);

    /* @var $kanban_log_service \Drupal\content_kanban\KanbanLogService */
    $kanban_log_service = \Drupal::service('content_kanban.kanban_log_service');

    // Get Logs.
    if ($logs = $kanban_log_service
      ->getRecentLogs($limit, [
      'exclude_anonymous_users' => TRUE,
    ])) {
      $entries = $this
        ->buildKanbanLogActivities($logs);
      $build = [
        '#theme' => 'content_kanban_log_recent_activity',
        '#entries' => $entries,
        '#show_user_thumb' => $this
          ->getCustomConfigByKey($config, 'show_user_thumb', 0),
      ];
    }
    return $build;
  }

  /**
   * Builds the log entries.
   *
   * @param array $logs
   *   An array with the logs.
   *
   * @return array
   *   Returns an array with the logs.
   */
  protected function buildKanbanLogActivities(array $logs) {
    $entries = [];
    foreach ($logs as $log) {

      // Get User object.
      $user = $log
        ->getOwner();

      // Get Entity object.
      $entity = $log
        ->getEntityObject();

      // If the Entity or user cannot be found, then continue with the next log.
      if (!$entity || !$user) {
        continue;
      }
      if ($message = $this
        ->composeMessage($log, $user, $entity)) {
        $entry = [
          'user_profile_image' => UserProfileImage::generateProfileImageUrl($user, 'content_kanban_user_thumb'),
          'username' => $user
            ->getAccountName(),
          'message' => $message,
        ];
        $entries[] = $entry;
      }
    }
    return $entries;
  }

  /**
   * Composes the message.
   *
   * @param \Drupal\content_kanban\Entity\KanbanLog $log
   *   The Kanban log object.
   * @param \Drupal\user\Entity\User $user
   *   The User object.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return string
   *   Returns a string containing the composed message.
   */
  protected function composeMessage(KanbanLog $log, User $user, EntityInterface $entity) {
    $state_from = $log
      ->getStateFrom();
    $state_to = $log
      ->getStateTo();
    $workflow_states = KanbanWorkflowService::getWorkflowStates($log
      ->getWorkflow());
    if ($state_from == $state_to) {
      $message = t('@username has updated @entity_type "@entity" @time ago', [
        '@username' => $user
          ->getAccountName(),
        '@entity' => $entity
          ->label(),
        '@entity_type' => ucfirst($entity
          ->getEntityTypeId()),
        '@time' => $this
          ->calculateTimeAgo($log),
      ]);
    }
    else {
      $message = t('@username has changed the state of @entity_type "@entity" from "@state_from" to "@state_to" @time ago', [
        '@username' => $user
          ->getAccountName(),
        '@entity' => $entity
          ->label(),
        '@entity_type' => ucfirst($entity
          ->getEntityTypeId()),
        '@time' => $this
          ->calculateTimeAgo($log),
        '@state_from' => $workflow_states[$state_from],
        '@state_to' => $workflow_states[$state_to],
      ]);
    }
    return $message;
  }

  /**
   * Gets the time difference for the given log since the created time.
   *
   * @param \Drupal\content_kanban\Entity\KanbanLog $log
   *   The Kanban log object.
   *
   * @return mixed
   *   Returns the calculated time ago for the given Kanban log.
   */
  protected function calculateTimeAgo(KanbanLog $log) {
    return $this->dateFormatter
      ->formatTimeDiffSince($log
      ->getCreatedTime());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DashboardBlockBase::$entityTypeManager protected property The route match.
DashboardBlockBase::getBasicConfigStructure public static function Get basic configuration structure for the block configuration.
DashboardBlockBase::getConfiguration public function Get Configuration passed in by Plugin Manager. Overrides DashboardBlockInterface::getConfiguration
DashboardBlockBase::getCustomConfigByKey protected function Get custom config.
DashboardBlockBase::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
DashboardBlockBase::getName public function Return the name of the block. Overrides DashboardBlockInterface::getName
DashboardBlockBase::isConfigurable public function Determines if the plugin is configurable. Overrides PluginBase::isConfigurable
DashboardBlockBase::submitSettingsForm public function Submit form handler. Overrides DashboardBlockInterface::submitSettingsForm
DashboardBlockBase::validateForm public function Validates teh plugin config form. Overrides DashboardBlockInterface::validateForm
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
RecentKanbanActivities::$dateFormatter protected property The date formatter object.
RecentKanbanActivities::$defaultLimit protected property An integer representing the default query limit.
RecentKanbanActivities::build public function Build the block and return a renderable array. Overrides DashboardBlockBase::build
RecentKanbanActivities::buildKanbanLogActivities protected function Builds the log entries.
RecentKanbanActivities::calculateTimeAgo protected function Gets the time difference for the given log since the created time.
RecentKanbanActivities::composeMessage protected function Composes the message.
RecentKanbanActivities::create public static function Creates an instance of the plugin. Overrides DashboardBlockBase::create
RecentKanbanActivities::getConfigSpecificFormFields public function Add additonal form elements specific to the Plugin. Overrides DashboardBlockBase::getConfigSpecificFormFields
RecentKanbanActivities::__construct public function Constructs a new UserLoginBlock instance. Overrides DashboardBlockBase::__construct