/library/Google/vendor/google/auth/src/Subscriber/SimpleSubscriber.php

https://gitlab.com/vangtrangbac123/zinkaiuit.tk · PHP · 90 lines · 28 code · 7 blank · 55 comment · 3 complexity · 09dd6f36332a3f8c7ff4b61ab169d0c9 MD5 · raw file

  1. <?php
  2. /*
  3. * Copyright 2015 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\Auth\Subscriber;
  18. use GuzzleHttp\Event\BeforeEvent;
  19. use GuzzleHttp\Event\RequestEvents;
  20. use GuzzleHttp\Event\SubscriberInterface;
  21. /**
  22. * SimpleSubscriber is a Guzzle Subscriber that implements Google's Simple API
  23. * access.
  24. *
  25. * Requests are accessed using the Simple API access developer key.
  26. */
  27. class SimpleSubscriber implements SubscriberInterface
  28. {
  29. /**
  30. * @var array
  31. */
  32. private $config;
  33. /**
  34. * Create a new Simple plugin.
  35. *
  36. * The configuration array expects one option
  37. * - key: required, otherwise InvalidArgumentException is thrown
  38. *
  39. * @param array $config Configuration array
  40. */
  41. public function __construct(array $config)
  42. {
  43. if (!isset($config['key'])) {
  44. throw new \InvalidArgumentException('requires a key to have been set');
  45. }
  46. $this->config = array_merge([], $config);
  47. }
  48. /**
  49. * @return array
  50. */
  51. public function getEvents()
  52. {
  53. return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]];
  54. }
  55. /**
  56. * Updates the request query with the developer key if auth is set to simple.
  57. *
  58. * use Google\Auth\Subscriber\SimpleSubscriber;
  59. * use GuzzleHttp\Client;
  60. *
  61. * $my_key = 'is not the same as yours';
  62. * $subscriber = new SimpleSubscriber(['key' => $my_key]);
  63. *
  64. * $client = new Client([
  65. * 'base_url' => 'https://www.googleapis.com/discovery/v1/',
  66. * 'defaults' => ['auth' => 'simple']
  67. * ]);
  68. * $client->getEmitter()->attach($subscriber);
  69. *
  70. * $res = $client->get('drive/v2/rest');
  71. *
  72. * @param BeforeEvent $event
  73. */
  74. public function onBefore(BeforeEvent $event)
  75. {
  76. // Requests using "auth"="simple" with the developer key.
  77. $request = $event->getRequest();
  78. if ($request->getConfig()['auth'] != 'simple') {
  79. return;
  80. }
  81. $request->getQuery()->overwriteWith($this->config);
  82. }
  83. }