Negotiation\AbstractNegotiator::getBest PHP Method

getBest() public method

public getBest ( string $header, array $priorities, $strict = false ) : negotiation\AcceptHeader | null
$header string A string containing an `Accept|Accept-*` header.
$priorities array A set of server priorities.
return negotiation\AcceptHeader | null best matching type
    public function getBest($header, array $priorities, $strict = false)
    {
        if (empty($priorities)) {
            throw new InvalidArgument('A set of server priorities should be given.');
        }
        if (!$header) {
            throw new InvalidArgument('The header string should not be empty.');
        }
        // Once upon a time, two `array_map` calls were sitting there, but for
        // some reasons, they triggered `E_WARNING` time to time (because of
        // PHP bug [55416](https://bugs.php.net/bug.php?id=55416). Now, they
        // are gone.
        // See: https://github.com/willdurand/Negotiation/issues/81
        $acceptedHeaders = array();
        foreach ($this->parseHeader($header) as $h) {
            try {
                $acceptedHeaders[] = $this->acceptFactory($h);
            } catch (Exception\Exception $e) {
                if ($strict) {
                    throw $e;
                }
            }
        }
        $acceptedPriorities = array();
        foreach ($priorities as $p) {
            $acceptedPriorities[] = $this->acceptFactory($p);
        }
        $matches = $this->findMatches($acceptedHeaders, $acceptedPriorities);
        $specificMatches = array_reduce($matches, 'Negotiation\\Match::reduce', []);
        usort($specificMatches, 'Negotiation\\Match::compare');
        $match = array_shift($specificMatches);
        return null === $match ? null : $acceptedPriorities[$match->index];
    }

Usage Example

 /**
  * Returns the best value of a header.
  *
  * @param string             $accept     The header to negotiate
  * @param AbstractNegotiator $negotiator
  * @param array              $priorities
  *
  * @return string|null
  */
 private function negotiateHeader($accept, AbstractNegotiator $negotiator, array $priorities)
 {
     if (empty($accept) || empty($priorities)) {
         return;
     }
     try {
         $best = $negotiator->getBest($accept, $priorities);
     } catch (\Exception $exception) {
         return;
     }
     if ($best) {
         return $best->getValue();
     }
 }