/** * Populates headers from string representation * * Parses a string for headers, and aggregates them, in order, in the * current instance, primarily as strings until they are needed (they * will be lazy loaded) * * @param string $string * @param string $EOL EOL string; defaults to {@link EOL} * @throws Exception\RuntimeException * @return Headers */ public static function fromString($string, $EOL = self::EOL) { $headers = new static(); $currentLine = ''; // iterate the header lines, some might be continuations foreach (explode($EOL, $string) as $line) { // check if a header name is present if (preg_match('/^(?P<name>[\\x21-\\x39\\x3B-\\x7E]+):.*$/', $line, $matches)) { if ($currentLine) { // a header name was present, then store the current complete line $headers->addHeaderLine($currentLine); } $currentLine = trim($line); } elseif (preg_match('/^\\s+.*$/', $line, $matches)) { // continuation: append to current line $currentLine .= trim($line); } elseif (preg_match('/^\\s*$/', $line)) { // empty line indicates end of headers break; } else { // Line does not match header format! throw new Exception\RuntimeException(sprintf('Line "%s"does not match header format!', $line)); } } if ($currentLine) { $headers->addHeaderLine($currentLine); } return $headers; }
/** * Populates headers from string representation * * Parses a string for headers, and aggregates them, in order, in the * current instance, primarily as strings until they are needed (they * will be lazy loaded) * * @param string $string * @param string $EOL EOL string; defaults to {@link EOL} * @throws Exception\RuntimeException * @return Headers */ public static function fromString($string, $EOL = self::EOL) { $headers = new static(); $currentLine = ''; $emptyLine = 0; // iterate the header lines, some might be continuations $lines = explode($EOL, $string); $total = count($lines); for ($i = 0; $i < $total; $i += 1) { $line = $lines[$i]; // Empty line indicates end of headers // EXCEPT if there are more lines, in which case, there's a possible error condition if (preg_match('/^\\s*$/', $line)) { $emptyLine += 1; if ($emptyLine > 2) { throw new Exception\RuntimeException('Malformed header detected'); } continue; } if ($emptyLine > 0) { throw new Exception\RuntimeException('Malformed header detected'); } // check if a header name is present if (preg_match('/^[\\x21-\\x39\\x3B-\\x7E]+:.*$/', $line)) { if ($currentLine) { // a header name was present, then store the current complete line $headers->addHeaderLine($currentLine); } $currentLine = trim($line); continue; } // continuation: append to current line // recover the whitespace that break the line (unfolding, rfc2822#section-2.2.3) if (preg_match('/^\\s+.*$/', $line)) { $currentLine .= ' ' . trim($line); continue; } // Line does not match header format! throw new Exception\RuntimeException(sprintf('Line "%s" does not match header format!', $line)); } if ($currentLine) { $headers->addHeaderLine($currentLine); } return $headers; }