UpdateMetadataTrait.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * Copyright 2023 Google LLC
  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;
  18. /**
  19. * Provides shared methods for updating request metadata (request headers).
  20. *
  21. * Should implement {@see UpdateMetadataInterface} and {@see FetchAuthTokenInterface}.
  22. *
  23. * @internal
  24. */
  25. trait UpdateMetadataTrait
  26. {
  27. /**
  28. * export a callback function which updates runtime metadata.
  29. *
  30. * @return callable updateMetadata function
  31. * @deprecated
  32. */
  33. public function getUpdateMetadataFunc()
  34. {
  35. return [$this, 'updateMetadata'];
  36. }
  37. /**
  38. * Updates metadata with the authorization token.
  39. *
  40. * @param array<mixed> $metadata metadata hashmap
  41. * @param string $authUri optional auth uri
  42. * @param callable $httpHandler callback which delivers psr7 request
  43. * @return array<mixed> updated metadata hashmap
  44. */
  45. public function updateMetadata(
  46. $metadata,
  47. $authUri = null,
  48. callable $httpHandler = null
  49. ) {
  50. if (isset($metadata[self::AUTH_METADATA_KEY])) {
  51. // Auth metadata has already been set
  52. return $metadata;
  53. }
  54. $result = $this->fetchAuthToken($httpHandler);
  55. $metadata_copy = $metadata;
  56. if (isset($result['access_token'])) {
  57. $metadata_copy[self::AUTH_METADATA_KEY] = ['Bearer ' . $result['access_token']];
  58. } elseif (isset($result['id_token'])) {
  59. $metadata_copy[self::AUTH_METADATA_KEY] = ['Bearer ' . $result['id_token']];
  60. }
  61. return $metadata_copy;
  62. }
  63. }