TweetFetcher.php in Media entity Twitter 8.2
File
src/TweetFetcher.php
View source
<?php
namespace Drupal\media_entity_twitter;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\media_entity_twitter\Exception\TwitterApiException;
class TweetFetcher implements TweetFetcherInterface {
protected $cache;
protected $credentials = [];
protected $twitter;
public function __construct(CacheBackendInterface $cache = NULL) {
$this->cache = $cache;
}
public function fetchTweet($id) {
if ($this->cache && ($cached_tweet = $this->cache
->get($id))) {
return $cached_tweet->data;
}
if (empty($this->twitter)) {
throw new \UnexpectedValueException('Twitter API exchange has not been initialized; credentials may not have been set yet.');
}
$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}.");
}
if (!empty($response['errors'])) {
throw new TwitterApiException($response['errors']);
}
$response = Json::decode($response);
if ($this->cache) {
$this->cache
->set($id, $response, time() + 86400 * 90);
}
return $response;
}
public function getCredentials() {
return $this->credentials;
}
public function setCredentials($consumer_key, $consumer_secret, $oauth_access_token, $oauth_access_token_secret) {
$this->credentials = [
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'oauth_access_token' => $oauth_access_token,
'oauth_access_token_secret' => $oauth_access_token_secret,
];
$this->twitter = new \TwitterAPIExchange($this->credentials);
}
}
Classes
Name |
Description |
TweetFetcher |
Fetches (and caches) tweet data from Twitter's API. |