TwistOAuthれどめ勝手に日本語化(Jul 02, 2014)

[TwistOAuth - github](https://github.com/Certainist/TwistOAuth)
~~気の向くままに訳しているので真実が知りたい方は公式をみてください~~
2.1になってREADME全面改訂！！！！この記事は全く参考になりません！！！！！！！！！！！！！！！！

#TwistOAuth

Rest APIとかStreaming APIとかが使えるすごいライブラリです.

#Download

## 圧縮版

1. Download **[ZIP Archive](https://github.com/Certainist/TwistOAuth/archive/master.zip)**.
2.  **`build`** の中の **TwistOAuth.php** を持ってこよう.
3. コードに **[require_once](http://php.net/manual/function.require-once.php)** を使って入れてね.
4. 楽しい！

```php:こんな感じ
require_once __DIR__ . '/TwistOAuth.php';
```

## Raw Files

1. Download **[ZIP Archive](https://github.com/Certainist/TwistOAuth/archive/master.zip)**.
2. Take all files in the directory **`src`**.
3. Write some code that autoloads them with **[spl_autoload_register](http://php.net/manual/function.spl-autoload-register.php)**.
4. 楽しい!

```php:
spl_autoload_register(function ($name) {
    $path = __DIR__ . '/' . $name . '.php';
    if (is_file($path)) {
        require $path;
    }
});
```

#他のライブラリとの比較

でかい表があります

##クラスの概要


###TwistException

```php
class TwistExcepton extends RuntimeException
```

**Error on Twitter** を扱います.

#### TwistBase

```php
abstract class TwistBase
```

Provide static filtering method for child classes.

#### TwistUnserializable

```php
abstract class TwistUnserializable extends TwistBase
```

Protect instances from invalid serializing.

##TwistCredential

```php
class TwistCredential extends TwistBase
```

This instance holds **identity**.  

##TwistRequest


```php
class TwistRequest extends TwistBase
```

This instance holds **request model**.  
For actually executing, use `TwistExecuter` instance.  

#### TwistExecuter

```php
class TwistExecuter extends TwistUnserializable 
```

単体又は複数のリクエストを **非同期的に** 実行します.  

##TwistIterator


```php
class TwistCredential extends TwistExecuter implements Iterator
```

Implemented `Iterator` on `TwistExecuter`.


##TwistOAuth

```php
class TwistOAuth extends TwistBase
```
`TwistCredential` と `TwistRequest` と `TwistIterator` のためのラッパーです.
これは、 **API limitの無効化** もします.

#クラスの詳細


重要なクラス,プロパティ,メソッドについてだけ記述します.

##TwistException


### final public string getMessage()

Return error message.

### final public int getCode()

Return **HTTP Status Code**.

### final public mixed getRequest()

Return `TwistRequest` instance on which an error occurred.  
In the case of error on `stream_select()`, the return value will be **null**.

### final public string __toString()

Return string according to the following format.

```php
return sprintf('[%d] %s', $this->getCode(), $this->getMessage());
```

##TwistCredential

### Properties

- **User Agent**

```php
private readonly string $userAgent = 'TwistOAuth';
```

- **OAuth Consumer**

```php
private readonly string $consumerKey    = '';
private readonly string $consumerSecret = '';
```

- **OAuth Tokens and Verifier**

```php
private readonly string $requestToken       = '';
private readonly string $requestTokenSecret = '';
private readonly string $accessToken        = '';
private readonly string $accessTokenSecret  = '';
private readonly string $verifier           = '';
```

- **User Information**

```php
private readonly string $userId     = '';
private readonly string $screenName = '';
```

- **Parameters for Para-xAuth authorization**

Para-xAuth認証をするときに使う.

```php
private readonly string $screenName = '';
private readonly string $password   = '';
```

### final public __construct()

コンストラクタです(オブジェクト生成時に呼び出される関数).

```php
new TwistCredential(
    string $consumerKey       = '', // Required.
    string $consumerSecret    = '', // Required.
    string $accessToken       = '', // Required unless authorize or authenticate later.
    string $accessTokenSecret = '', // Required unless authorize or authenticate later.
    string $screenName        = '', // Required if Para-xAuth authorize later.
    string $password          = ''  // Required if Para-xAuth authorize later.
)
```

### final public string __toString()

よくわかんないけど一応マニュアル[PHP: Exception::__toString - Manual](http://php.net/manual/ja/exception.tostring.php)
Return string according to the following format.

```php
$string = '';
if ($this->screenName !== '') {
    $string .= "@{$this->screenName}";
}
if ($this->userId !== '') {
    $string .= "(#{$this->userId})";
}
return $string;
```

### final public `$this` setUserAgent()<br />final public `$this` setConsumer()<br />final public `$this` setRequestToken()<br />final public `$this` setAccessToken()<br />final public `$this` setUserId()<br />final public `$this` setScreenName()<br />final public `$this` setPassword()<br />final public `$this` setVerifier()

Setter for properties.

```php
$TwistCredential
    ->setUserAgent    (string $userAgent    = '')
    ->setConsumer     (string $consumerKey  = '', string $consumerSecret     = '')
    ->setRequestToken (string $requestToken = '', string $requestTokenSecret = '')
    ->setAccessToken  (string $accessToken  = '', string $accessTokenSecret  = '')
    ->setUserId       (string $userId       = '')
    ->setScreenName   (string $screenName   = '')
    ->setPassword     (string $password     = '')
    ->setVerifier     (string $verifier     = '')
```

### final public string getAuthenticateUrl()<br />final public string getAuthorizeUrl()

Return URL for **authentication** or **authorization**.

```php
(string) $TwistCredential->getAuthenticateUrl (bool $force_login = false)
(string) $TwistCredential->getAuthorizeUrl    (bool $force_login = false)
```

#### Note: What is the difference between *Authenticate* and *Authorize* ?

|                | Authenticate  |  Authorize   |
| :-------------: |:---------------:| :-----------:|
| New User, Authed User on **force_login** | Jump to Twitter | Jump to Twitter |
| Authed User   | Jump to Twitter, however, if you set your application **__Allow this application to be used to Sign in with Twitter__**, quickly jump back to your callback URL.  |  Jump to Twitter  |

##TwistRequest


This class has a private constructor.  
Use static **factory methods** instead.

### Properties

```php
private readonly string $host;     // e.g. "api.twitter.com"
private readonly string $endpoint; // e.g. "/1.1/statuses/update.json"
private readonly string $method;   // e.g. "POST"
private readonly TwistCredential $credential;
private readonly mixed $response;  // Response object is set here
```

### final public static TwistRequest get()<br />final public static TwistRequest getAuto()<br />final public static TwistRequest post()<br />final public static TwistRequest postAuto()<br />final public static TwistRequest send()

指定されたリクエストのためのインスタンス`TwistRequest`を作ります.

`$params` と `$credential` は後で変えることができます.

- `get` `getAuto` は **GET** リクエストのために使います.
- `post` `postAuto` `send` は **POST** リクエストのために使います.
- `getAuto` `postAuto` は,自動的に `TwistException` を投げます.
- `send` は,レスポンスを待ちません.

```php
(TwistRequest) TwistRequest::get      (string $endpoint, mixed $params = array(), TwistCredential $credential = null)
(TwistRequest) TwistRequest::getAuto  (string $endpoint, mixed $params = array(), TwistCredential $credential = null)
(TwistRequest) TwistRequest::post     (string $endpoint, mixed $params = array(), TwistCredential $credential = null)
(TwistRequest) TwistRequest::postAuto (string $endpoint, mixed $params = array(), TwistCredential $credential = null)
(TwistRequest) TwistRequest::send     (string $endpoint, mixed $params = array(), TwistCredential $credential = null)
```

#### 例

下の同じグループの例はそれぞれ同じ意味になります.

```php:指定のユーザーの情報を取得
$TwistRequest = TwistRequest::getAuto('users/show'); 
$TwistRequest = TwistRequest::getAuto('users/show.json');
$TwistRequest = TwistRequest::getAuto('users/show.json?');
$TwistRequest = TwistRequest::getAuto('users/show?');
$TwistRequest = TwistRequest::getAuto('/users/show');
$TwistRequest = TwistRequest::getAuto('1.1/users/show');
$TwistRequest = TwistRequest::getAuto('/1.1/users/show');
$TwistRequest = TwistRequest::getAuto('https://api.twitter.com/1.1/users/show.json'); 
```

```php:指定のユーザーの情報を取得
$TwistRequest = TwistRequest::getAuto('users/show', array('id' => '12345')); 
$TwistRequest = TwistRequest::getAuto('users/show', 'id=12345'); // WITHOUT URL ENCODED!!
```

```php:プロフィール画像を変更
$TwistRequest = TwistRequest::postAuto('account/update_profile_image', array(
    '@image' => 'test.png',
));
$TwistRequest = TwistRequest::postAuto('account/update_profile_image', '@image=test.png');
$TwistRequest = TwistRequest::postAuto('account/update_profile_image', array(
    'image' => base64_encode(file_get_contents('test.png')), // BASE64 ENCODED!!
));
```

```php:画像付き投稿
$TwistRequest = TwistRequest::postAuto('statuses/update_with_media', array(
    '@media[]' => 'test.png',
    'status'   => 'TEST',
));
$TwistRequest = TwistRequest::postAuto('statuses/update_with_media',
    '@media[]=test.png&status=TEST',
);
$TwistRequest = TwistRequest::postAuto('statuses/update_with_media', array(
    'media[]' => file_get_contents('test.png'), // WITHOUT BASE64 ENCODED!!
    'status'  => 'TEST',
));
```

### final public static TwistRequest login()

Provide a model for **Para-xAuth** authorization.

```php
(TwistRequest) TwistRequest::login(TwistCredential $credential)
```

### final public `$this` setParams()<br />final public `$this` setCredential()

Setter for properties.  
Exceptionally, the instances created by `TwistRequest::login()` cannot be applied.

```php
$TwistRequest
    ->setParams     (mixed $params     = array())
    ->setCredential (mixed $credential = null)
```

### final public mixed execute()

```php
(mixed) $TwistRequest->execute()
```

Execute request internally using `TwistIterator` and return response.  

#### Return Value Types

| Methods     | Value                                                                |
|:-----------:|:--------------------------------------------------------------------:|
|get          | **stdClass** or **array** or `TwistException`                        |
|post         | **stdClass** or **array** or `TwistException`                        |
|getAuto      | **stdClass** or **array** (`TwistException` is automatically thrown) |
|postAuto     | **stdClass** or **array** (`TwistException` is automatically thrown) |
|send         | **null**                                                             |
|login        | **stdClass** (`TwistException` is automatically thrown)              |

#### Examples

```php
try {
    $statuses = TwistRequest::getAuto('statuses/home_timeline', '', $credential)->execute();
    foreach ($statuses as $status) {
        echo "<p>@{$status->screen_name}: {$status->text}<p>\n";
    }
} catch (TwistException $e) {
    echo $e . "\n";
}
```

```php
$statuses = TwistRequest::get('statuses/home_timeline', '', $credential)->execute();
if ($statuses instanceof TwistException) {
    die($statuses . "\n");
}
foreach ($statuses as $status) {
    echo "<p>@{$status->screen_name}: {$status->text}<p>\n";
}
```

##TwistIterator

Manually use this instance insteadof `$TwistRequest->execute()` for **Multiple Requests** or **Streaming Requests**.  

### final public __construct()

```php
new TwistIterator(TwistRequest $request1, TwistRequest $request2, ...)
new TwistIterator(array<TwistRequest> $requests)
```

### final public `$this` setInterval()

Set interval function called while looping `foreach` block.

```php
$TwistIterator->setInterval(callable $callback, float $interval = 0, array $args = array())
```

### final public `$this` runAll()

Execute all requests internally using `TwistIterator`.

```php
$TwistRequest->runAll()
```

### Examples

#### Multiple REST requests

```php
$TwistRequests = array(
    TwistRequest::send('statuses/update', 'status=@BarackObama FOO!!', $credential),
    TwistRequest::send('statuses/update', 'status=@BarackObama BAR!!', $credential),
    TwistRequest::send('statuses/update', 'status=@BarackObama BAZ!!', $credential),
);
$ex = new TwistExecuter($TwistRequests);
$ex->runAll();
```

```php
$TwistRequests = array(
    TwistRequest::send('statuses/update', 'status=@BarackObama FOO!!', $credential),
    TwistRequest::send('statuses/update', 'status=@BarackObama BAR!!', $credential),
    TwistRequest::send('statuses/update', 'status=@BarackObama BAZ!!', $credential),
);
$it = new TwistIterator($TwistRequests);
$it->runAll();
```

#### Single streaming request

```php
set_time_limit(0);
try {
    $TwistRequest = TwistRequest::getAuto('user', '', $credential);
    foreach (new TwistIterator($TwistRequest) as $TwistRequest) {
        var_dump($TwistRequest->response);
    }
} catch (TwistException $e) {
    var_dump((string)$e);
}
```

#### Multiple streaming requests

```php
set_time_limit(0);
try {
    $TwistRequests = array(
        TwistRequest::getAuto('user', '', $credential),
        TwistRequest::getAuto('statuses/sample', '', $credential),
        TwistRequest::postAuto('statuses/filter', 'track=youtube', $credential),
    );
    foreach (new TwistIterator($TwistRequests) as $TwistRequest) {
        var_dump($TwistRequest->response);
    }
} catch (TwistException $e) {
    var_dump((string)$e);
}
```

##TwistOAuth

**シングルRESTリクエスト** がしたい人はこれを使おう.
POSTリクエストの時は、メインの認証だけ使われるけど、GETの時は、サブ認証も使わます.規制回避します.

### final public __construct()

```php
new TwistOAuth(TwistCredential $credential)
```

### final public `$this` setSub()

Register or unregister sub TwistCredential instances.

```php
$TwistOAuth->setSub(TwistCredential $credential1, TwistCredential $credential2, ...)
$TwistOAuth->setSub(array<TwistCredential> $credentials)
$TwistOAuth->setSub()
```

### final public mixed get()<br />final public mixed getAuto()<br />final public mixed post()<br />final public mixed postAuto()<br />final public void send()<br />final public stdClass login()

```php
(mixed)    $TwistOAuth->get      (string $endpoint, mixed $params = array())
(mixed)    $TwistOAuth->getAuto  (string $endpoint, mixed $params = array())
(mixed)    $TwistOAuth->post     (string $endpoint, mixed $params = array())
(mixed)    $TwistOAuth->postAuto (string $endpoint, mixed $params = array())
(null)     $TwistOAuth->send     (string $endpoint, mixed $params = array())
(stdClass) $TwistOAuth->login    ()
```

### サンプル

#### 基本的な使い方

```php:TL表示するぜ
try {
    $TwistOAuth = new TwistOAuth($credential);
    foreach ($TwistOAuth->getAuto('statuses/home_timeline') as $status) {
        var_dump($status);
    }
    $TwistOAuth->postAuto('statuses/update', array('status' => 'test'));
} catch (TwistException $e) {
    var_dump((string)$e);
}
```

#### API規制回避

```php
try {
    $TwistOAuth = new TwistOAuth($mainCredential);
    $TwistOAuth->setSub($subCredential1, $subCredential2);
    $TwistOAuth->getAuto('statuses/home_timeline');
    $TwistOAuth->getAuto('statuses/home_timeline');
    $TwistOAuth->getAuto('statuses/home_timeline');
    $TwistOAuth->getAuto('statuses/home_timeline');
    $TwistOAuth->getAuto('statuses/home_timeline');
    $TwistOAuth->getAuto('statuses/home_timeline');
    $TwistOAuth->getAuto('statuses/home_timeline');
    ...
} catch (TwistException $e) {
    var_dump((string)$e);
}
```