CaseInsensitiveDictionary.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Case-insensitive dictionary, suitable for HTTP headers
  4. *
  5. * @package Requests
  6. * @subpackage Utilities
  7. */
  8. /**
  9. * Case-insensitive dictionary, suitable for HTTP headers
  10. *
  11. * @package Requests
  12. * @subpackage Utilities
  13. */
  14. class Requests_Utility_CaseInsensitiveDictionary implements ArrayAccess, IteratorAggregate {
  15. /**
  16. * Actual item data
  17. *
  18. * @var array
  19. */
  20. protected $data = array();
  21. /**
  22. * Creates a case insensitive dictionary.
  23. *
  24. * @param array $data Dictionary/map to convert to case-insensitive
  25. */
  26. public function __construct(array $data = array()) {
  27. foreach ($data as $key => $value) {
  28. $this->offsetSet($key, $value);
  29. }
  30. }
  31. /**
  32. * Check if the given item exists
  33. *
  34. * @param string $key Item key
  35. * @return boolean Does the item exist?
  36. */
  37. public function offsetExists($key) {
  38. $key = strtolower($key);
  39. return isset($this->data[$key]);
  40. }
  41. /**
  42. * Get the value for the item
  43. *
  44. * @param string $key Item key
  45. * @return string Item value
  46. */
  47. public function offsetGet($key) {
  48. $key = strtolower($key);
  49. if (!isset($this->data[$key])) {
  50. return null;
  51. }
  52. return $this->data[$key];
  53. }
  54. /**
  55. * Set the given item
  56. *
  57. * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`)
  58. *
  59. * @param string $key Item name
  60. * @param string $value Item value
  61. */
  62. public function offsetSet($key, $value) {
  63. if ($key === null) {
  64. throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset');
  65. }
  66. $key = strtolower($key);
  67. $this->data[$key] = $value;
  68. }
  69. /**
  70. * Unset the given header
  71. *
  72. * @param string $key
  73. */
  74. public function offsetUnset($key) {
  75. unset($this->data[strtolower($key)]);
  76. }
  77. /**
  78. * Get an iterator for the data
  79. *
  80. * @return ArrayIterator
  81. */
  82. public function getIterator() {
  83. return new ArrayIterator($this->data);
  84. }
  85. /**
  86. * Get the headers as an array
  87. *
  88. * @return array Header data
  89. */
  90. public function getAll() {
  91. return $this->data;
  92. }
  93. }