Parses Accept header

@param string $accept Accept header

@return float[] With 'type' => priority
Keys may contain '*'
11082
public static function parseAccept(string $accept)
    {
        $result = [];

        foreach (explode(',', $accept) as $directive) {
            $parts = explode(';', $directive, 2);

            $type = trim($parts[0]);

            $priority = ((float) filter_var(
                $parts[1] ?? 1,
                FILTER_SANITIZE_NUMBER_FLOAT,
                FILTER_FLAG_ALLOW_FRACTION
            ));
            $priority = Utils::numberLimit($priority, 0, 1);

            if (strpos($type, '*') !== false) {
                $priority -= 0.0001;
            }
            $result[$type] = $priority;
        }

        return $result;
    }
661176
public static function determineAcceptedMediaTypes(RequestInterface $request): array
    {
        $rawValues = $request->getHeader('Accept');
        if (empty($rawValues) || !is_string($rawValues)) {
            return ['*/*'];
        }
        $acceptedMediaTypes = self::parseContentNegotiationQualityValues($rawValues);

        return $acceptedMediaTypes;
    }
29662
private function parseHeader(string $header)
    {
        if (strpos($header, 'Basic') !== 0) {
            return false;
        }

        $header = base64_decode(substr($header, 6));

        if ($header === false) {
            return false;
        }

        $header = explode(':', $header, 2);

        return [
            'username' => $header[0],
            'password' => isset($header[1]) ? $header[1] : null,
        ];
    }
597773
public static function parse($headers)
    {
        if (is_string($headers)) {
            $headers = explode("\r\n\r\n", trim($headers));

            return explode("\r\n", end($headers));
        }

        $parsedHeaders = [];

        foreach ($headers as $name => $value) {
            $value = HeadersNormalizer::normalizeHeaderValue($value);

            if (is_int($name)) {
                if (strpos($value, 'HTTP/') === 0) {
                    $parsedHeaders = [$value];
                } else {
                    $parsedHeaders[] = $value;
                }
            } else {
                $parsedHeaders[] = $name.': '.$value;
            }
        }

        return $parsedHeaders;
    }
575819
public function parseHeader($header)
    {
        $header = rtrim($header, "\r\n");
        $pieces = preg_split('@\s*[;,]\s*@', $header);
        $cookies = array();

        foreach ($pieces as $cookie) {
            $cookie = explode('=', $cookie, 2);

            if (count($cookie) === 2) {
                $key = urldecode($cookie[0]);
                $value = urldecode($cookie[1]);

                if (!isset($cookies[$key])) {
                    $cookies[$key] = $value;
                }
            }
        }

        return $cookies;
    }
299049
protected static function _parseAccept($accept, array $defaults = null)
    {
        if (! empty($accept)) {
            // Get all of the types
            $types = explode(',', $accept);

            foreach ($types as $type) {
                // Split the type into parts
                $parts = explode(';', $type);

                // Make the type only the MIME
                $type = trim(array_shift($parts));

                // Default quality is 1.0
                $options = array('quality' => 1.0);

                foreach ($parts as $part) {
                    // Prevent undefined $value notice below
                    if (strpos($part, '=') === false) {
                        continue;
                    }

                    // Separate the key and value
                    list($key, $value) = explode('=', trim($part));

                    switch ($key) {
                        case 'q':
                            $options['quality'] = (float) trim($value);
                            break;
                        case 'version':
                            $options['version'] = (float) trim($value);
                            break;
                    }
                }

                // Add the accept type and quality
                $defaults[$type] = $options;
            }
        }

        // Make sure that accepts is an array
        $accepts = (array) $defaults;

        // Order by quality
        arsort($accepts);

        return $accepts;
    }
582302
public static function parseHeaderValue(string $value): array
    {
        $parts = \explode(';', $value);
        $type = \trim($parts[0]);
        unset($parts[0]);

        $parameters = [];
        foreach ($parts as $part) {
            [$k, $v] = \explode('=', $part, 2);

            $key = \strtolower(\trim($k));
            $parameters[$key] = \trim($v, ' "');
        }

        return [$type, $parameters];
    }
502725
def get_accept_list(self, request):
        
        header = request.META.get('HTTP_ACCEPT', '*/*')
        return [token.strip() for token in header.split(',')]
916067
function getHttpAccept()
    {
        if ( isset( $_GET[$this->FormatVar] ) )
        {
            return $_GET[$this->FormatVar];
        }
        else
        {
            if ( isset( $_POST['http_accept'] ) )
                $acceptList = explode( ',', $_POST['http_accept'] );
            else if ( isset( $_POST['HTTP_ACCEPT'] ) )
                $acceptList = explode( ',', $_POST['HTTP_ACCEPT'] );
            else if ( isset( $_GET['http_accept'] ) )
                $acceptList = explode( ',', $_GET['http_accept'] );
            else if ( isset( $_GET['HTTP_ACCEPT'] ) )
                $acceptList = explode( ',', $_GET['HTTP_ACCEPT'] );
            else if ( isset( $_SERVER['HTTP_ACCEPT'] ) )
                $acceptList = explode( ',', $_SERVER['HTTP_ACCEPT'] );
            else
                $acceptList = false;

            if ( !$acceptList ) // works for false && for empty arrays too
            {
                return '';
            }

            $weightedList = array();
            foreach( $acceptList as $accept )
            {
                if ( preg_match( '/; *q *= *([0-9.]+) *$/', $accept, $matches ) )
                {
                    $accept = explode( ';', $accept );
                    $accept = trim( $accept[0] );
                    $weightedList[$accept] = (float)$matches[1];
                }
                else
                {
                    $weightedList[$accept] = 1.0;
                }
            }
            arsort( $weightedList );
            $weightedList = array_keys( $weightedList );

            // try first we the types that responses can serialize to
            /// @todo add txt, html, php, phps to the list - be loyal to other class methods
            $aliasList = array( 'json' => 'application/json', 'javascript' => 'application/json', /*'xml' => 'text/xml', 'html' => 'text/xhtml', 'text' => 'text'*/ );
            foreach( $weightedList as $accept )
            {
                if ( $accept == '*/*' )
                {
                    return reset( $aliasList );
                }
                foreach( $aliasList as $alias => $returnType )
                {
                    if ( strpos( $accept, $alias ) !== false )
                    {
                        return $returnType;
                    }
                }
            }

            // request said what it wants, but we cannot give it back as it is not supported by response
            return $weightedList[0];
        }
    }
1360931
protected function getAcceptHeader(Request $request): Accept
	{
		$headerName = 'Accept';
		$headerLine = '*/*';
		if ($request->hasHeader($headerName))
		{
			$headerLine = $request->getHeaderLine($headerName);
		}
		try
		{
			return Accept::fromString($headerName . ': ' . $headerLine);
		}
		catch (\Exception $e)
		{
			throw new Exception\BadRequest('Invalid Accept header', $e);
		}
	}
143401
public static function parseHeader(string $header): array
    {
        $cookie = [];
        $kvs = explode('; ', $header);
        $nv = explode('=', array_shift($kvs));
        $cookie['name'] = $nv[0];
        //because of some stupid system could return Set-Cookie: foo=''; so we must replace it.
        $cookie['value'] = str_replace(['\'\'', '""'], '', $nv[1]);
        foreach ($kvs as $kv) {
            $kv = explode('=', $kv);
            $kv[0] = strtolower($kv[0]);
            if (isset($kv[1])) {
                $cookie[$kv[0]] = $kv[1];
            } else {
                $cookie[$kv[0]] = true;
            }
        }
        /**
         * If a response includes both an Expires header and a max-age directive,
         * the max-age directive overrides the Expires header!
         */
        if (isset($cookie['max-age'])) {
            $cookie['expires'] = time() + $cookie['max-age'];
        } else {
            if (isset($cookie['expires'])) {
                $cookie['expires'] = strtotime($cookie['expires']);
            }
        }

        return $cookie;
    }
485585
public static function getAccept(): array
    {
        if (!self::$accept) {
            // get header from request
            self::$accept = self::parseAcceptHeader(self::getHeader('Accept'));
        }
        return self::$accept;
    }
720772
def parse_accept_lang_header(lang_string):
    
    result = []
    pieces = accept_language_re.split(lang_string)
    if pieces[-1]:
        return []
    for i in range(0, len(pieces) - 1, 3):
        first, lang, priority = pieces[i : i + 3]
        if first:
            return []
        priority = priority and float(priority) or 1.0
        result.append((lang, priority))
    result.sort(lambda x, y: -cmp(x[1], y[1]))
    return result
337411
protected function _parseAccept() {
		$accept = $this->env('HTTP_ACCEPT');
		$accept = (preg_match('/[a-z,-]/i', $accept)) ? explode(',', $accept) : ['text/html'];

		foreach (array_reverse($accept) as $i => $type) {
			unset($accept[$i]);
			list($type, $q) = (explode(';q=', $type, 2) + [$type, 1.0 + $i / 100]);
			$accept[$type] = ($type === '*/*') ? 0.1 : floatval($q);
		}
		arsort($accept, SORT_NUMERIC);

		if (isset($accept['application/xhtml+xml']) && $accept['application/xhtml+xml'] >= 1) {
			unset($accept['application/xml']);
		}
		$media = $this->_classes['media'];

		if (isset($this->params['type']) && ($handler = $media::type($this->params['type']))) {
			if (isset($handler['content'])) {
				$type = (array) $handler['content'];
				$accept = [current($type) => 1] + $accept;
			}
		}
		return array_keys($accept);
	}
772795
public function getAcceptRange(): AcceptRange {
		if ($this->acceptRange !== null) {
			return $this->acceptRange;
		}
		
		if (isset($this->serverVars['HTTP_ACCEPT'])) {
			return $this->acceptRange = AcceptRange::createFromStr($this->serverVars['HTTP_ACCEPT']);
		}
		
		return $this->acceptRange = new AcceptRange(array());
	}
1155582
public function accept($accept)
    {
        if (is_array($accept)) {
            $accept = implode(',', $accept);
        }

        $this->addAttribute('accept', $accept);

        return $this;
    }
282066
private function negotiateHeader(string $accept, AbstractNegotiator $negotiator, array $priorities)
    {
        try {
            $best = $negotiator->getBest($accept, $priorities);
        } catch (\Exception $exception) {
            return null;
        }

        if ($best) {
            return $best->getValue();
        }
    }