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