Skip to content

Instantly share code, notes, and snippets.

@DuaelFr
Last active March 14, 2017 12:19
Show Gist options
  • Save DuaelFr/8aeb1cd83389f5be8848 to your computer and use it in GitHub Desktop.
Save DuaelFr/8aeb1cd83389f5be8848 to your computer and use it in GitHub Desktop.
Guzzle Oauth current state
<?php
/**
* @file
* Contains \Drupal\sf_test\Controller\DefaultController.
*/
namespace Drupal\sf_test\Controller;
use Drupal\Core\Controller\ControllerBase;
use GuzzleHttp\Exception\ClientException;
/**
* Class DefaultController.
*
* @package Drupal\sf_test\Controller
*/
class DefaultController extends ControllerBase {
/**
* Hello.
*
* @return string
* Return Hello string.
*/
public function hello() {
// Get the HTTP Client Factory so that custom options can be added.
$factory = \Drupal::service('http_client_factory');
$client = $factory->fromOptions([
'base_uri' => 'https://api.twitter.com',
'auth' => 'oauth', // <--- magic !!
]);
try {
$response = $client->get('1.1/statuses/user_timeline.json');
$tweets = var_export(json_decode($response->getBody()), TRUE);
}
catch (ClientException $e) {
$tweets = $e->getMessage();
}
return [
'#type' => 'markup',
'#prefix' => '<pre>',
'#markup' => $tweets,
'#suffix' => '</pre>',
];
}
}
services:
guzzle_oauth.factory:
class: Drupal\guzzle_oauth\OauthFactory
arguments: ['@config.factory']
guzzle_oauth.middleware:
class: GuzzleHttp\Subscriber\Oauth\Oauth1
factory: guzzle_oauth.factory:getService
tags:
- { name: http_client_middleware } # <-- magic
consumer_key: "consumer_key"
consumer_secret: "consumer_secret"
token: "token"
token_secret: "token_secret"
<?php
/**
* @file
* Contains \Drupal\guzzle_oauth\OauthFactory.
*/
namespace Drupal\guzzle_oauth;
use Drupal\Core\Config\ConfigFactory;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
/**
* Class OauthFactory
*/
class OauthFactory {
/**
* @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* OauthFactory constructor.
*
* @param \Drupal\Core\Config\ConfigFactory $configFactory
*/
function __construct(ConfigFactory $configFactory) {
$this->config = $configFactory->get('guzzle_oauth.settings');
}
/**
* @return Oauth1
*/
public function getService() {
return new Oauth1((array) $this->config->get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment