Path: blob/master/src/aphront/headerparser/AphrontHTTPHeaderParser.php
12241 views
<?php12final class AphrontHTTPHeaderParser extends Phobject {34private $name;5private $content;6private $pairs;78public function parseRawHeader($raw_header) {9$this->name = null;10$this->content = null;1112$parts = explode(':', $raw_header, 2);13$this->name = trim($parts[0]);14if (count($parts) > 1) {15$this->content = trim($parts[1]);16}1718$this->pairs = null;1920return $this;21}2223public function getHeaderName() {24$this->requireParse();25return $this->name;26}2728public function getHeaderContent() {29$this->requireParse();30return $this->content;31}3233public function getHeaderContentAsPairs() {34$content = $this->getHeaderContent();353637$state = 'prekey';38$length = strlen($content);3940$pair_name = null;41$pair_value = null;4243$pairs = array();44$ii = 0;45while ($ii < $length) {46$c = $content[$ii];4748switch ($state) {49case 'prekey';50// We're eating space in front of a key.51if ($c == ' ') {52$ii++;53break;54}55$pair_name = '';56$state = 'key';57break;58case 'key';59// We're parsing a key name until we find "=" or ";".60if ($c == ';') {61$state = 'done';62break;63}6465if ($c == '=') {66$ii++;67$state = 'value';68break;69}7071$ii++;72$pair_name .= $c;73break;74case 'value':75// We found an "=", so now figure out if the value is quoted76// or not.77if ($c == '"') {78$ii++;79$state = 'quoted';80break;81}82$state = 'unquoted';83break;84case 'quoted':85// We're in a quoted string, parse until we find the closing quote.86if ($c == '"') {87$ii++;88$state = 'done';89break;90}9192$ii++;93$pair_value .= $c;94break;95case 'unquoted':96// We're in an unquoted string, parse until we find a space or a97// semicolon.98if ($c == ' ' || $c == ';') {99$state = 'done';100break;101}102$ii++;103$pair_value .= $c;104break;105case 'done':106// We parsed something, so eat any trailing whitespace and semicolons107// and look for a new value.108if ($c == ' ' || $c == ';') {109$ii++;110break;111}112113$pairs[] = array(114$pair_name,115$pair_value,116);117118$pair_name = null;119$pair_value = null;120121$state = 'prekey';122break;123}124}125126if ($state == 'quoted') {127throw new Exception(128pht(129'Header has unterminated double quote for key "%s".',130$pair_name));131}132133if ($pair_name !== null) {134$pairs[] = array(135$pair_name,136$pair_value,137);138}139140return $pairs;141}142143private function requireParse() {144if ($this->name === null) {145throw new PhutilInvalidStateException('parseRawHeader');146}147}148149}150151152