Nenhuma descrição

Guzzle5AuthHandler.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. use Google\Auth\CredentialsLoader;
  3. use Google\Auth\HttpHandler\HttpHandlerFactory;
  4. use Google\Auth\FetchAuthTokenCache;
  5. use Google\Auth\Subscriber\AuthTokenSubscriber;
  6. use Google\Auth\Subscriber\ScopedAccessTokenSubscriber;
  7. use Google\Auth\Subscriber\SimpleSubscriber;
  8. use GuzzleHttp\Client;
  9. use GuzzleHttp\ClientInterface;
  10. use Psr\Cache\CacheItemPoolInterface;
  11. /**
  12. *
  13. */
  14. class Google_AuthHandler_Guzzle5AuthHandler
  15. {
  16. protected $cache;
  17. protected $cacheConfig;
  18. public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
  19. {
  20. $this->cache = $cache;
  21. $this->cacheConfig = $cacheConfig;
  22. }
  23. public function attachCredentials(
  24. ClientInterface $http,
  25. CredentialsLoader $credentials,
  26. callable $tokenCallback = null
  27. ) {
  28. // use the provided cache
  29. if ($this->cache) {
  30. $credentials = new FetchAuthTokenCache(
  31. $credentials,
  32. $this->cacheConfig,
  33. $this->cache
  34. );
  35. }
  36. // if we end up needing to make an HTTP request to retrieve credentials, we
  37. // can use our existing one, but we need to throw exceptions so the error
  38. // bubbles up.
  39. $authHttp = $this->createAuthHttp($http);
  40. $authHttpHandler = HttpHandlerFactory::build($authHttp);
  41. $subscriber = new AuthTokenSubscriber(
  42. $credentials,
  43. $authHttpHandler,
  44. $tokenCallback
  45. );
  46. $http->setDefaultOption('auth', 'google_auth');
  47. $http->getEmitter()->attach($subscriber);
  48. return $http;
  49. }
  50. public function attachToken(ClientInterface $http, array $token, array $scopes)
  51. {
  52. $tokenFunc = function ($scopes) use ($token) {
  53. return $token['access_token'];
  54. };
  55. $subscriber = new ScopedAccessTokenSubscriber(
  56. $tokenFunc,
  57. $scopes,
  58. $this->cacheConfig,
  59. $this->cache
  60. );
  61. $http->setDefaultOption('auth', 'scoped');
  62. $http->getEmitter()->attach($subscriber);
  63. return $http;
  64. }
  65. public function attachKey(ClientInterface $http, $key)
  66. {
  67. $subscriber = new SimpleSubscriber(['key' => $key]);
  68. $http->setDefaultOption('auth', 'simple');
  69. $http->getEmitter()->attach($subscriber);
  70. return $http;
  71. }
  72. private function createAuthHttp(ClientInterface $http)
  73. {
  74. return new Client(
  75. [
  76. 'base_url' => $http->getBaseUrl(),
  77. 'defaults' => [
  78. 'exceptions' => true,
  79. 'verify' => $http->getDefaultOption('verify'),
  80. 'proxy' => $http->getDefaultOption('proxy'),
  81. ]
  82. ]
  83. );
  84. }
  85. }