HttpHeaders.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace PicoFeed\Client;
  3. use ArrayAccess;
  4. use PicoFeed\Logging\Logger;
  5. /**
  6. * Class to handle HTTP headers case insensitivity.
  7. *
  8. * @author Bernhard Posselt
  9. * @author Frederic Guillot
  10. */
  11. class HttpHeaders implements ArrayAccess
  12. {
  13. private $headers = array();
  14. public function __construct(array $headers)
  15. {
  16. foreach ($headers as $key => $value) {
  17. $this->headers[strtolower($key)] = $value;
  18. }
  19. }
  20. public function offsetGet($offset)
  21. {
  22. return $this->offsetExists($offset) ? $this->headers[strtolower($offset)] : '';
  23. }
  24. public function offsetSet($offset, $value)
  25. {
  26. $this->headers[strtolower($offset)] = $value;
  27. }
  28. public function offsetExists($offset)
  29. {
  30. return isset($this->headers[strtolower($offset)]);
  31. }
  32. public function offsetUnset($offset)
  33. {
  34. unset($this->headers[strtolower($offset)]);
  35. }
  36. /**
  37. * Parse HTTP headers.
  38. *
  39. * @static
  40. *
  41. * @param array $lines List of headers
  42. *
  43. * @return array
  44. */
  45. public static function parse(array $lines)
  46. {
  47. $status = 0;
  48. $headers = array();
  49. foreach ($lines as $line) {
  50. if (strpos($line, 'HTTP/1') === 0) {
  51. $headers = array();
  52. $status = (int) substr($line, 9, 3);
  53. } elseif (strpos($line, ': ') !== false) {
  54. list($name, $value) = explode(': ', $line);
  55. if ($value) {
  56. $headers[trim($name)] = trim($value);
  57. }
  58. }
  59. }
  60. Logger::setMessage(get_called_class().' HTTP status code: '.$status);
  61. foreach ($headers as $name => $value) {
  62. Logger::setMessage(get_called_class().' HTTP header: '.$name.' => '.$value);
  63. }
  64. return array($status, new self($headers));
  65. }
  66. }