EndpointList.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Aws\EndpointDiscovery;
  3. class EndpointList
  4. {
  5. private $active;
  6. private $expired = [];
  7. public function __construct(array $endpoints)
  8. {
  9. $this->active = $endpoints;
  10. reset($this->active);
  11. }
  12. /**
  13. * Gets an active (unexpired) endpoint. Returns null if none found.
  14. *
  15. * @return null|string
  16. */
  17. public function getActive()
  18. {
  19. if (count($this->active) < 1) {
  20. return null;
  21. }
  22. while (time() > current($this->active)) {
  23. $key = key($this->active);
  24. $this->expired[$key] = current($this->active);
  25. $this->increment($this->active);
  26. unset($this->active[$key]);
  27. if (count($this->active) < 1) {
  28. return null;
  29. }
  30. }
  31. $active = key($this->active);
  32. $this->increment($this->active);
  33. return $active;
  34. }
  35. /**
  36. * Gets an active endpoint if possible, then an expired endpoint if possible.
  37. * Returns null if no endpoints found.
  38. *
  39. * @return null|string
  40. */
  41. public function getEndpoint()
  42. {
  43. if (!empty($active = $this->getActive())) {
  44. return $active;
  45. }
  46. return $this->getExpired();
  47. }
  48. /**
  49. * Removes an endpoint from both lists.
  50. *
  51. * @param string $key
  52. */
  53. public function remove($key)
  54. {
  55. unset($this->active[$key]);
  56. unset($this->expired[$key]);
  57. }
  58. /**
  59. * Get an expired endpoint. Returns null if none found.
  60. *
  61. * @return null|string
  62. */
  63. private function getExpired()
  64. {
  65. if (count($this->expired) < 1) {
  66. return null;
  67. }
  68. $expired = key($this->expired);
  69. $this->increment($this->expired);
  70. return $expired;
  71. }
  72. private function increment(&$array)
  73. {
  74. if (next($array) === false) {
  75. reset($array);
  76. }
  77. }
  78. }