| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
namespace Wikimedia\Http; |
| 12 |
|
| 13 |
class HttpAcceptParser { |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public function parseAccept( $accept ): array { |
| 30 |
$accepts = explode( ',', $accept ); |
| 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] ); |
| 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; |
| 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 |
|
| 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 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
public function parseWeights( $rawHeader ) { |
| 98 |
|
| 99 |
$rawHeader = preg_replace( '/^[-\w]+:\s*/', '', $rawHeader ); |
| 100 |
|
| 101 |
|
| 102 |
$rawHeader = strtolower( $rawHeader ); |
| 103 |
|
| 104 |
$accepts = $this->parseAccept( $rawHeader ); |
| 105 |
|
| 106 |
|
| 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 |
} |