1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\HttpFoundation;
13:
14: 15: 16: 17: 18: 19: 20: 21:
22: class
23: {
24: 25: 26:
27: private $items = array();
28:
29: 30: 31:
32: private $sorted = true;
33:
34: 35: 36: 37: 38:
39: public function __construct(array $items)
40: {
41: foreach ($items as $item) {
42: $this->add($item);
43: }
44: }
45:
46: 47: 48: 49: 50: 51: 52:
53: public static function fromString($headerValue)
54: {
55: $index = 0;
56:
57: return new self(array_map(function ($itemValue) use (&$index) {
58: $item = AcceptHeaderItem::fromString($itemValue);
59: $item->setIndex($index++);
60:
61: return $item;
62: }, preg_split('/\s*(?:,*("[^"]+"),*|,*(\'[^\']+\'),*|,+)\s*/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)));
63: }
64:
65: 66: 67: 68: 69:
70: public function __toString()
71: {
72: return implode(',', $this->items);
73: }
74:
75: 76: 77: 78: 79: 80: 81:
82: public function has($value)
83: {
84: return isset($this->items[$value]);
85: }
86:
87: 88: 89: 90: 91: 92: 93:
94: public function get($value)
95: {
96: return isset($this->items[$value]) ? $this->items[$value] : null;
97: }
98:
99: 100: 101: 102: 103: 104: 105:
106: public function add(AcceptHeaderItem $item)
107: {
108: $this->items[$item->getValue()] = $item;
109: $this->sorted = false;
110:
111: return $this;
112: }
113:
114: 115: 116: 117: 118:
119: public function all()
120: {
121: $this->sort();
122:
123: return $this->items;
124: }
125:
126: 127: 128: 129: 130: 131: 132:
133: public function filter($pattern)
134: {
135: return new self(array_filter($this->items, function (AcceptHeaderItem $item) use ($pattern) {
136: return preg_match($pattern, $item->getValue());
137: }));
138: }
139:
140: 141: 142: 143: 144:
145: public function first()
146: {
147: $this->sort();
148:
149: return !empty($this->items) ? reset($this->items) : null;
150: }
151:
152: 153: 154:
155: private function sort()
156: {
157: if (!$this->sorted) {
158: uasort($this->items, function ($a, $b) {
159: $qA = $a->getQuality();
160: $qB = $b->getQuality();
161:
162: if ($qA === $qB) {
163: return $a->getIndex() > $b->getIndex() ? 1 : -1;
164: }
165:
166: return $qA > $qB ? -1 : 1;
167: });
168:
169: $this->sorted = true;
170: }
171: }
172: }
173: