You are here

public function HeartbeatBlock::build in Heartbeat 8

Throws

\Drupal\Core\Database\InvalidQueryException

Overrides BlockPluginInterface::build

File

src/Plugin/Block/HeartbeatBlock.php, line 120

Class

HeartbeatBlock
Provides a 'HeartbeatBlock' block.

Namespace

Drupal\heartbeat\Plugin\Block

Code

public function build() {
  $messages = array();
  if (\Drupal::currentUser()
    ->id() > 0) {
    $myConfig = \Drupal::service('config.factory')
      ->getEditable('heartbeat_feed.settings');
    $friendData = \Drupal::config('heartbeat_friendship.settings')
      ->get('data');

    //TODO Use User IDs from friendData as conditions for heartbeats, rather than retrieving friendships in a separate query as is what follows in the lines ahead
    $feed = $myConfig
      ->get('message');
    if ($feed === null || $feed === 'null') {
      $feed = "Public";
      $myConfig
        ->set('message', $feed)
        ->save();
    }
    $uids = null;
    $query = Database::getConnection()
      ->select('heartbeat_friendship', 'hf')
      ->fields('hf', [
      'uid',
      'uid_target',
    ]);
    $conditionOr = $query
      ->orConditionGroup()
      ->condition('hf.uid', \Drupal::currentUser()
      ->id())
      ->condition('hf.uid_target', \Drupal::currentUser()
      ->id());
    $results = $query
      ->condition($conditionOr)
      ->execute();
    if ($result = $results
      ->fetchAll()) {
      $uids = array();
      foreach ($result as $uid) {
        $uids[] = $uid->uid_target;
        $uids[] = $uid->uid;
      }
    }
    if ($feed !== null && $this->heartbeatStreamServices) {
      $uids = count($uids) > 1 ? array_unique($uids) : $uids;
      if (!empty($uids)) {
        foreach ($this->heartbeatStreamServices
          ->createStreamForUidsByType($uids, $feed) as $heartbeat) {
          $this
            ->renderMessage($messages, $heartbeat);
        }
      }
      else {
        foreach ($this->heartbeatStreamServices
          ->createStreamByType($feed) as $heartbeat) {
          $this
            ->renderMessage($messages, $heartbeat);
        }
      }
    }
    else {
      foreach ($this->heartbeatStreamServices
        ->loadAllStreams() as $heartbeat) {
        $this
          ->renderMessage($messages, $heartbeat);
      }
    }
  }
  else {
    foreach ($this->heartbeatStreamServices
      ->loadAllStreams() as $heartbeat) {
      $this
        ->renderMessage($messages, $heartbeat);
    }
  }
  return [
    '#theme' => 'heartbeat_stream',
    '#messages' => $messages,
    '#attached' => array(
      'library' => 'heartbeat/heartbeat',
      'drupalSettings' => [
        'activeFeed' => 'jigga',
        'friendData' => $friendData,
      ],
    ),
    '#cache' => array(
      'max-age' => 0,
    ),
  ];
}