CaseInsensitiveArray.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. #[\ReturnTypeWillChange]
  21. public function count()
  22. {
  23. return \count($this->container);
  24. }
  25. #[\ReturnTypeWillChange]
  26. public function getIterator()
  27. {
  28. return new \ArrayIterator($this->container);
  29. }
  30. #[\ReturnTypeWillChange]
  31. public function offsetSet($offset, $value)
  32. {
  33. $offset = static::maybeLowercase($offset);
  34. if (null === $offset) {
  35. $this->container[] = $value;
  36. } else {
  37. $this->container[$offset] = $value;
  38. }
  39. }
  40. #[\ReturnTypeWillChange]
  41. public function offsetExists($offset)
  42. {
  43. $offset = static::maybeLowercase($offset);
  44. return isset($this->container[$offset]);
  45. }
  46. #[\ReturnTypeWillChange]
  47. public function offsetUnset($offset)
  48. {
  49. $offset = static::maybeLowercase($offset);
  50. unset($this->container[$offset]);
  51. }
  52. #[\ReturnTypeWillChange]
  53. public function offsetGet($offset)
  54. {
  55. $offset = static::maybeLowercase($offset);
  56. return isset($this->container[$offset]) ? $this->container[$offset] : null;
  57. }
  58. private static function maybeLowercase($v)
  59. {
  60. if (\is_string($v)) {
  61. return \strtolower($v);
  62. }
  63. return $v;
  64. }
  65. }