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 $kvArray = explode( '=', trim( $kv ), 2 );
44 if ( count( $kvArray ) != 2 ) {
45 continue;
46 }
47 [ $key, $val ] = $kvArray;
48 $key = strtolower( trim( $key ) );
49 $val = trim( $val );
50 if ( $key === 'q' ) {
51 $q = (float)$val; // FIXME: Spec is stricter about this
52 } else {
53 if ( $val && $val[0] === '"' && $val[ strlen( $val ) - 1 ] === '"' ) {
54 $val = substr( $val, 1, strlen( $val ) - 2 );
55 }
56 $params[$key] = $val;
57 }
58 }
59 }
60 $ret[] = [
61 'type' => $matches[1],
62 'subtype' => $matches[2],
63 'q' => $q,
64 'i' => $i,
65 'params' => $params,
66 ];
67 }
68
69 // Sort list. First by q values, then by order
70 usort( $ret, static function ( $a, $b ) {
71 if ( $b['q'] > $a['q'] ) {
72 return 1;
73 } elseif ( $b['q'] === $a['q'] ) {
74 return $a['i'] - $b['i'];
75 } else {
76 return -1;
77 }
78 } );
79
80 return $ret;
81 }
82
97 public function parseWeights( $rawHeader ) {
98 // first, strip header name
99 $rawHeader = preg_replace( '/^[-\w]+:\s*/', '', $rawHeader );
100
101 // Return values in lower case
102 $rawHeader = strtolower( $rawHeader );
103
104 $accepts = $this->parseAccept( $rawHeader );
105
106 // Create a list like "en" => 0.8
107 return array_reduce( $accepts, static function ( $prev, $next ) {
108 $type = "{$next['type']}/{$next['subtype']}";
109 $prev[$type] = $next['q'];
110 return $prev;
111 }, [] );
112 }
113
114}
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.