You are here

public function OpignoMessageThread::getThreadDisplayData in Opigno messaging 3.x

Get the messages thread data: image, title, date, text.

Parameters

\Drupal\private_message\Entity\PrivateMessageThreadInterface $thread: The message thread to get the data for.

Return value

array The array that contains the thread display data.

File

src/Services/OpignoMessageThread.php, line 164

Class

OpignoMessageThread
The private messages manager service.

Namespace

Drupal\opigno_messaging\Services

Code

public function getThreadDisplayData(PrivateMessageThreadInterface $thread) : array {
  $members = $thread
    ->getMembers();
  $count = count($members);

  // Get the last thread message.
  $messages = $thread
    ->getMessages();
  $message = end($messages);
  $data = [];

  // Get the message date and shortened text.
  if ($message instanceof PrivateMessage) {
    $data['date'] = $this
      ->getMessageFormattedDate($message);
    $length = 20;
    $text = strip_tags($message
      ->getMessage());

    // Remove the unneeded characters from the text.
    $text = trim(html_entity_decode($text, ENT_NOQUOTES), " \n\r\t\v\0 ");
    $text = mb_strlen($text) > $length ? mb_substr($text, 0, $length) . '...' : $text;
    $data['text'] = Markup::create($text);
  }

  // The case when the user was deleted.
  if ($count < 2) {
    return $data + [
      'title' => $this
        ->t('Deleted user'),
      'image' => UserStatisticsManager::getDefaultUserPicture(),
    ];
  }

  // Get the user name and image for 1-to-1 message thread.
  if ($count === 2) {
    foreach ($members as $member) {
      if ($member instanceof UserInterface && (int) $member
        ->id() !== (int) $this->account
        ->id()) {
        return $data + [
          'title' => $member
            ->getDisplayName(),
          'image' => UserStatisticsManager::getUserPicture($member),
        ];
      }
    }
  }

  // Get the data for the group message thread.
  $title = $thread
    ->get('field_pm_subject')
    ->getString() ?: $this
    ->t('Discussion');
  if (!$thread
    ->get('field_image')
    ->isEmpty()) {
    $image = $thread
      ->get('field_image')
      ->view([
      'label' => 'hidden',
      'type' => 'image',
      'settings' => [
        'image_style' => 'user_compact_image',
      ],
    ]);
  }
  else {
    $path = drupal_get_path('theme', 'aristotle') . '/src/images/content/group_profile.svg';
    $image = [
      '#theme' => 'image',
      '#uri' => file_exists($path) ? file_url_transform_relative(base_path() . $path) : '',
      '#alt' => $title,
      '#title' => $title,
    ];
  }
  $message_author = $message
    ->getOwner();
  if ($message_author instanceof UserInterface) {
    $data['text'] = $message_author
      ->getDisplayName();
  }
  return $data + [
    'title' => $title,
    'image' => $image,
    'unread_count' => $this
      ->getThreadUnreadMessagesCount($thread),
  ];
}