00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00016 class HeaderParser
00017 {
00018 private $headers = array();
00019 private $currentHeader = null;
00020
00021 public static function create()
00022 {
00023 return new self;
00024 }
00025
00030 public function parse($data)
00031 {
00032 $lines = explode("\n", $data);
00033
00034 foreach ($lines as $line) {
00035 $this->doLine($line);
00036 }
00037
00038 return $this;
00039 }
00040
00041 public function doLine($line)
00042 {
00043 $line = trim($line, "\r\n");
00044 $matches = array();
00045
00046 if (preg_match("/^([\w-]+):\s+(.+)/", $line, $matches)) {
00047
00048 $name = strtolower($matches[1]);
00049 $value = $matches[2];
00050 $this->currentHeader = $name;
00051
00052 if (isset($this->headers[$name])) {
00053 if (!is_array($this->headers[$name])) {
00054 $this->headers[$name] = array($this->headers[$name]);
00055 }
00056 $this->headers[$name][] = $value;
00057 } else {
00058 $this->headers[$name] = $value;
00059 }
00060
00061 } elseif (
00062 preg_match("/^\s+(.+)$/", $line, $matches)
00063 && $this->currentHeader !== null
00064 ) {
00065 if (is_array($this->headers[$this->currentHeader])) {
00066 $lastKey = count($this->headers[$this->currentHeader]) - 1;
00067 $this->headers[$this->currentHeader][$lastKey]
00068 .= $matches[1];
00069 } else {
00070 $this->headers[$this->currentHeader] .= $matches[1];
00071 }
00072 }
00073
00074 return $this;
00075 }
00076
00080 public function getHeaders()
00081 {
00082 return $this->headers;
00083 }
00084
00085 public function hasHeader($name)
00086 {
00087 return isset($this->headers[strtolower($name)]);
00088 }
00089
00090 public function getHeader($name)
00091 {
00092 return $this->headers[strtolower($name)];
00093 }
00094 }
00095 ?>