1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Negotiation |
5
|
|
|
* |
6
|
|
|
* A module for handling Content Negotiation. |
7
|
|
|
* |
8
|
|
|
* @package core |
9
|
|
|
* @author [email protected] |
10
|
|
|
* @copyright Caffeina srl - 2016 - http://caffeina.com |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
class Negotiation { |
14
|
|
|
protected $list; |
15
|
|
|
|
16
|
|
|
public static function parse($query){ |
17
|
|
|
$list = new \SplPriorityQueue(); |
18
|
|
|
array_map(function($e) use ($list) { |
19
|
|
|
preg_match_all('(([^;]+)(?=\s*;\s*(\w+)\s*=\s*([^;]+))*)',$e,$p); |
20
|
|
|
$params = array_map('trim',array_merge( |
21
|
|
|
[ 'type' => current($p[0]) ], array_combine($p[2], $p[3])) |
22
|
|
|
); |
23
|
|
|
unset($params['']); |
24
|
|
|
$params['q'] = isset($params['q']) ? 1.0*$params['q'] : $params['q'] = 1.0; |
25
|
|
|
$list->insert($params, $params['q']); |
26
|
|
|
},preg_split('(\s*,\s*)', $query)); |
27
|
|
|
return array_values(iterator_to_array($list)); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function bestMatch($acceptables, $choices) { |
31
|
|
|
return (new self($acceptables))->best($choices); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function __construct($query) { |
35
|
|
|
$this->list = self::parse(trim($query)); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function preferred(){ |
39
|
|
|
return self::encodeParsedValue(current($this->list)); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
protected static function encodeParsedValue($parsed){ |
43
|
|
|
unset($parsed['q']); // Hide quality key from output |
44
|
|
|
$type = $parsed['type']; // Extract type |
45
|
|
|
unset($parsed['type']); |
46
|
|
|
return implode(';', array_merge([$type], array_map(function($k,$v){ |
47
|
|
|
return "$k=$v"; |
48
|
|
|
}, array_keys($parsed), $parsed))); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function best($choices){ |
52
|
|
|
$_choices = self::parse(trim($choices)); |
53
|
|
|
foreach ($this->list as $accept){ |
54
|
|
|
foreach ($_choices as $choice){ |
55
|
|
|
if (preg_match('('.strtr($accept["type"], |
56
|
|
|
[ '.' => '\.', '+' => '\+', '*' => '.+' ] |
57
|
|
|
).')', $choice["type"])){ |
58
|
|
|
return self::encodeParsedValue($choice); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
return false; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
} /* End of class */ |
66
|
|
|
|
67
|
|
|
|