1: | <?php |
2: | |
3: | |
4: | |
5: | |
6: | |
7: | |
8: | |
9: | |
10: | |
11: | |
12: | |
13: | |
14: | |
15: | |
16: | |
17: | |
18: | |
19: | |
20: | |
21: | |
22: | |
23: | |
24: | |
25: | |
26: | |
27: | |
28: | namespace Ally\PetStore; |
29: | |
30: | use \Exception; |
31: | |
32: | |
33: | |
34: | |
35: | |
36: | |
37: | |
38: | |
39: | |
40: | class HeaderSelector |
41: | { |
42: | |
43: | |
44: | |
45: | |
46: | |
47: | public function selectHeaders($accept, $contentTypes) |
48: | { |
49: | $headers = []; |
50: | |
51: | $accept = $this->selectAcceptHeader($accept); |
52: | if ($accept !== null) { |
53: | $headers['Accept'] = $accept; |
54: | } |
55: | |
56: | $headers['Content-Type'] = $this->selectContentTypeHeader($contentTypes); |
57: | return $headers; |
58: | } |
59: | |
60: | |
61: | |
62: | |
63: | |
64: | public function selectHeadersForMultipart($accept) |
65: | { |
66: | $headers = $this->selectHeaders($accept, []); |
67: | |
68: | unset($headers['Content-Type']); |
69: | return $headers; |
70: | } |
71: | |
72: | |
73: | |
74: | |
75: | |
76: | |
77: | |
78: | |
79: | private function selectAcceptHeader($accept) |
80: | { |
81: | if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { |
82: | return null; |
83: | } elseif ($jsonAccept = preg_grep('~(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$~', $accept)) { |
84: | return implode(',', $jsonAccept); |
85: | } else { |
86: | return implode(',', $accept); |
87: | } |
88: | } |
89: | |
90: | |
91: | |
92: | |
93: | |
94: | |
95: | |
96: | |
97: | private function selectContentTypeHeader($contentType) |
98: | { |
99: | if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { |
100: | return 'application/json'; |
101: | } elseif (preg_grep("/application\/json/i", $contentType)) { |
102: | return 'application/json'; |
103: | } else { |
104: | return implode(',', $contentType); |
105: | } |
106: | } |
107: | } |
108: | |