Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing error handling and object conversion for array types #71

Merged
merged 5 commits into from
Jan 30, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/Google/Http/REST.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,13 @@ public static function decodeHttpResponse($response)
$err .= ": ($code) $body";
}

throw new Google_Service_Exception($err, $code, null, $decoded['error']['errors']);
$errors = null;
// Specific check for APIs which don't return error details, such as Blogger.
if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
$errors = $decoded['error']['errors'];
}

throw new Google_Service_Exception($err, $code, null, $errors);
}

// Only attempt to decode the response, if the response code wasn't (204) 'no content'
Expand Down
35 changes: 27 additions & 8 deletions src/Google/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,23 +113,42 @@ public function toSimpleObject()
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $member) {
$name = $member->getName();
if ($this->$name instanceof Google_Model) {
$object->$name = $this->$name->toSimpleObject();
} else if ($this->$name !== null) {
$object->$name = $this->$name;
$result = $this->getSimpleValue($this->$name);
if ($result != null) {
$object->$name = $result;
}
}

// Process all other data.
foreach ($this->data as $key => $val) {
if ($val instanceof Google_Model) {
$object->$key = $val->toSimpleObject();
} else if ($val !== null) {
$object->$key = $val;
$result = $this->getSimpleValue($val);
if ($result != null) {
$object->$key = $result;
}
}
return $object;
}

/**
* Handle different types of values, primarily
* other objects and map and array data types.
*/
private function getSimpleValue($value)
{
if ($value instanceof Google_Model) {
return $value->toSimpleObject();
} else if (is_array($value)) {
$return = array();
foreach ($value as $key => $a_value) {
$a_value = $this->getSimpleValue($a_value);
if ($a_value != null) {
$return[$key] = $a_value;
}
}
return $return;
}
return $value;
}

/**
* Returns true only if the array is associative.
Expand Down
2 changes: 2 additions & 0 deletions tests/AllTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@
require_once 'pagespeed/AllPageSpeedTests.php';
require_once 'urlshortener/AllUrlShortenerTests.php';
require_once 'plus/PlusTest.php';
require_once 'youtube/YouTubeTest.php';

class AllTests {
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite();
$suite->setName('All Google API PHP Client tests');
$suite->addTestSuite(YouTubeTests::suite());
$suite->addTestSuite(AllTasksTests::suite());
$suite->addTestSuite(AllPageSpeedTests::suite());
$suite->addTestSuite(AllUrlShortenerTests::suite());
Expand Down
4 changes: 3 additions & 1 deletion tests/OAuthHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@
"https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/urlshortener",
"https://www.googleapis.com/auth/tasks",
"https://www.googleapis.com/auth/adsense"
"https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/youtube"
));
$client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob");
$client->setAccessType("offline");
// Visit https://code.google.com/apis/console to
// generate your oauth2_client_id, oauth2_client_secret, and to
// register your oauth2_redirect_uri.
Expand Down
7 changes: 7 additions & 0 deletions tests/general/ApiModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,18 @@ public function testJsonStructure() {
$model2->publicC = 12345;
$model2->publicD = null;
$model->publicB = $model2;
$model3 = new Google_Model();
$model3->publicE = 54321;
$model3->publicF = null;
$model->publicG = array($model3, "hello");
$string = json_encode($model->toSimpleObject());
$data = json_decode($string, true);
$this->assertEquals(12345, $data['publicB']['publicC']);
$this->assertEquals("This is a string", $data['publicA']);
$this->assertArrayNotHasKey("publicD", $data['publicB']);
$this->assertArrayHasKey("publicE", $data['publicG'][0]);
$this->assertArrayNotHasKey("publicF", $data['publicG'][0]);
$this->assertEquals("hello", $data['publicG'][1]);
$this->assertArrayNotHasKey("data", $data);
}
}
40 changes: 40 additions & 0 deletions tests/general/RestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,45 @@ public function testCreateRequestUri() {
$value = $this->rest->createRequestUri($basePath, '/plus', $params);
$this->assertEquals("http://localhost/plus?u=%40me%2F", $value);
}

/**
* @expectedException Google_Service_Exception
*/
public function testBadErrorFormatting()
{
$request = new Google_Http_Request("/a/b");
$request->setResponseHttpCode(500);
$request->setResponseBody('{
"error": {
"code": 500,
"message": null
}
}');
Google_Http_Rest::decodeHttpResponse($request);
}

/**
* @expectedException Google_Service_Exception
*/
public function tesProperErrorFormatting()
{
$request = new Google_Http_Request("/a/b");
$request->setResponseHttpCode(401);
$request->setResponseBody('{
error: {
errors: [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}');
Google_Http_Rest::decodeHttpResponse($request);
}
}

84 changes: 84 additions & 0 deletions tests/youtube/YouTubeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

require_once 'Google/Service/YouTube.php';

class YouTubeTests extends PHPUnit_Framework_TestSuite {
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite();
$suite->setName('Google YouTube API tests');
$suite->addTestSuite('YouTubeTest');
return $suite;
}
}

class YouTubeTest extends BaseTest {
/** @var Google_PlusService */
public $plus;
public function __construct() {
parent::__construct();
$this->youtube = new Google_Service_YouTube($this->getClient());
}

public function testMissingFieldsAreNull() {
$parts = "id,brandingSettings";
$opts = array("mine" => true);
$channels = $this->youtube->channels->listChannels($parts, $opts);

$newChannel = new Google_Service_YouTube_Channel();
$newChannel->setId($channels[0]->getId());
$newChannel->setBrandingSettings($channels[0]->getBrandingSettings());

$simpleOriginal = $channels[0]->toSimpleObject();
$simpleNew = $newChannel->toSimpleObject();

$this->assertObjectHasAttribute('etag', $simpleOriginal);
$this->assertObjectNotHasAttribute('etag', $simpleNew);

$owner_details = new Google_Service_YouTube_ChannelContentOwnerDetails();
$owner_details->setTimeLinked("123456789");
$o_channel = new Google_Service_YouTube_Channel();
$o_channel->setContentOwnerDetails($owner_details);
$simpleManual = $o_channel->toSimpleObject();
$this->assertObjectHasAttribute('timeLinked', $simpleManual->contentOwnerDetails);
$this->assertObjectNotHasAttribute('contentOwner', $simpleManual->contentOwnerDetails);

$owner_details = new Google_Service_YouTube_ChannelContentOwnerDetails();
$owner_details->timeLinked = "123456789";
$o_channel = new Google_Service_YouTube_Channel();
$o_channel->setContentOwnerDetails($owner_details);
$simpleManual = $o_channel->toSimpleObject();
$this->assertObjectHasAttribute('timeLinked', $simpleManual->contentOwnerDetails);
$this->assertObjectNotHasAttribute('contentOwner', $simpleManual->contentOwnerDetails);

$owner_details = new Google_Service_YouTube_ChannelContentOwnerDetails();
$owner_details['timeLinked'] = "123456789";
$o_channel = new Google_Service_YouTube_Channel();
$o_channel->setContentOwnerDetails($owner_details);
$simpleManual = $o_channel->toSimpleObject();
$this->assertObjectHasAttribute('timeLinked', $simpleManual->contentOwnerDetails);
$this->assertObjectNotHasAttribute('contentOwner', $simpleManual->contentOwnerDetails);

$ping = new Google_Service_YouTube_ChannelConversionPing();
$ping->setContext("hello");
$pings = new Google_Service_YouTube_ChannelConversionPings();
$pings->setPings(array($ping));
$simplePings = $pings->toSimpleObject();
$this->assertObjectHasAttribute('context', $simplePings->pings[0]);
$this->assertObjectNotHasAttribute('conversionUrl', $simplePings->pings[0]);
}
}