Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/AcceptHeader.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 // Help opcache.preload discover always-needed symbols
15 class_exists(AcceptHeaderItem::class);
16
17 /**
18 * Represents an Accept-* header.
19 *
20 * An accept header is compound with a list of items,
21 * sorted by descending quality.
22 *
23 * @author Jean-François Simon <[email protected]>
24 */
25 class AcceptHeader
26 {
27 /**
28 * @var array<string, AcceptHeaderItem>
29 */
30 private array $items = [];
31
32 private bool $sorted = true;
33
34 /**
35 * @param AcceptHeaderItem[] $items
36 */
37 public function __construct(array $items)
38 {
39 foreach ($items as $item) {
40 $this->add($item);
41 }
42 }
43
44 /**
45 * Builds an AcceptHeader instance from a string.
46 */
47 public static function fromString(?string $headerValue): self
48 {
49 $items = [];
50 foreach (HeaderUtils::split($headerValue ?? '', ',;=') as $i => $parts) {
51 $part = array_shift($parts);
52 $item = new AcceptHeaderItem($part[0], HeaderUtils::combine($parts));
53
54 $items[] = $item->setIndex($i);
55 }
56
57 return new self($items);
58 }
59
60 /**
61 * Returns header value's string representation.
62 */
63 public function __toString(): string
64 {
65 return implode(',', $this->items);
66 }
67
68 /**
69 * Tests if header has given value.
70 */
71 public function has(string $value): bool
72 {
73 $canonicalKey = $this->getCanonicalKey(AcceptHeaderItem::fromString($value));
74
75 return isset($this->items[$canonicalKey]);
76 }
77
78 /**
79 * Returns given value's item, if exists.
80 */
81 public function get(string $value): ?AcceptHeaderItem
82 {
83 $queryItem = AcceptHeaderItem::fromString($value.';q=1');
84 $canonicalKey = $this->getCanonicalKey($queryItem);
85
86 if (isset($this->items[$canonicalKey])) {
87 return $this->items[$canonicalKey];
88 }
89
90 // Collect and filter matching candidates
91 if (!$candidates = array_filter($this->items, fn (AcceptHeaderItem $item) => $this->matches($item, $queryItem))) {
92 return null;
93 }
94
95 usort(
96 $candidates,
97 fn ($a, $b) => $this->getSpecificity($b, $queryItem) <=> $this->getSpecificity($a, $queryItem) // Descending specificity
98 ?: $b->getQuality() <=> $a->getQuality() // Descending quality
99 ?: $a->getIndex() <=> $b->getIndex() // Ascending index (stability)
100 );
101
102 return reset($candidates);
103 }
104
105 /**
106 * Adds an item.
107 *
108 * @return $this
109 */
110 public function add(AcceptHeaderItem $item): static
111 {
112 $this->items[$this->getCanonicalKey($item)] = $item;
113 $this->sorted = false;
114
115 return $this;
116 }
117
118 /**
119 * Returns all items.
120 *
121 * @return AcceptHeaderItem[]
122 */
123 public function all(): array
124 {
125 $this->sort();
126
127 return $this->items;
128 }
129
130 /**
131 * Filters items on their value using given regex.
132 */
133 public function filter(string $pattern): self
134 {
135 return new self(array_filter($this->items, static fn ($item) => preg_match($pattern, $item->getValue())));
136 }
137
138 /**
139 * Returns first item.
140 */
141 public function first(): ?AcceptHeaderItem
142 {
143 $this->sort();
144
145 return $this->items ? reset($this->items) : null;
146 }
147
148 /**
149 * Sorts items by descending quality.
150 */
151 private function sort(): void
152 {
153 if (!$this->sorted) {
154 uasort($this->items, static fn ($a, $b) => $b->getQuality() <=> $a->getQuality() ?: $a->getIndex() <=> $b->getIndex());
155
156 $this->sorted = true;
157 }
158 }
159
160 /**
161 * Generates the canonical key for storing/retrieving an item.
162 */
163 private function getCanonicalKey(AcceptHeaderItem $item): string
164 {
165 $parts = [];
166
167 // Normalize and sort attributes for consistent key generation
168 $attributes = $this->getMediaParams($item);
169 ksort($attributes);
170
171 foreach ($attributes as $name => $value) {
172 if (null === $value) {
173 $parts[] = $name; // Flag parameter (e.g., "flowed")
174 continue;
175 }
176
177 // Quote values containing spaces, commas, semicolons, or equals per RFC 9110
178 // This handles cases like 'format="value with space"' or similar.
179 $quotedValue = \is_string($value) && preg_match('/[\s;,=]/', $value) ? '"'.addcslashes($value, '"\\').'"' : $value;
180
181 $parts[] = $name.'='.$quotedValue;
182 }
183
184 return $item->getValue().($parts ? ';'.implode(';', $parts) : '');
185 }
186
187 /**
188 * Checks if a given header item (range) matches a queried item (value).
189 *
190 * @param AcceptHeaderItem $rangeItem The item from the Accept header (e.g., text/*;format=flowed)
191 * @param AcceptHeaderItem $queryItem The item being queried (e.g., text/plain;format=flowed;charset=utf-8)
192 */
193 private function matches(AcceptHeaderItem $rangeItem, AcceptHeaderItem $queryItem): bool
194 {
195 $rangeValue = strtolower($rangeItem->getValue());
196 $queryValue = strtolower($queryItem->getValue());
197
198 // Handle universal wildcard ranges
199 if ('*' === $rangeValue || '*/*' === $rangeValue) {
200 return $this->rangeParametersMatch($rangeItem, $queryItem);
201 }
202
203 // Queries for '*' only match wildcard ranges (handled above)
204 if ('*' === $queryValue) {
205 return false;
206 }
207
208 // Ensure media vs. non-media consistency
209 $isQueryMedia = str_contains($queryValue, '/');
210 $isRangeMedia = str_contains($rangeValue, '/');
211
212 if ($isQueryMedia !== $isRangeMedia) {
213 return false;
214 }
215
216 // Non-media: exact match only (wildcards handled above)
217 if (!$isQueryMedia) {
218 return $rangeValue === $queryValue && $this->rangeParametersMatch($rangeItem, $queryItem);
219 }
220
221 // Media type: type/subtype with wildcards
222 [$queryType, $querySubtype] = explode('/', $queryValue, 2);
223 [$rangeType, $rangeSubtype] = explode('/', $rangeValue, 2) + [1 => '*'];
224
225 if ('*' !== $rangeType && $rangeType !== $queryType) {
226 return false;
227 }
228
229 if ('*' !== $rangeSubtype && $rangeSubtype !== $querySubtype) {
230 return false;
231 }
232
233 // Parameters must match
234 return $this->rangeParametersMatch($rangeItem, $queryItem);
235 }
236
237 /**
238 * Checks if the parameters of a range item are satisfied by the query item.
239 *
240 * Parameters are case-insensitive; range params must be a subset of query params.
241 */
242 private function rangeParametersMatch(AcceptHeaderItem $rangeItem, AcceptHeaderItem $queryItem): bool
243 {
244 $queryAttributes = $this->getMediaParams($queryItem);
245 $rangeAttributes = $this->getMediaParams($rangeItem);
246
247 foreach ($rangeAttributes as $name => $rangeValue) {
248 if (!\array_key_exists($name, $queryAttributes)) {
249 return false; // Missing required param
250 }
251
252 $queryValue = $queryAttributes[$name];
253
254 if (null === $rangeValue) {
255 return null === $queryValue; // Both flags or neither
256 }
257
258 if (null === $queryValue || strtolower($queryValue) !== strtolower($rangeValue)) {
259 return false;
260 }
261 }
262
263 return true;
264 }
265
266 /**
267 * Calculates a specificity score for sorting: media precision + param count.
268 */
269 private function getSpecificity(AcceptHeaderItem $item, AcceptHeaderItem $queryItem): int
270 {
271 $rangeValue = strtolower($item->getValue());
272 $queryValue = strtolower($queryItem->getValue());
273
274 $paramCount = \count($this->getMediaParams($item));
275
276 $isQueryMedia = str_contains($queryValue, '/');
277 $isRangeMedia = str_contains($rangeValue, '/');
278
279 if (!$isQueryMedia && !$isRangeMedia) {
280 return ('*' !== $rangeValue ? 2000 : 1000) + $paramCount;
281 }
282
283 [$rangeType, $rangeSubtype] = explode('/', $rangeValue, 2) + [1 => '*'];
284
285 $specificity = match (true) {
286 '*' !== $rangeSubtype => 3000, // Exact subtype (text/plain)
287 '*' !== $rangeType => 2000, // Type wildcard (text/*)
288 default => 1000, // Full wildcard (*/* or *)
289 };
290
291 return $specificity + $paramCount;
292 }
293
294 /**
295 * Returns normalized attributes: keys lowercased, excluding 'q'.
296 */
297 private function getMediaParams(AcceptHeaderItem $item): array
298 {
299 $attributes = array_change_key_case($item->getAttributes(), \CASE_LOWER);
300 unset($attributes['q']);
301
302 return $attributes;
303 }
304 }