CaseInsensitiveArray.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Stripe\Util;
  3. /**
  4. * CaseInsensitiveArray is an array-like class that ignores case for keys.
  5. *
  6. * It is used to store HTTP headers. Per RFC 2616, section 4.2:
  7. * Each header field consists of a name followed by a colon (":") and the field value. Field names
  8. * are case-insensitive.
  9. *
  10. * In the context of stripe-php, this is useful because the API will return headers with different
  11. * case depending on whether HTTP/2 is used or not (with HTTP/2, headers are always in lowercase).
  12. */
  13. class CaseInsensitiveArray implements \ArrayAccess, \Countable, \IteratorAggregate
  14. {
  15. private $container = [];
  16. public function __construct($initial_array = [])
  17. {
  18. $this->container = \array_change_key_case($initial_array, \CASE_LOWER);
  19. }
  20. /**
  21. * @return int
  22. */
  23. #[\ReturnTypeWillChange]
  24. public function count()
  25. {
  26. return \count($this->container);
  27. }
  28. /**
  29. * @return \ArrayIterator
  30. */
  31. #[\ReturnTypeWillChange]
  32. public function getIterator()
  33. {
  34. return new \ArrayIterator($this->container);
  35. }
  36. /**
  37. * @return void
  38. */
  39. #[\ReturnTypeWillChange]
  40. public function offsetSet($offset, $value)
  41. {
  42. $offset = self::maybeLowercase($offset);
  43. if (null === $offset) {
  44. $this->container[] = $value;
  45. } else {
  46. $this->container[$offset] = $value;
  47. }
  48. }
  49. /**
  50. * @return bool
  51. */
  52. #[\ReturnTypeWillChange]
  53. public function offsetExists($offset)
  54. {
  55. $offset = self::maybeLowercase($offset);
  56. return isset($this->container[$offset]);
  57. }
  58. /**
  59. * @return void
  60. */
  61. #[\ReturnTypeWillChange]
  62. public function offsetUnset($offset)
  63. {
  64. $offset = self::maybeLowercase($offset);
  65. unset($this->container[$offset]);
  66. }
  67. /**
  68. * @return mixed
  69. */
  70. #[\ReturnTypeWillChange]
  71. public function offsetGet($offset)
  72. {
  73. $offset = self::maybeLowercase($offset);
  74. return isset($this->container[$offset]) ? $this->container[$offset] : null;
  75. }
  76. private static function maybeLowercase($v)
  77. {
  78. if (\is_string($v)) {
  79. return \strtolower($v);
  80. }
  81. return $v;
  82. }
  83. }