lithium\net\http\Media::negotiate PHP Méthode

negotiate() public static méthode

Performs content-type negotiation on a Request object, by iterating over the accepted types in sequence, from most preferred to least, and attempting to match each one against a content type defined by Media::type(), until a match is found. If more than one defined type matches for a given content type, they will be checked in the order they were added (usually, this corresponds to the order they were defined in the application bootstrapping process).
See also: lithium\net\http\Media::type()
See also: lithium\net\http\Media::match()
See also: lithium\action\Request
public static negotiate ( Request $request ) : string | null
$request lithium\action\Request The request which contains the details of the request to be content-negotiated.
Résultat string | null Returns the first matching type name, i.e. `'html'` or `'json'`. When no matching type is found returns `null`.
    public static function negotiate($request)
    {
        $self = get_called_class();
        $match = function ($name) use($self, $request) {
            if (($cfg = $self::type($name)) && $self::match($request, compact('name') + $cfg)) {
                return true;
            }
            return false;
        };
        if (($type = $request->type) && $match($type)) {
            return $type;
        }
        foreach ($request->accepts(true) as $type) {
            if (!($types = (array) static::_types($type))) {
                continue;
            }
            foreach ($types as $name) {
                if (!$match($name)) {
                    continue;
                }
                return $name;
            }
        }
    }

Usage Example

Exemple #1
0
 public function testContentNegotiationByUserAgent()
 {
     Media::type('iphone', 'application/xhtml+xml', array('conditions' => array('mobile' => true)));
     $request = new Request(array('env' => array('HTTP_USER_AGENT' => 'Safari', 'HTTP_ACCEPT' => 'application/xhtml+xml,text/html')));
     $this->assertEqual('html', Media::negotiate($request));
     $request = new Request(array('env' => array('HTTP_USER_AGENT' => 'iPhone', 'HTTP_ACCEPT' => 'application/xhtml+xml,text/html')));
     $this->assertEqual('iphone', Media::negotiate($request));
 }