CaseInsensitiveArray.php 1.8 KB

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