MediaWiki REL1_41
HttpAcceptNegotiator.php
Go to the documentation of this file.
1<?php
2
3namespace Wikimedia\Http;
4
18
22 private $supportedValues;
23
27 private $defaultValue;
28
32 public function __construct( array $supported ) {
33 $this->supportedValues = $supported;
34 $this->defaultValue = reset( $supported );
35 }
36
53 public function getBestSupportedKey( array $weights, $default = null ) {
54 // Make sure we correctly bias against wildcards and ranges, see RFC2616, section 14.
55 foreach ( $weights as $name => &$weight ) {
56 if ( $name === '*' || $name === '*/*' ) {
57 $weight -= 0.000002;
58 } elseif ( substr( $name, -2 ) === '/*' ) {
59 $weight -= 0.000001;
60 }
61 }
62
63 // Sort $weights by value and...
64 asort( $weights );
65
66 // remove any keys with values equal to 0 or false (HTTP/1.1 section 3.9)
67 $weights = array_filter( $weights );
68
69 // ...use the ordered list of keys
70 $preferences = array_reverse( array_keys( $weights ) );
71
72 $value = $this->getFirstSupportedValue( $preferences, $default );
73 return $value;
74 }
75
89 public function getFirstSupportedValue( array $preferences, $default = null ) {
90 foreach ( $preferences as $value ) {
91 foreach ( $this->supportedValues as $supported ) {
92 if ( $this->valueMatches( $value, $supported ) ) {
93 return $supported;
94 }
95 }
96 }
97
98 return $default;
99 }
100
116 private function valueMatches( $accepted, $supported ) {
117 // RDF 2045: MIME types are case insensitive.
118 // full match
119 if ( strcasecmp( $accepted, $supported ) === 0 ) {
120 return true;
121 }
122
123 // wildcard match (HTTP/1.1 section 14.1, 14.2, 14.3)
124 if ( $accepted === '*' || $accepted === '*/*' ) {
125 return true;
126 }
127
128 // wildcard match (HTTP/1.1 section 14.1)
129 if ( substr( $accepted, -2 ) === '/*'
130 && strncasecmp( $accepted, $supported, strlen( $accepted ) - 2 ) === 0
131 ) {
132 return true;
133 }
134
135 return false;
136 }
137
138}
Utility for negotiating a value from a set of supported values using a preference list.
getFirstSupportedValue(array $preferences, $default=null)
Returns the first supported value from the given preference list.
getBestSupportedKey(array $weights, $default=null)
Returns the best supported key from the given weight map.
Utility for parsing a HTTP Accept header value into a weight map.