You are here

public function PrivateMessageService::createRenderablePrivateMessageThreadLink in Private Message 8.2

Add a link to send a private message to the owner of the given entity.

Parameters

array $build: A render array representing the given entity. Chances should be made to this render array.

\Drupal\Core\Entity\EntityInterface $entity: The entity being rendered.

\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display: The display being used to render the entity.

string $view_mode: The view mode being used to render the entity.

Overrides PrivateMessageServiceInterface::createRenderablePrivateMessageThreadLink

File

src/Service/PrivateMessageService.php, line 336

Class

PrivateMessageService
The Private Message service for the private message module.

Namespace

Drupal\private_message\Service

Code

public function createRenderablePrivateMessageThreadLink(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display
    ->getComponent('private_message_link')) {
    if ($entity instanceof UserInterface) {
      $author = $entity;
    }
    else {
      $author = $entity
        ->getOwner();
    }
    $current_user = \Drupal::currentUser();
    if ($current_user
      ->isAuthenticated()) {
      if ($current_user
        ->hasPermission('use private messaging system') && $current_user
        ->id() != $author
        ->id()) {
        $members = [
          $current_user,
          $author,
        ];
        $thread_id = $this->mapper
          ->getThreadIdForMembers($members);
        if ($thread_id) {
          $url = Url::fromRoute('entity.private_message_thread.canonical', [
            'private_message_thread' => $thread_id,
          ], [
            'attributes' => [
              'class' => [
                'private_message_link',
              ],
            ],
          ]);
          $build['private_message_link'] = [
            '#type' => 'link',
            '#url' => $url,
            '#title' => t('Send private message'),
            '#prefix' => '<div class="private_message_link_wrapper">',
            '#suffix' => '</div>',
          ];
        }
        else {
          $url = Url::fromRoute('private_message.private_message_create', [], [
            'query' => [
              'recipient' => $author
                ->id(),
            ],
          ]);
          $build['private_message_link'] = [
            '#type' => 'link',
            '#url' => $url,
            '#title' => t('Send private message'),
            '#prefix' => '<div class="private_message_link_wrapper">',
            '#suffix' => '</div>',
          ];
        }
      }
    }
    else {
      $url = Url::fromRoute('user.login');
      $build['private_message_link'] = [
        '#type' => 'link',
        '#url' => $url,
        '#title' => t('Send private message'),
        '#prefix' => '<div class="private_message_link_wrapper">',
        '#suffix' => '</div>',
      ];
    }
  }
}