Headers.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Case-insensitive dictionary, suitable for HTTP headers
  4. *
  5. * @package Requests
  6. */
  7. /**
  8. * Case-insensitive dictionary, suitable for HTTP headers
  9. *
  10. * @package Requests
  11. */
  12. class Requests_Response_Headers extends Requests_Utility_CaseInsensitiveDictionary {
  13. /**
  14. * Get the given header
  15. *
  16. * Unlike {@see self::getValues()}, this returns a string. If there are
  17. * multiple values, it concatenates them with a comma as per RFC2616.
  18. *
  19. * Avoid using this where commas may be used unquoted in values, such as
  20. * Set-Cookie headers.
  21. *
  22. * @param string $key
  23. * @return string Header value
  24. */
  25. public function offsetGet($key) {
  26. $key = strtolower($key);
  27. if (!isset($this->data[$key])) {
  28. return null;
  29. }
  30. return $this->flatten($this->data[$key]);
  31. }
  32. /**
  33. * Set the given item
  34. *
  35. * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`)
  36. *
  37. * @param string $key Item name
  38. * @param string $value Item value
  39. */
  40. public function offsetSet($key, $value) {
  41. if ($key === null) {
  42. throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset');
  43. }
  44. $key = strtolower($key);
  45. if (!isset($this->data[$key])) {
  46. $this->data[$key] = array();
  47. }
  48. $this->data[$key][] = $value;
  49. }
  50. /**
  51. * Get all values for a given header
  52. *
  53. * @param string $key
  54. * @return array Header values
  55. */
  56. public function getValues($key) {
  57. $key = strtolower($key);
  58. if (!isset($this->data[$key])) {
  59. return null;
  60. }
  61. return $this->data[$key];
  62. }
  63. /**
  64. * Flattens a value into a string
  65. *
  66. * Converts an array into a string by imploding values with a comma, as per
  67. * RFC2616's rules for folding headers.
  68. *
  69. * @param string|array $value Value to flatten
  70. * @return string Flattened value
  71. */
  72. public function flatten($value) {
  73. if (is_array($value)) {
  74. $value = implode(',', $value);
  75. }
  76. return $value;
  77. }
  78. /**
  79. * Get an iterator for the data
  80. *
  81. * Converts the internal
  82. * @return ArrayIterator
  83. */
  84. public function getIterator() {
  85. return new Requests_Utility_FilteredIterator($this->data, array($this, 'flatten'));
  86. }
  87. }