Skip to content

Commit

Permalink
Merge pull request #675 from abraham/json-request
Browse files Browse the repository at this point in the history
Json request
  • Loading branch information
abraham authored Jul 2, 2018
2 parents ea135f2 + e4735d6 commit 01026d2
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 21 deletions.
12 changes: 10 additions & 2 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class Request
protected $parameters;
protected $httpMethod;
protected $httpUrl;
protected $json;
public static $version = '1.0';

/**
Expand Down Expand Up @@ -43,7 +44,8 @@ public static function fromConsumerAndToken(
Token $token = null,
$httpMethod,
$httpUrl,
array $parameters = []
array $parameters = [],
$json = false
) {
$defaults = [
"oauth_version" => Request::$version,
Expand All @@ -55,7 +57,13 @@ public static function fromConsumerAndToken(
$defaults['oauth_token'] = $token->key;
}

$parameters = array_merge($defaults, $parameters);
// The json payload is not included in the signature on json requests,
// therefore it shouldn't be included in the parameters array.
if ($json) {
$parameters = $defaults;
} else {
$parameters = array_merge($defaults, $parameters);
}

return new Request($httpMethod, $httpUrl, $parameters);
}
Expand Down
48 changes: 29 additions & 19 deletions src/TwitterOAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,20 +206,21 @@ public function oauth2($path, array $parameters = [])
*/
public function get($path, array $parameters = [])
{
return $this->http('GET', self::API_HOST, $path, $parameters);
return $this->http('GET', self::API_HOST, $path, $parameters, false);
}

/**
* Make POST requests to the API.
*
* @param string $path
* @param array $parameters
* @param bool $json
*
* @return array|object
*/
public function post($path, array $parameters = [])
public function post($path, array $parameters = [], $json = false)
{
return $this->http('POST', self::API_HOST, $path, $parameters);
return $this->http('POST', self::API_HOST, $path, $parameters, $json);
}

/**
Expand All @@ -232,7 +233,7 @@ public function post($path, array $parameters = [])
*/
public function delete($path, array $parameters = [])
{
return $this->http('DELETE', self::API_HOST, $path, $parameters);
return $this->http('DELETE', self::API_HOST, $path, $parameters, false);
}

/**
Expand All @@ -245,7 +246,7 @@ public function delete($path, array $parameters = [])
*/
public function put($path, array $parameters = [])
{
return $this->http('PUT', self::API_HOST, $path, $parameters);
return $this->http('PUT', self::API_HOST, $path, $parameters, false);
}

/**
Expand Down Expand Up @@ -278,7 +279,7 @@ public function mediaStatus($media_id)
return $this->http('GET', self::UPLOAD_HOST, 'media/upload', [
'command' => 'STATUS',
'media_id' => $media_id
]);
], false);
}

/**
Expand All @@ -296,7 +297,7 @@ private function uploadMediaNotChunked($path, array $parameters)
throw new \InvalidArgumentException('You must supply a readable file');
}
$parameters['media'] = base64_encode($file);
return $this->http('POST', self::UPLOAD_HOST, $path, $parameters);
return $this->http('POST', self::UPLOAD_HOST, $path, $parameters, false);
}

/**
Expand All @@ -309,7 +310,7 @@ private function uploadMediaNotChunked($path, array $parameters)
*/
private function uploadMediaChunked($path, array $parameters)
{
$init = $this->http('POST', self::UPLOAD_HOST, $path, $this->mediaInitParameters($parameters));
$init = $this->http('POST', self::UPLOAD_HOST, $path, $this->mediaInitParameters($parameters), false);
// Append
$segmentIndex = 0;
$media = fopen($parameters['media'], 'rb');
Expand All @@ -319,14 +320,14 @@ private function uploadMediaChunked($path, array $parameters)
'media_id' => $init->media_id_string,
'segment_index' => $segmentIndex++,
'media_data' => base64_encode(fread($media, $this->chunkSize))
]);
], false);
}
fclose($media);
// Finalize
$finalize = $this->http('POST', self::UPLOAD_HOST, 'media/upload', [
'command' => 'FINALIZE',
'media_id' => $init->media_id_string
]);
], false);
return $finalize;
}

Expand Down Expand Up @@ -359,16 +360,17 @@ private function mediaInitParameters(array $parameters)
* @param string $host
* @param string $path
* @param array $parameters
* @param bool $json
*
* @return array|object
*/
private function http($method, $host, $path, array $parameters)
private function http($method, $host, $path, array $parameters, $json)
{
$this->resetLastResponse();
$this->resetAttemptsNumber();
$url = sprintf('%s/%s/%s.json', $host, self::API_VERSION, $path);
$this->response->setApiPath($path);
return $this->makeRequests($url, $method, $parameters);
return $this->makeRequests($url, $method, $parameters, $json);
}

/**
Expand All @@ -379,14 +381,15 @@ private function http($method, $host, $path, array $parameters)
* @param string $url
* @param string $method
* @param array $parameters
* @param bool $json
*
* @return array|object
*/
private function makeRequests($url, $method, array $parameters)
private function makeRequests($url, $method, array $parameters, $json)
{
do {
$this->sleepIfNeeded();
$result = $this->oAuthRequest($url, $method, $parameters);
$result = $this->oAuthRequest($url, $method, $parameters, $json);
$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
$this->response->setBody($response);
$this->attempts++;
Expand All @@ -412,13 +415,14 @@ private function requestsAvailable()
* @param string $url
* @param string $method
* @param array $parameters
* @param bool $json
*
* @return string
* @throws TwitterOAuthException
*/
private function oAuthRequest($url, $method, array $parameters)
private function oAuthRequest($url, $method, array $parameters, $json = false)
{
$request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters);
$request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters, $json);
if (array_key_exists('oauth_callback', $parameters)) {
// Twitter doesn't like oauth_callback as a parameter.
unset($parameters['oauth_callback']);
Expand All @@ -434,7 +438,7 @@ private function oAuthRequest($url, $method, array $parameters)
} else {
$authorization = 'Authorization: Bearer ' . $this->bearer;
}
return $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters);
return $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters, $json);
}

/**
Expand Down Expand Up @@ -481,11 +485,12 @@ private function curlOptions()
* @param string $method
* @param string $authorization
* @param array $postfields
* @param bool $json
*
* @return string
* @throws TwitterOAuthException
*/
private function request($url, $method, $authorization, array $postfields)
private function request($url, $method, $authorization, array $postfields, $json = false)
{
$options = $this->curlOptions();
$options[CURLOPT_URL] = $url;
Expand All @@ -496,7 +501,12 @@ private function request($url, $method, $authorization, array $postfields)
break;
case 'POST':
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields);
if ($json) {
$options[CURLOPT_HTTPHEADER][] = 'Content-type: application/json';
$options[CURLOPT_POSTFIELDS] = json_encode($postfields);
} else {
$options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields);
}
break;
case 'DELETE':
$options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
Expand Down
30 changes: 30 additions & 0 deletions tests/TwitterOAuthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class TwitterOAuthTest extends \PHPUnit_Framework_TestCase
protected function setUp()
{
$this->twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$this->userId = explode('-', ACCESS_TOKEN)[0];
}

public function testBuildClient()
Expand Down Expand Up @@ -185,6 +186,35 @@ public function testPostFavoritesDestroy()
$this->assertEquals(200, $this->twitter->getLastHttpCode());
}

public function testPostDirectMessagesEventsNew()
{
$data = [
'event' => [
'type' => 'message_create',
'message_create' => [
'target' => [
'recipient_id' => $this->userId
],
'message_data' => [
'text' => 'Hello World!'
]
]
]
];
$result = $this->twitter->post('direct_messages/events/new', $data, true);
$this->assertEquals(200, $this->twitter->getLastHttpCode());
return $result;
}

/**
* @depends testPostDirectMessagesEventsNew
*/
public function testDeleteDirectMessagesEventsDestroy($message)
{
$this->twitter->delete('direct_messages/events/destroy', ['id' => $message->event->id]);
$this->assertEquals(204, $this->twitter->getLastHttpCode());
}

public function testPostStatusesUpdateWithMedia()
{
$this->twitter->setTimeouts(60, 30);
Expand Down

0 comments on commit 01026d2

Please sign in to comment.