Header.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. $result = [];
  45. foreach ((array) $header as $value) {
  46. foreach ((array) $value as $v) {
  47. if (strpos($v, ',') === false) {
  48. $trimmed = trim($v);
  49. if ($trimmed !== '') {
  50. $result[] = $trimmed;
  51. }
  52. continue;
  53. }
  54. foreach (preg_split('/,(?=([^"]*"([^"]|\\\\.)*")*[^"]*$)/', $v) as $vv) {
  55. $trimmed = trim($vv);
  56. if ($trimmed !== '') {
  57. $result[] = $trimmed;
  58. }
  59. }
  60. }
  61. }
  62. return $result;
  63. }
  64. }