123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- class AcceptHeader extends \ArrayObject
- {
-
- public function __construct($header)
- {
- $acceptedTypes = $this->_parse($header);
- usort($acceptedTypes, [$this, '_compare']);
- parent::__construct($acceptedTypes);
- }
-
- private function _parse($data)
- {
- $array = [];
- $items = explode(',', $data);
- foreach ($items as $item) {
- $elems = explode(';', $item);
- $mime = current($elems);
- $types = explode('/', $mime);
- if (!isset($types[1])) {
- continue;
- }
- $acceptElement = [
- 'raw' => $mime,
- 'type' => trim($types[0]),
- 'subtype' => trim($types[1]),
- ];
- $acceptElement['params'] = [];
- while (next($elems)) {
- list($name, $value) = explode('=', current($elems));
- $acceptElement['params'][trim($name)] = trim($value);
- }
- $array[] = $acceptElement;
- }
- return $array;
- }
-
- private function _compare($a, $b)
- {
- $a_q = isset($a['params']['q']) ? floatval($a['params']['q']) : 1.0;
- $b_q = isset($b['params']['q']) ? floatval($b['params']['q']) : 1.0;
- if ($a_q === $b_q) {
- $a_count = count($a['params']);
- $b_count = count($b['params']);
- if ($a_count === $b_count) {
- if ($r = $this->_compareSubType($a['subtype'], $b['subtype'])) {
- return $r;
- } else {
- return $this->_compareSubType($a['type'], $b['type']);
- }
- } else {
- return $a_count < $b_count;
- }
- } else {
- return $a_q < $b_q;
- }
- }
-
- private function _compareSubType($a, $b)
- {
- if ($a === '*' && $b !== '*') {
- return 1;
- } elseif ($b === '*' && $a !== '*') {
- return -1;
- } else {
- return 0;
- }
- }
- }
|