Skip to content

Commit

Permalink
feat: allow array/null config constructors for services (#1929)
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer committed Sep 23, 2020
1 parent 9df720d commit 61517ef
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/Google/Service.php
Expand Up @@ -25,9 +25,22 @@ class Google_Service
public $resource;
private $client;

public function __construct(Google_Client $client)
/**
* @param Google_Client|array $clientOrConfig Optional
*/
public function __construct($clientOrConfig = [])
{
$this->client = $client;
if ($clientOrConfig instanceof Google_Client) {
$this->client = $clientOrConfig;
} elseif (is_array($clientOrConfig)) {
$this->client = new Google_Client($clientOrConfig ?: []);
} else {
$errorMessage = 'constructor must be array or instance of Google_Client';
if (class_exists('TypeError')) {
throw new TypeError($errorMessage);
}
trigger_error($errorMessage, E_USER_ERROR);
}
}

/**
Expand Down
56 changes: 56 additions & 0 deletions tests/Google/ServiceTest.php
Expand Up @@ -121,4 +121,60 @@ public function serviceProvider()

return $classes;
}

public function testConfigConstructor()
{
$clientId = 'test-client-id';
$service = new TestService(['client_id' => $clientId]);
$this->assertEquals($clientId, $service->getClient()->getClientId());
}

public function testNoConstructor()
{
$service = new TestService();
$this->assertInstanceOf('Google_Client', $service->getClient());
}

public function testInvalidConstructorPhp7Plus()
{
if (!class_exists('TypeError')) {
$this->markTestSkipped('PHP 7+ only');
}

try {
$service = new TestService('foo');
} catch (TypeError $e) {}

$this->assertInstanceOf('TypeError', $e);
$this->assertEquals(
'constructor must be array or instance of Google_Client',
$e->getMessage()
);
}

private static $errorMessage;

/** @runInSeparateProcess */
public function testInvalidConstructorPhp5()
{
if (class_exists('TypeError')) {
$this->markTestSkipped('PHP 5 only');
}

set_error_handler('Google_ServiceTest::handlePhp5Error');

$service = new TestService('foo');

$this->assertEquals(
'constructor must be array or instance of Google_Client',
self::$errorMessage
);
}

public static function handlePhp5Error($errno, $errstr, $errfile, $errline)
{
self::assertEquals(E_USER_ERROR, $errno);
self::$errorMessage = $errstr;
return true;
}
}

0 comments on commit 61517ef

Please sign in to comment.