Skip to content

Commit f872fea

Browse files
committed
adds PSR-6 and removes custom caching (#943)
* adds PSR-6 and removes custom caching * Adds callback * documents these changes in the README
1 parent b8c815b commit f872fea

File tree

20 files changed

+190
-943
lines changed

20 files changed

+190
-943
lines changed

README.md

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ $ php -S localhost:8000 -t examples/
6262
And then browsing to the host and port you specified
6363
(in the above example, `http://localhost:8000`).
6464

65-
```PHP
65+
```php
6666
// include your composer dependencies
6767
require_once 'vendor/autoload.php';
6868

@@ -79,6 +79,33 @@ foreach ($results as $item) {
7979
}
8080
```
8181

82+
### Caching ###
83+
84+
It is recommended to use another caching library to improve performance. This can be done by passing a [PSR-6](http://www.php-fig.org/psr/psr-6/) compatible library to the client:
85+
86+
```php
87+
$cache = new Stash\Pool(new Stash\Driver\FileSystem);
88+
$client->setCache($cache);
89+
```
90+
91+
In this example we use [StashPHP](http://www.stashphp.com/). Add this to your project with composer:
92+
93+
```
94+
composer require tedivm/stash
95+
```
96+
97+
### Updating Tokens ###
98+
99+
When using [Refresh Tokens](https://developers.google.com/identity/protocols/OAuth2InstalledApp#refresh) or [Service Account Credentials](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#overview), it may be useful to perform some action when a new access token is granted. To do this, pass a callable to the `setTokenCallback` method on the client:
100+
101+
```php
102+
$logger = new Monolog\Logger;
103+
$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
104+
$logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
105+
};
106+
$client->setTokenCallback($tokenCallback);
107+
```
108+
82109
### Service Specific Examples ###
83110

84111
YouTube: https://github.com/youtube/api-samples/tree/master/php
@@ -87,9 +114,9 @@ YouTube: https://github.com/youtube/api-samples/tree/master/php
87114

88115
### What do I do if something isn't working? ###
89116

90-
For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: http://stackoverflow.com/questions/tagged/google-api-php-client
117+
For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: http://stackoverflow.com/questions/tagged/google-api-php-client
91118

92-
If there is a specific bug with the library, please file a issue in the Github issues tracker, including a (minimal) example of the failing code and any specific errors retrieved. Feature requests can also be filed, as long as they are core library requests, and not-API specific: for those, refer to the documentation for the individual APIs for the best place to file requests. Please try to provide a clear statement of the problem that the feature would address.
119+
If there is a specific bug with the library, please [file a issue](/Google/google-api-php-client/issues) in the Github issues tracker, including an example of the failing code and any specific errors retrieved. Feature requests can also be filed, as long as they are core library requests, and not-API specific: for those, refer to the documentation for the individual APIs for the best place to file requests. Please try to provide a clear statement of the problem that the feature would address.
93120

94121
### How do I contribute? ###
95122

composer.json

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,23 @@
77
"license": "Apache-2.0",
88
"require": {
99
"php": ">=5.4",
10-
"google/auth": "0.7",
10+
"google/auth": "0.8",
1111
"google/apiclient-services": "*@dev",
1212
"firebase/php-jwt": "~2.0|~3.0",
1313
"monolog/monolog": "^1.17",
1414
"phpseclib/phpseclib": "~2.0",
1515
"guzzlehttp/guzzle": "~5.2|~6.0",
16-
"guzzlehttp/psr7": "1.2.*",
17-
"psr/http-message": "1.0.*"
16+
"guzzlehttp/psr7": "^1.2"
1817
},
1918
"require-dev": {
2019
"phpunit/phpunit": "~4",
2120
"squizlabs/php_codesniffer": "~2.3",
22-
"symfony/dom-crawler": "~2.0",
23-
"symfony/css-selector": "~2.0"
21+
"symfony/dom-crawler": "~2.1",
22+
"symfony/css-selector": "~2.1",
23+
"tedivm/stash": "^0.14.1"
24+
},
25+
"suggest": {
26+
"tedivm/stash": "For caching certs and tokens (using Google_Client::setCache)"
2427
},
2528
"autoload": {
2629
"psr-0": {

src/Google/AccessToken/Verify.php

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@
1717
*/
1818

1919
use Firebase\JWT\ExpiredException as ExpiredExceptionV3;
20-
use Google\Auth\CacheInterface;
2120
use GuzzleHttp\Client;
2221
use GuzzleHttp\ClientInterface;
2322
use phpseclib\Crypt\RSA;
2423
use phpseclib\Math\BigInteger;
24+
use Psr\Cache\CacheItemPoolInterface;
25+
use Stash\Driver\FileSystem;
26+
use Stash\Pool;
2527

2628
/**
2729
* Wrapper around Google Access Tokens which provides convenience functions
@@ -39,20 +41,24 @@ class Google_AccessToken_Verify
3941
private $http;
4042

4143
/**
42-
* @var Google\Auth\CacheInterface cache class
44+
* @var Psr\Cache\CacheItemPoolInterface cache class
4345
*/
4446
private $cache;
4547

4648
/**
4749
* Instantiates the class, but does not initiate the login flow, leaving it
4850
* to the discretion of the caller.
4951
*/
50-
public function __construct(ClientInterface $http = null, CacheInterface $cache = null)
52+
public function __construct(ClientInterface $http = null, CacheItemPoolInterface $cache = null)
5153
{
5254
if (is_null($http)) {
5355
$http = new Client();
5456
}
5557

58+
if (is_null($cache) && class_exists('Stash\Pool')) {
59+
$cache = new Pool(new FileSystem);
60+
}
61+
5662
$this->http = $http;
5763
$this->cache = $cache;
5864
$this->jwt = $this->getJwtService();
@@ -120,20 +126,9 @@ public function verifyIdToken($idToken, $audience = null)
120126

121127
private function getCache()
122128
{
123-
if (!$this->cache) {
124-
$this->cache = $this->createDefaultCache();
125-
}
126-
127129
return $this->cache;
128130
}
129131

130-
private function createDefaultCache()
131-
{
132-
return new Google_Cache_File(
133-
sys_get_temp_dir().'/google-api-php-client'
134-
);
135-
}
136-
137132
/**
138133
* Retrieve and cache a certificates file.
139134
*
@@ -174,14 +169,22 @@ private function retrieveCertsFromLocation($url)
174169
// are PEM encoded certificates.
175170
private function getFederatedSignOnCerts()
176171
{
177-
$cache = $this->getCache();
172+
$certs = null;
173+
if ($cache = $this->getCache()) {
174+
$cacheItem = $cache->getItem('federated_signon_certs_v3', 3600);
175+
$certs = $cacheItem->get();
176+
}
178177

179-
if (!$certs = $cache->get('federated_signon_certs_v3', 3600)) {
178+
179+
if (!$certs) {
180180
$certs = $this->retrieveCertsFromLocation(
181181
self::FEDERATED_SIGNON_CERT_URL
182182
);
183183

184-
$cache->set('federated_signon_certs_v3', $certs);
184+
if ($cache) {
185+
$cacheItem->set($certs);
186+
$cache->save($cacheItem);
187+
}
185188
}
186189

187190
if (!isset($certs['keys'])) {
@@ -200,9 +203,11 @@ private function getJwtService()
200203
$jwtClass = 'Firebase\JWT\JWT';
201204
}
202205

203-
// adds 1 second to JWT leeway
204-
// @see https://github.com/google/google-api-php-client/issues/827
205-
$jwtClass::$leeway = 1;
206+
if (property_exists($jwtClass, 'leeway')) {
207+
// adds 1 second to JWT leeway
208+
// @see https://github.com/google/google-api-php-client/issues/827
209+
$jwtClass::$leeway = 1;
210+
}
206211

207212
return new $jwtClass;
208213
}

src/Google/AuthHandler/AuthHandlerFactory.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,15 @@ class Google_AuthHandler_AuthHandlerFactory
2626
* @return Google_AuthHandler_Guzzle5AuthHandler|Google_AuthHandler_Guzzle6AuthHandler
2727
* @throws Exception
2828
*/
29-
public static function build($cache = null)
29+
public static function build($cache = null, array $cacheConfig = [])
3030
{
3131
$version = ClientInterface::VERSION;
3232

3333
switch ($version[0]) {
3434
case '5':
35-
return new Google_AuthHandler_Guzzle5AuthHandler($cache);
35+
return new Google_AuthHandler_Guzzle5AuthHandler($cache, $cacheConfig);
3636
case '6':
37-
return new Google_AuthHandler_Guzzle6AuthHandler($cache);
37+
return new Google_AuthHandler_Guzzle6AuthHandler($cache, $cacheConfig);
3838
default:
3939
throw new Exception('Version not supported');
4040
}

src/Google/AuthHandler/Guzzle5AuthHandler.php

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,44 @@
11
<?php
22

3-
use Google\Auth\CacheInterface;
43
use Google\Auth\CredentialsLoader;
54
use Google\Auth\HttpHandler\HttpHandlerFactory;
65
use Google\Auth\Subscriber\AuthTokenSubscriber;
76
use Google\Auth\Subscriber\ScopedAccessTokenSubscriber;
87
use Google\Auth\Subscriber\SimpleSubscriber;
98
use GuzzleHttp\Client;
109
use GuzzleHttp\ClientInterface;
10+
use Psr\Cache\CacheItemPoolInterface;
1111

1212
/**
1313
*
1414
*/
1515
class Google_AuthHandler_Guzzle5AuthHandler
1616
{
1717
protected $cache;
18+
protected $cacheConfig;
1819

19-
public function __construct(CacheInterface $cache = null)
20+
public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
2021
{
2122
$this->cache = $cache;
23+
$this->cacheConfig = $cacheConfig;
2224
}
2325

24-
public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials)
25-
{
26+
public function attachCredentials(
27+
ClientInterface $http,
28+
CredentialsLoader $credentials,
29+
callable $tokenCallback = null
30+
) {
2631
// if we end up needing to make an HTTP request to retrieve credentials, we
2732
// can use our existing one, but we need to throw exceptions so the error
2833
// bubbles up.
2934
$authHttp = $this->createAuthHttp($http);
3035
$authHttpHandler = HttpHandlerFactory::build($authHttp);
3136
$subscriber = new AuthTokenSubscriber(
3237
$credentials,
33-
[],
38+
$this->cacheConfig,
3439
$this->cache,
35-
$authHttpHandler
40+
$authHttpHandler,
41+
$tokenCallback
3642
);
3743

3844
$http->setDefaultOption('auth', 'google_auth');

src/Google/AuthHandler/Guzzle6AuthHandler.php

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,44 @@
11
<?php
22

3-
use Google\Auth\CacheInterface;
43
use Google\Auth\CredentialsLoader;
54
use Google\Auth\HttpHandler\HttpHandlerFactory;
65
use Google\Auth\Middleware\AuthTokenMiddleware;
76
use Google\Auth\Middleware\ScopedAccessTokenMiddleware;
87
use Google\Auth\Middleware\SimpleMiddleware;
98
use GuzzleHttp\Client;
109
use GuzzleHttp\ClientInterface;
10+
use Psr\Cache\CacheItemPoolInterface;
1111

1212
/**
1313
*
1414
*/
1515
class Google_AuthHandler_Guzzle6AuthHandler
1616
{
1717
protected $cache;
18+
protected $cacheConfig;
1819

19-
public function __construct(CacheInterface $cache = null)
20+
public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
2021
{
2122
$this->cache = $cache;
23+
$this->cacheConfig = $cacheConfig;
2224
}
2325

24-
public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials)
25-
{
26+
public function attachCredentials(
27+
ClientInterface $http,
28+
CredentialsLoader $credentials,
29+
callable $tokenCallback = null
30+
) {
2631
// if we end up needing to make an HTTP request to retrieve credentials, we
2732
// can use our existing one, but we need to throw exceptions so the error
2833
// bubbles up.
2934
$authHttp = $this->createAuthHttp($http);
3035
$authHttpHandler = HttpHandlerFactory::build($authHttp);
3136
$middleware = new AuthTokenMiddleware(
3237
$credentials,
33-
[],
38+
$this->cacheConfig,
3439
$this->cache,
35-
$authHttpHandler
40+
$authHttpHandler,
41+
$tokenCallback
3642
);
3743

3844
$config = $http->getConfig();

0 commit comments

Comments
 (0)