Provider.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace AlibabaCloud\Client\Credentials\Providers;
  3. use AlibabaCloud\Client\Clients\Client;
  4. /**
  5. * Class Provider
  6. *
  7. * @package AlibabaCloud\Client\Credentials\Providers
  8. */
  9. class Provider
  10. {
  11. /**
  12. * For TSC Duration Seconds
  13. */
  14. const DURATION_SECONDS = 3600;
  15. /**
  16. * @var array
  17. */
  18. protected static $credentialsCache = [];
  19. /**
  20. * Expiration time slot for temporary security credentials.
  21. *
  22. * @var int
  23. */
  24. protected $expirationSlot = 180;
  25. /**
  26. * @var Client
  27. */
  28. protected $client;
  29. /**
  30. * @var string
  31. */
  32. protected $error = 'Result contains no credentials';
  33. /**
  34. * CredentialTrait constructor.
  35. *
  36. * @param Client $client
  37. */
  38. public function __construct(Client $client)
  39. {
  40. $this->client = $client;
  41. }
  42. /**
  43. * Get the credentials from the cache in the validity period.
  44. *
  45. * @return array|null
  46. */
  47. public function getCredentialsInCache()
  48. {
  49. if (isset(self::$credentialsCache[$this->key()])) {
  50. $result = self::$credentialsCache[$this->key()];
  51. if (\strtotime($result['Expiration']) - \time() >= $this->expirationSlot) {
  52. return $result;
  53. }
  54. unset(self::$credentialsCache[$this->key()]);
  55. }
  56. return null;
  57. }
  58. /**
  59. * Get the toString of the credentials as the key.
  60. *
  61. * @return string
  62. */
  63. protected function key()
  64. {
  65. return (string)$this->client->getCredential();
  66. }
  67. /**
  68. * Cache credentials.
  69. *
  70. * @param array $credential
  71. */
  72. protected function cache(array $credential)
  73. {
  74. self::$credentialsCache[$this->key()] = $credential;
  75. }
  76. }