|
14 | 14 |
|
15 | 15 | use Hyperf\HttpMessage\Stream\SwooleStream; |
16 | 16 | use InvalidArgumentException; |
17 | | -use Laminas\Mime\Decode; |
18 | 17 | use Psr\Http\Message\StreamInterface; |
19 | 18 | use RuntimeException; |
20 | 19 | use Throwable; |
@@ -299,7 +298,7 @@ public function withBody(StreamInterface $body): static |
299 | 298 | */ |
300 | 299 | public function getHeaderField(string $name, string $wantedPart = '0', string $firstName = '0') |
301 | 300 | { |
302 | | - return Decode::splitHeaderField($this->getHeaderLine($name), $wantedPart, $firstName); |
| 301 | + return $this->splitHeaderField($this->getHeaderLine($name), $wantedPart, $firstName); |
303 | 302 | } |
304 | 303 |
|
305 | 304 | public function getContentType(): string |
@@ -447,4 +446,55 @@ private function trimHeaderValues(array $values): array |
447 | 446 | } |
448 | 447 | return $result; |
449 | 448 | } |
| 449 | + |
| 450 | + /** |
| 451 | + * split a header field like content type in its different parts. |
| 452 | + * |
| 453 | + * @param string $field header field |
| 454 | + * @param string $wantedPart the wanted part, else an array with all parts is returned |
| 455 | + * @param string $firstName key name for the first part |
| 456 | + * @return array|string wanted part or all parts as array($firstName => firstPart, partname => value) |
| 457 | + * @throws RuntimeException |
| 458 | + */ |
| 459 | + private function splitHeaderField(string $field, ?string $wantedPart = null, string $firstName = '0'): array|string |
| 460 | + { |
| 461 | + $wantedPart = strtolower($wantedPart ?? ''); |
| 462 | + $firstName = strtolower($firstName); |
| 463 | + |
| 464 | + // special case - a bit optimized |
| 465 | + if ($firstName === $wantedPart) { |
| 466 | + $field = strtok($field, ';'); |
| 467 | + return $field[0] === '"' ? substr($field, 1, -1) : $field; |
| 468 | + } |
| 469 | + |
| 470 | + $field = $firstName . '=' . $field; |
| 471 | + if (! preg_match_all('%([^=\s]+)\s*=\s*("[^"]+"|[^;]+)(;\s*|$)%', $field, $matches)) { |
| 472 | + throw new RuntimeException('not a valid header field'); |
| 473 | + } |
| 474 | + |
| 475 | + if ($wantedPart) { |
| 476 | + foreach ($matches[1] as $key => $name) { |
| 477 | + if (strcasecmp($name, $wantedPart)) { |
| 478 | + continue; |
| 479 | + } |
| 480 | + if ($matches[2][$key][0] !== '"') { |
| 481 | + return $matches[2][$key]; |
| 482 | + } |
| 483 | + return substr($matches[2][$key], 1, -1); |
| 484 | + } |
| 485 | + return ''; |
| 486 | + } |
| 487 | + |
| 488 | + $split = []; |
| 489 | + foreach ($matches[1] as $key => $name) { |
| 490 | + $name = strtolower($name); |
| 491 | + if ($matches[2][$key][0] === '"') { |
| 492 | + $split[$name] = substr($matches[2][$key], 1, -1); |
| 493 | + } else { |
| 494 | + $split[$name] = $matches[2][$key]; |
| 495 | + } |
| 496 | + } |
| 497 | + |
| 498 | + return $split; |
| 499 | + } |
450 | 500 | } |
0 commit comments