1: <?php
2: namespace Worldline\Connect\Sdk\Communication;
3:
4: /**
5: * Class ConnectionResponse
6: *
7: * @package Worldline\Connect\Sdk\Communication
8: */
9: class ConnectionResponse
10: {
11: /**
12: * @var int
13: */
14: private int $httpStatusCode;
15:
16: /**
17: * @var array
18: */
19: private array $headers;
20:
21: /**
22: * @var array
23: */
24: private array $lowerCasedHeaderKeyMap;
25:
26: /**
27: * @var string
28: */
29: private string $body;
30:
31: /**
32: * @param int $httpStatusCode
33: * @param array $headers
34: * @param string $body
35: */
36: public function __construct(int $httpStatusCode, array $headers, string $body)
37: {
38: $this->httpStatusCode = $httpStatusCode;
39: $this->headers = $headers;
40: $this->lowerCasedHeaderKeyMap = array();
41: foreach (array_keys($headers) as $headerKey) {
42: $this->lowerCasedHeaderKeyMap[strtolower($headerKey)] = $headerKey;
43: }
44: $this->body = $body;
45: }
46:
47: /**
48: * @return int
49: */
50: public function getHttpStatusCode(): int
51: {
52: return $this->httpStatusCode;
53: }
54:
55: /**
56: * @return array
57: */
58: public function getHeaders(): array
59: {
60: return $this->headers;
61: }
62:
63: /**
64: * @param string $name
65: *
66: * @return string|array
67: */
68: public function getHeaderValue(string $name)
69: {
70: $lowerCasedName = strtolower($name);
71: if (array_key_exists($lowerCasedName, $this->lowerCasedHeaderKeyMap)) {
72: return $this->headers[$this->lowerCasedHeaderKeyMap[$lowerCasedName]];
73: }
74: return '';
75: }
76:
77: /**
78: * @return string
79: */
80: public function getBody(): string
81: {
82: return $this->body;
83: }
84:
85: /**
86: * @param array $headers
87: *
88: * @return string|null The value of the filename parameter of the Content-Disposition header from the given headers,
89: * or null if there was no such header or parameter.
90: */
91: public static function getDispositionFilename(array $headers): ?string
92: {
93: $headerValue = null;
94: foreach ($headers as $key => $value) {
95: if (strtolower($key) === 'content-disposition') {
96: $headerValue = $value;
97: break;
98: }
99: }
100: if (!$headerValue) {
101: return null;
102: }
103: if (preg_match('/(?i)(?:^|;)\s*fileName\s*=\s*(.*?)\s*(?:;|$)/', $headerValue, $matches)) {
104: $filename = $matches[1];
105: return self::trimQuotes($filename);
106: }
107: return null;
108: }
109:
110: private static function trimQuotes(string $filename): string
111: {
112: $len = strlen($filename);
113: if ($len < 2) {
114: return $filename;
115: }
116: if ((strrpos($filename, '"', -$len) === 0 && strpos($filename, '"', $len - 1) === $len - 1)
117: || (strrpos($filename, "'", -$len) === 0 && strpos($filename, "'", $len - 1) === $len - 1)
118: ) {
119: return substr($filename, 1, $len - 2);
120: }
121: return $filename;
122: }
123: }
124: