1: <?php
2:
3: namespace Guzzle\Parser\Message;
4:
5: 6: 7:
8: class MessageParser extends AbstractMessageParser
9: {
10: 11: 12:
13: public function parseRequest($message)
14: {
15: if (!$message) {
16: return false;
17: }
18:
19: $parts = $this->parseMessage($message);
20:
21:
22: if (isset($parts['start_line'][2])) {
23: $startParts = explode('/', $parts['start_line'][2]);
24: $protocol = strtoupper($startParts[0]);
25: $version = isset($startParts[1]) ? $startParts[1] : '1.1';
26: } else {
27: $protocol = 'HTTP';
28: $version = '1.1';
29: }
30:
31: $parsed = array(
32: 'method' => strtoupper($parts['start_line'][0]),
33: 'protocol' => $protocol,
34: 'version' => $version,
35: 'headers' => $parts['headers'],
36: 'body' => $parts['body']
37: );
38:
39: $parsed['request_url'] = $this->getUrlPartsFromMessage($parts['start_line'][1], $parsed);
40:
41: return $parsed;
42: }
43:
44: 45: 46:
47: public function parseResponse($message)
48: {
49: if (!$message) {
50: return false;
51: }
52:
53: $parts = $this->parseMessage($message);
54: list($protocol, $version) = explode('/', trim($parts['start_line'][0]));
55:
56: return array(
57: 'protocol' => $protocol,
58: 'version' => $version,
59: 'code' => $parts['start_line'][1],
60: 'reason_phrase' => isset($parts['start_line'][2]) ? $parts['start_line'][2] : '',
61: 'headers' => $parts['headers'],
62: 'body' => $parts['body']
63: );
64: }
65:
66: 67: 68: 69: 70: 71: 72:
73: protected function parseMessage($message)
74: {
75: $startLine = null;
76: $headers = array();
77: $body = '';
78:
79:
80: $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
81: for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) {
82:
83: $line = $lines[$i];
84:
85:
86: if (empty($line)) {
87: if ($i < $totalLines - 1) {
88: $body = implode('', array_slice($lines, $i + 2));
89: }
90: break;
91: }
92:
93:
94: if (!$startLine) {
95: $startLine = explode(' ', $line, 3);
96: } elseif (strpos($line, ':')) {
97: $parts = explode(':', $line, 2);
98: $key = trim($parts[0]);
99: $value = isset($parts[1]) ? trim($parts[1]) : '';
100: if (!isset($headers[$key])) {
101: $headers[$key] = $value;
102: } elseif (!is_array($headers[$key])) {
103: $headers[$key] = array($headers[$key], $value);
104: } else {
105: $headers[$key][] = $value;
106: }
107: }
108: }
109:
110: return array(
111: 'start_line' => $startLine,
112: 'headers' => $headers,
113: 'body' => $body
114: );
115: }
116: }
117: