1: <?php
2: namespace Worldline\Connect\Sdk\Communication;
3:
4: /**
5: * Class HttpHeaderHelper
6: *
7: * @package Worldline\Connect\Sdk\Communication
8: */
9: class HttpHeaderHelper
10: {
11: private function __construct()
12: {
13: }
14:
15: /**
16: * Parses a raw array of HTTP headers into an associative array with the same structure as the output
17: * of the get_headers method using the $format = 1 parameter
18: *
19: * @param string[] $rawHeaders
20: *
21: * @return array
22: */
23: public static function parseRawHeaders(array $rawHeaders): array
24: {
25: $headers = array();
26: $key = '';
27: foreach ($rawHeaders as $rawHeader) {
28: $rawHeaderLineParts = explode(':', $rawHeader, 2);
29: if (isset($rawHeaderLineParts[1])) {
30: $key = $rawHeaderLineParts[0];
31: $value = trim($rawHeaderLineParts[1]);
32: if (!isset($headers[$key])) {
33: $headers[$key] = $value;
34: } elseif (is_array($headers[$key])) {
35: $headers[$key][] = $value;
36: } else {
37: $headers[$key] = array($headers[$key], $value);
38: }
39: } elseif (strlen($rawHeaderLineParts[0]) > 0) {
40: if (!$key) {
41: $headers[0] = trim($rawHeaderLineParts[0]);
42: } elseif (in_array(substr($rawHeaderLineParts[0], 0, 1), array(' ', "\t"))) {
43: if (is_array($headers[$key])) {
44: $lastValue = array_pop($headers[$key]);
45: $headers[$key][] = $lastValue . "\r\n" . rtrim($rawHeaderLineParts[0]);
46: } else {
47: $headers[$key] .= "\r\n" . rtrim($rawHeaderLineParts[0]);
48: }
49: }
50: }
51: }
52: return $headers;
53: }
54:
55: /**
56: * Generates an array of raw headers from an associative array of headers with the same structure as the output
57: * of the get_headers method using the $format = 1 parameter
58: *
59: * @param array $headers
60: *
61: * @return string[]
62: */
63: public static function generateRawHeaders(array $headers): array
64: {
65: $rawHeaders = array();
66: foreach ($headers as $key => $values) {
67: if (!is_array($values)) {
68: $values = array($values);
69: }
70: foreach ($values as $value) {
71: if ($key !== 0) {
72: $rawHeader = $key . ': ' . $value;
73: } else {
74: $rawHeader = $value;
75: }
76: foreach (explode("\r\n", $rawHeader) as $singleLineRawHeader) {
77: $rawHeaders[] = $singleLineRawHeader;
78: }
79: }
80: }
81: return $rawHeaders;
82: }
83: }
84: