Header.php 2.1 KB

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