/src/Carica/Io/Network/Http/Headers.php

https://bitbucket.org/tobmaster/carica-io · PHP · 66 lines · 54 code · 12 blank · 0 comment · 8 complexity · 272dfd89b2dcce807f7914d9c712417d MD5 · raw file

  1. <?php
  2. namespace Carica\Io\Network\Http {
  3. use Carica\Io;
  4. class Headers implements \IteratorAggregate, \Countable, \ArrayAccess {
  5. private $_headers = array();
  6. public function count() {
  7. return count($this->_headers);
  8. }
  9. public function getIterator() {
  10. return new \ArrayIterator($this->_headers);
  11. }
  12. public function offsetExists($name) {
  13. return array_key_exists($this->prepareKey($name, TRUE), $this->_headers);
  14. }
  15. public function offsetGet($name) {
  16. return $this->_headers[$this->prepareKey($name)];
  17. }
  18. public function offsetSet($name, $value) {
  19. if (!$value instanceOf Header) {
  20. if (FALSE != strpos($value, ':')) {
  21. list($name, $value) = explode(':', $value, 2);
  22. }
  23. }
  24. if ($value instanceOf Header) {
  25. $name = $value->name;
  26. }
  27. $key = $this->prepareKey($name);
  28. if (isset($this->_headers[$key])) {
  29. $this->_headers[$key]->values[] = $value;
  30. } elseif ($value instanceOf Header) {
  31. $this->_headers[$key] = $value;
  32. } else {
  33. $this->_headers[$key] = new Header($name, $value);
  34. }
  35. }
  36. public function offsetUnset($name) {
  37. unset($this->_headers[$this->prepareKey($name)]);
  38. }
  39. private function prepareKey($name, $silent = FALSE) {
  40. $name = trim($name);
  41. if (empty($name)) {
  42. throw new \InvalidArgumentException('The header name can not be empty.');
  43. }
  44. if (!preg_match('(^[a-z][a-z\d]*(?:-[a-z\d]+)*$)iD', $name)) {
  45. throw new \InvalidArgumentException(
  46. sprintf(
  47. 'The header name "%s" is invalid.', $name
  48. )
  49. );
  50. }
  51. return strToLower($name);
  52. }
  53. }
  54. }