1: <?php
2:
3: namespace Httpful\Response;
4:
5: final class Headers implements \ArrayAccess, \Countable {
6:
7: private $headers;
8:
9: /**
10: * @param array $headers
11: */
12: private function __construct($headers)
13: {
14: $this->headers = $headers;
15: }
16:
17: /**
18: * @param string $string
19: * @return Headers
20: */
21: public static function fromString($string)
22: {
23: $lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY);
24: array_shift($lines); // HTTP HEADER
25: $headers = array();
26: foreach ($lines as $line) {
27: list($name, $value) = explode(':', $line, 2);
28: $headers[strtolower(trim($name))] = trim($value);
29: }
30: return new self($headers);
31: }
32:
33: /**
34: * @param string $offset
35: * @return bool
36: */
37: public function offsetExists($offset)
38: {
39: return isset($this->headers[strtolower($offset)]);
40: }
41:
42: /**
43: * @param string $offset
44: * @return mixed
45: */
46: public function offsetGet($offset)
47: {
48: if (isset($this->headers[$name = strtolower($offset)])) {
49: return $this->headers[$name];
50: }
51: }
52:
53: /**
54: * @param string $offset
55: * @param string $value
56: * @throws \Exception
57: */
58: public function offsetSet($offset, $value)
59: {
60: throw new \Exception("Headers are read-only.");
61: }
62:
63: /**
64: * @param string $offset
65: * @throws \Exception
66: */
67: public function offsetUnset($offset)
68: {
69: throw new \Exception("Headers are read-only.");
70: }
71:
72: /**
73: * @return int
74: */
75: public function count()
76: {
77: return count($this->headers);
78: }
79:
80: /**
81: * @return array
82: */
83: public function toArray()
84: {
85: return $this->headers;
86: }
87:
88: }