3 namespace Drupal\media_entity_twitter;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Core\Cache\CacheBackendInterface;
7 use Drupal\media_entity_twitter\Exception\TwitterApiException;
10 * Fetches (and caches) tweet data from Twitter's API.
12 class TweetFetcher implements TweetFetcherInterface {
15 * The optional cache backend.
17 * @var \Drupal\Core\Cache\CacheBackendInterface
22 * The current set of Twitter API credentials.
26 protected $credentials = [];
29 * The current API exchange object.
31 * @var \TwitterAPIExchange
36 * TweetFetcher constructor.
38 * @param \Drupal\Core\Cache\CacheBackendInterface|NULL $cache
39 * (optional) A cache bin for storing fetched tweets.
41 public function __construct(CacheBackendInterface $cache = NULL) {
42 $this->cache = $cache;
48 public function fetchTweet($id) {
49 // Tweets don't change much, so pull it out of the cache (if we have one)
50 // if this one has already been fetched.
51 if ($this->cache && $cached_tweet = $this->cache->get($id)) {
52 return $cached_tweet->data;
55 // Ensure that we have an actual API exchange instance.
56 if (empty($this->twitter)) {
57 throw new \UnexpectedValueException('Twitter API exchange has not been initialized; credentials may not have been set yet.');
60 // Query Twitter's API.
61 $response = $this->twitter
62 ->setGetfield('?id=' . $id)
63 ->buildOAuth('https://api.twitter.com/1.1/statuses/show.json', 'GET')
66 if (empty($response)) {
67 throw new \Exception("Could not retrieve tweet $id.");
69 // Handle errors as per https://dev.twitter.com/overview/api/response-codes.
70 if (!empty($response['errors'])) {
71 throw new TwitterApiException($response['errors']);
74 $response = Json::decode($response);
75 // If we have a cache, store the response for future use.
77 // Tweets don't change often, so the response should expire from the cache
78 // on its own in 90 days.
79 $this->cache->set($id, $response, time() + (86400 * 90));
88 public function getCredentials() {
89 return $this->credentials;
95 public function setCredentials($consumer_key, $consumer_secret, $oauth_access_token, $oauth_access_token_secret) {
96 $this->credentials = [
97 'consumer_key' => $consumer_key,
98 'consumer_secret' => $consumer_secret,
99 'oauth_access_token' => $oauth_access_token,
100 'oauth_access_token_secret' => $oauth_access_token_secret,
102 $this->twitter = new \TwitterAPIExchange($this->credentials);