Token.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace Aws\Token;
  3. use Aws\Identity\BearerTokenIdentity;
  4. use Aws\Token\TokenInterface;
  5. /**
  6. * Basic implementation of the AWS Token interface that allows callers to
  7. * pass in an AWS token in the constructor.
  8. */
  9. class Token extends BearerTokenIdentity implements TokenInterface, \Serializable
  10. {
  11. protected $token;
  12. protected $expires;
  13. /**
  14. * Constructs a new basic token object, with the specified AWS
  15. * token
  16. *
  17. * @param string $token Security token to use
  18. * @param int $expires UNIX timestamp for when the token expires
  19. */
  20. public function __construct($token, $expires = null)
  21. {
  22. $this->token = $token;
  23. $this->expires = $expires;
  24. }
  25. /**
  26. * Sets the state of a token object
  27. *
  28. * @param array $state array containing 'token' and 'expires'
  29. */
  30. public static function __set_state(array $state)
  31. {
  32. return new self(
  33. $state['token'],
  34. $state['expires']
  35. );
  36. }
  37. /**
  38. * @return string
  39. */
  40. public function getToken()
  41. {
  42. return $this->token;
  43. }
  44. /**
  45. * @return int
  46. */
  47. public function getExpiration()
  48. {
  49. return $this->expires;
  50. }
  51. /**
  52. * @return bool
  53. */
  54. public function isExpired()
  55. {
  56. return $this->expires !== null && time() >= $this->expires;
  57. }
  58. /**
  59. * @return array
  60. */
  61. public function toArray()
  62. {
  63. return [
  64. 'token' => $this->token,
  65. 'expires' => $this->expires
  66. ];
  67. }
  68. /**
  69. * @return string
  70. */
  71. public function serialize()
  72. {
  73. return json_encode($this->__serialize());
  74. }
  75. /**
  76. * Sets the state of the object from serialized json data
  77. */
  78. public function unserialize($serialized)
  79. {
  80. $data = json_decode($serialized, true);
  81. $this->__unserialize($data);
  82. }
  83. /**
  84. * @return array
  85. */
  86. public function __serialize()
  87. {
  88. return $this->toArray();
  89. }
  90. /**
  91. * Sets the state of this object from an array
  92. */
  93. public function __unserialize($data)
  94. {
  95. $this->token = $data['token'];
  96. $this->expires = $data['expires'];
  97. }
  98. }