You are here

public function HubspotBlock::build in HubSpot 8

Same name and namespace in other branches
  1. 3.x src/Plugin/Block/HubspotBlock.php \Drupal\hubspot\Plugin\Block\HubspotBlock::build()

Throws

\GuzzleHttp\Exception\GuzzleException

Overrides BlockPluginInterface::build

File

src/Plugin/Block/HubspotBlock.php, line 99

Class

HubspotBlock
Provides a 'hubspot' block.

Namespace

Drupal\hubspot\Plugin\Block

Code

public function build() : array {
  $leads = $this->hubspot
    ->hubspotGetRecent();

  // This part of the HubSpot API returns HTTP error codes on failure, with
  // no message.
  if (!empty($leads['Error']) || $leads['HTTPCode'] != 200) {
    $output = $this
      ->t('An error occurred when fetching the HubSpot leads data: @error', [
      '@error' => !empty($leads['Error']) ? $leads['Error'] : $leads['HTTPCode'],
    ]);
    return [
      '#type' => 'markup',
      '#markup' => $output,
    ];
  }
  elseif (empty($leads['Data'])) {
    $output = $this
      ->t('No leads to show.');
    return [
      '#type' => 'markup',
      '#markup' => $output,
    ];
  }
  $items = [];
  foreach ($leads['Data']['contacts'] as $lead) {
    $first_name = isset($lead['properties']['firstname']['value']) ? $lead['properties']['firstname']['value'] : NULL;
    $last_name = isset($lead['properties']['lastname']['value']) ? $lead['properties']['lastname']['value'] : NULL;
    $url = Url::fromUri($lead['profile-url']);
    $items[] = [
      '#markup' => Link::fromTextAndUrl($first_name . ' ' . $last_name, $url)
        ->toString() . ' ' . $this
        ->t('(@time ago)', [
        '@time' => $this->dateFormatter
          ->formatInterval($this->time
          ->getRequestTime() - floor($lead['addedAt'] / 1000)),
      ]),
    ];
  }
  return [
    '#theme' => 'item_list',
    '#items' => $items,
    '#cache' => [
      'max-age' => 0,
    ],
  ];
}