You are here

public function TweetFetcher::fetchTweet in Media entity Twitter 8.2

Same name and namespace in other branches
  1. 8 src/TweetFetcher.php \Drupal\media_entity_twitter\TweetFetcher::fetchTweet()

Retrieves a tweet by its ID.

Parameters

int $id: The tweet ID.

Return value

array The tweet information.

Throws

\Drupal\media_entity_twitter\Exception\TwitterApiException If the Twitter API returns errors in the response.

Overrides TweetFetcherInterface::fetchTweet

File

src/TweetFetcher.php, line 48

Class

TweetFetcher
Fetches (and caches) tweet data from Twitter's API.

Namespace

Drupal\media_entity_twitter

Code

public function fetchTweet($id) {

  // Tweets don't change much, so pull it out of the cache (if we have one)
  // if this one has already been fetched.
  if ($this->cache && ($cached_tweet = $this->cache
    ->get($id))) {
    return $cached_tweet->data;
  }

  // Ensure that we have an actual API exchange instance.
  if (empty($this->twitter)) {
    throw new \UnexpectedValueException('Twitter API exchange has not been initialized; credentials may not have been set yet.');
  }

  // Query Twitter's API.
  $response = $this->twitter
    ->setGetfield('?id=' . $id . '&tweet_mode=extended')
    ->buildOAuth('https://api.twitter.com/1.1/statuses/show.json', 'GET')
    ->performRequest();
  if (empty($response)) {
    throw new \Exception("Could not retrieve tweet {$id}.");
  }

  // Handle errors as per https://dev.twitter.com/overview/api/response-codes.
  if (!empty($response['errors'])) {
    throw new TwitterApiException($response['errors']);
  }
  $response = Json::decode($response);

  // If we have a cache, store the response for future use.
  if ($this->cache) {

    // Tweets don't change often, so the response should expire from the cache
    // on its own in 90 days.
    $this->cache
      ->set($id, $response, time() + 86400 * 90);
  }
  return $response;
}