1 | <?php |
||
2 | |||
3 | /** |
||
4 | * @copyright (c) 2006-present brian ridley |
||
5 | * @author brian ridley <[email protected]> |
||
6 | * @license http://opensource.org/licenses/MIT MIT |
||
7 | */ |
||
8 | |||
9 | namespace ptlis\ConNeg\Preference\Builder; |
||
10 | |||
11 | use ptlis\ConNeg\Exception\InvalidVariantException; |
||
12 | use ptlis\ConNeg\Preference\Preference; |
||
13 | |||
14 | /** |
||
15 | * Shared preference builder (handles Charset, Encoding & Language). |
||
16 | */ |
||
17 | class PreferenceBuilder extends AbstractPreferenceBuilder |
||
18 | { |
||
19 | /** |
||
20 | * @inheritDoc |
||
21 | */ |
||
22 | 47 | protected function validateVariant($variant) |
|
23 | { |
||
24 | 47 | if ($this->isFromServer && '*' === $variant) { |
|
25 | 1 | throw new InvalidVariantException('Wildcards are not allowed in server-provided variants.'); |
|
26 | } |
||
27 | 46 | } |
|
28 | |||
29 | /** |
||
30 | * @inheritDoc |
||
31 | * |
||
32 | * @throws \RuntimeException if the HTTP field was not provided |
||
33 | */ |
||
34 | 60 | public function get() |
|
35 | { |
||
36 | 60 | if (is_null($this->fromField)) { |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
37 | 1 | throw new \RuntimeException( |
|
38 | 1 | 'The HTTP field must be provided to the builder.' |
|
39 | ); |
||
40 | } |
||
41 | |||
42 | 59 | return new Preference( |
|
43 | 59 | $this->variant, |
|
44 | 59 | $this->getQualityFactor(), |
|
45 | 59 | $this->getPrecedence() |
|
46 | ); |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * Get the variant's quality factor, defaulting to 0 on absent variant. |
||
51 | * |
||
52 | * @return float |
||
53 | */ |
||
54 | 59 | private function getQualityFactor() |
|
55 | { |
||
56 | 59 | $qFactor = 0.0; |
|
57 | |||
58 | 59 | if (strlen($this->variant)) { |
|
59 | 51 | $qFactor = $this->qFactor; |
|
60 | } |
||
61 | |||
62 | 59 | return $qFactor; |
|
63 | } |
||
64 | |||
65 | /** |
||
66 | * Determine the precedence from the variant. |
||
67 | * |
||
68 | * @return int |
||
69 | */ |
||
70 | 59 | private function getPrecedence() |
|
71 | { |
||
72 | 59 | $precedence = Preference::ABSENT; |
|
73 | |||
74 | // Wildcards |
||
75 | 59 | if ('*' === $this->variant) { |
|
76 | 13 | $precedence = Preference::WILDCARD; |
|
77 | |||
78 | // Special handling for Accept-Language field |
||
79 | 58 | } elseif (Preference::LANGUAGE === $this->fromField && '-*' === substr($this->variant, -2, 2)) { |
|
80 | 7 | $precedence = Preference::PARTIAL_WILDCARD; |
|
81 | |||
82 | // Full match |
||
83 | 58 | } elseif (strlen($this->variant)) { |
|
84 | 50 | $precedence = Preference::COMPLETE; |
|
85 | } |
||
86 | |||
87 | 59 | return $precedence; |
|
88 | } |
||
89 | } |
||
90 |