4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
15 * Represents an Accept-* header.
17 * An accept header is compound with a list of items,
18 * sorted by descending quality.
20 * @author Jean-François Simon <contact@jfsimon.fr>
25 * @var AcceptHeaderItem[]
27 private $items = array();
32 private $sorted = true;
37 * @param AcceptHeaderItem[] $items
39 public function __construct(array $items)
41 foreach ($items as $item) {
47 * Builds an AcceptHeader instance from a string.
49 * @param string $headerValue
53 public static function fromString($headerValue)
57 return new self(array_map(function ($itemValue) use (&$index) {
58 $item = AcceptHeaderItem::fromString($itemValue);
59 $item->setIndex($index++);
62 }, preg_split('/\s*(?:,*("[^"]+"),*|,*(\'[^\']+\'),*|,+)\s*/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)));
66 * Returns header value's string representation.
70 public function __toString()
72 return implode(',', $this->items);
76 * Tests if header has given value.
78 * @param string $value
82 public function has($value)
84 return isset($this->items[$value]);
88 * Returns given value's item, if exists.
90 * @param string $value
92 * @return AcceptHeaderItem|null
94 public function get($value)
96 return isset($this->items[$value]) ? $this->items[$value] : null;
102 * @param AcceptHeaderItem $item
106 public function add(AcceptHeaderItem $item)
108 $this->items[$item->getValue()] = $item;
109 $this->sorted = false;
117 * @return AcceptHeaderItem[]
119 public function all()
127 * Filters items on their value using given regex.
129 * @param string $pattern
133 public function filter($pattern)
135 return new self(array_filter($this->items, function (AcceptHeaderItem $item) use ($pattern) {
136 return preg_match($pattern, $item->getValue());
141 * Returns first item.
143 * @return AcceptHeaderItem|null
145 public function first()
149 return !empty($this->items) ? reset($this->items) : null;
153 * Sorts items by descending quality.
155 private function sort()
157 if (!$this->sorted) {
158 uasort($this->items, function ($a, $b) {
159 $qA = $a->getQuality();
160 $qB = $b->getQuality();
163 return $a->getIndex() > $b->getIndex() ? 1 : -1;
166 return $qA > $qB ? -1 : 1;
169 $this->sorted = true;