Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created August 14, 2014 12:33
Show Gist options
  • Select an option

  • Save hubgit/f5dbc97998760cef0cbb to your computer and use it in GitHub Desktop.

Select an option

Save hubgit/f5dbc97998760cef0cbb to your computer and use it in GitHub Desktop.

Revisions

  1. hubgit created this gist Aug 14, 2014.
    46 changes: 46 additions & 0 deletions OAuthClient.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    <?php

    class OAuthClient {
    /** @var OAuth */
    public $oauth;

    /** @var cURL */
    public $curl;

    function __construct(array $config) {
    // sudo pecl install oauth
    $this->oauth = new OAuth($config['api_key'], $config['api_secret']);
    $this->oauth->setToken($config['access_token'], $config['access_token_secret']);

    $this->curl = curl_init();

    curl_setopt_array($this->curl, array(
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_VERBOSE => true,
    ));
    }

    function exec($url, $data = array(), $method = 'GET') {
    curl_setopt($this->curl, CURLOPT_URL, $url);

    switch ($method) {
    case 'GET':
    curl_setopt($this->curl, CURLOPT_HTTPGET, true);
    break;

    case 'POST':
    curl_setopt($this->curl, CURLOPT_POSTFIELDS, http_build_query($data));
    break;
    }

    curl_setopt($this->curl, CURLOPT_HTTPHEADER, array(
    'Authorization: ' . $this->oauth->getRequestHeader($method, $url, $data)
    ));

    curl_exec($this->curl);

    // TODO: retry connection if failed, with backoff
    // TODO: retry on idle connection
    }
    }