Completed
Push — master ( ebb03d...34ccd6 )
by Stefano
23:05
created

Negotiation::best()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 2
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 best($acceptables, $choices) {
31
    return (new self($acceptables))->match($choices);
32
  }
33
34
  public function __construct($query) {
35
    $this->list = self::parse(trim($query));
36
  }
37
38
  public function __toString(){
39
    return empty($this->list[0]) ? '' : $this->list[0];
40
  }
41
42
  public function match($choices){
43
    $_choices  = self::parse(trim($choices));
44
    foreach ($this->list as $accept){
45
      foreach ($_choices as $choice){
46
        if (preg_match('('.strtr($accept["type"],
47
          [ '.' => '\.', '+' => '\+', '*' => '.+' ]
48
        ).')', $choice["type"])){
49
          unset($choice['q']);     // Hide quality key from output
50
          $type = $choice['type']; // Extract type
51
          unset($choice['type']);
52
          return implode(';', array_merge([$type], array_map(function($k,$v){
53
            return "$k=$v";
54
          }, array_keys($choice), $choice)));
55
        }
56
      }
57
    }
58
    return false;
59
  }
60
61
} /* End of class */
62
63