MediaWiki REL1_39
HttpAcceptParser.php
Go to the documentation of this file.
1<?php
2
11namespace Wikimedia\Http;
12
14
29 public function parseAccept( $accept ): array {
30 $accepts = explode( ',', $accept ); // FIXME: Allow commas in quotes
31 $ret = [];
32
33 foreach ( $accepts as $i => $a ) {
34 if ( !preg_match( '!^([^\s/;]+)/([^;\s]+)\s*(?:;(.*))?$!D', trim( $a ), $matches ) ) {
35 continue;
36 }
37
38 $q = 1;
39 $params = [];
40 if ( isset( $matches[3] ) ) {
41 $kvps = explode( ';', $matches[3] ); // FIXME: Allow semi-colon in quotes
42 foreach ( $kvps as $kv ) {
43 [ $key, $val ] = explode( '=', trim( $kv ), 2 );
44 $key = strtolower( trim( $key ) );
45 $val = trim( $val );
46 if ( $key === 'q' ) {
47 $q = (float)$val; // FIXME: Spec is stricter about this
48 } else {
49 if ( $val && $val[0] === '"' && $val[ strlen( $val ) - 1 ] === '"' ) {
50 $val = substr( $val, 1, strlen( $val ) - 2 );
51 }
52 $params[$key] = $val;
53 }
54 }
55 }
56 $ret[] = [
57 'type' => $matches[1],
58 'subtype' => $matches[2],
59 'q' => $q,
60 'i' => $i,
61 'params' => $params,
62 ];
63 }
64
65 // Sort list. First by q values, then by order
66 usort( $ret, static function ( $a, $b ) {
67 if ( $b['q'] > $a['q'] ) {
68 return 1;
69 } elseif ( $b['q'] === $a['q'] ) {
70 return $a['i'] - $b['i'];
71 } else {
72 return -1;
73 }
74 } );
75
76 return $ret;
77 }
78
93 public function parseWeights( $rawHeader ) {
94 // first, strip header name
95 $rawHeader = preg_replace( '/^[-\w]+:\s*/', '', $rawHeader );
96
97 // Return values in lower case
98 $rawHeader = strtolower( $rawHeader );
99
100 $accepts = $this->parseAccept( $rawHeader );
101
102 // Create a list like "en" => 0.8
103 return array_reduce( $accepts, static function ( $prev, $next ) {
104 $type = "{$next['type']}/{$next['subtype']}";
105 $prev[$type] = $next['q'];
106 return $prev;
107 }, [] );
108 }
109
110}
parseAccept( $accept)
Parse media types from an Accept header and sort them by q-factor.
parseWeights( $rawHeader)
Parses an HTTP header into a weight map, that is an associative array mapping values to their respect...
Utility for parsing a HTTP Accept header value into a weight map.