Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<?php
namespace Drupal\my_module\Twitter;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\Client;
class TwitterClient
{
private $consumerKey;
private $consumerSecret;
private $bearerToken;
private $client;
public function __construct(Client $client, $consumerKey, $consumerSecret)
{
$this->client = $client;
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
}
public function search($keywords, $length = 25)
{
$response = $this->client->request(
'GET',
sprintf('https://api.twitter.com/1.1/search/tweets.json?result_type=recent&count=%s&q=%s', $length, urlencode($keywords)),
[
'headers' => [
'Authorization' => 'Bearer ' . $this->getBearerToken()
]
]
);
if ($response->getStatusCode() != 200) {
throw new \Exception('Twitter search failed with HTTP code ' . $response->getStatusCode());
}
return json_decode((string) $response->getBody(), true);
}
private function getBearerToken()
{
if ($this->bearerToken === null) {
$response = $this->client->request('POST', 'https://api.twitter.com/oauth2/token', [
'headers' => [
'Authorization' => 'Basic ' . $this->getBearerRequestToken(),
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8',
],
'form_params' => [
'grant_type' => 'client_credentials'
]
]);
if ($response->getStatusCode() != 200) {
return null;
}
$body = (string) $response->getBody();
$data = json_decode($body, true);
$this->bearerToken = $data['access_token'];
}
return $this->bearerToken;
}
private function getBearerRequestToken()
{
$token = sprintf('%s:%s', urlencode($this->consumerKey), urlencode($this->consumerSecret));
return base64_encode($token);
}
public static function createClient(ContainerInterface $container)
{
$econfig = $container->get('config.factory')->get('my_module.settings')->get('api');
$client = $container->get('http_client');
return new static($client, $config['consumer_key'], $config['consumer_secret']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment