Header.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. final class Header
  5. {
  6. /**
  7. * Parse an array of header values containing ";" separated data into an
  8. * array of associative arrays representing the header key value pair data
  9. * of the header. When a parameter does not contain a value, but just
  10. * contains a key, this function will inject a key with a '' string value.
  11. *
  12. * @param string|array $header Header to parse into components.
  13. */
  14. public static function parse($header): array
  15. {
  16. static $trimmed = "\"' \n\t\r";
  17. $params = $matches = [];
  18. foreach (self::normalize($header) as $val) {
  19. $part = [];
  20. foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
  21. if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
  22. $m = $matches[0];
  23. if (isset($m[1])) {
  24. $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed);
  25. } else {
  26. $part[] = trim($m[0], $trimmed);
  27. }
  28. }
  29. }
  30. if ($part) {
  31. $params[] = $part;
  32. }
  33. }
  34. return $params;
  35. }
  36. /**
  37. * Converts an array of header values that may contain comma separated
  38. * headers into an array of headers with no comma separated values.
  39. *
  40. * @param string|array $header Header to normalize.
  41. */
  42. public static function normalize($header): array
  43. {
  44. if (!is_array($header)) {
  45. return array_map('trim', explode(',', $header));
  46. }
  47. $result = [];
  48. foreach ($header as $value) {
  49. foreach ((array) $value as $v) {
  50. if (strpos($v, ',') === false) {
  51. $result[] = $v;
  52. continue;
  53. }
  54. foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) {
  55. $result[] = trim($vv);
  56. }
  57. }
  58. }
  59. return $result;
  60. }
  61. }