Class yii\filters\ContentNegotiator

Inheritanceyii\filters\ContentNegotiator » yii\base\ActionFilter » yii\base\Behavior » yii\base\BaseObject
Implementsyii\base\BootstrapInterface, yii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/filters/ContentNegotiator.php

ContentNegotiator supports response format negotiation and application language negotiation.

When the supported formats property is specified, ContentNegotiator will support response format negotiation based on the value of the GET parameter $formatParam and the Accept HTTP header. If a match is found, the yii\web\Response::$format property will be set as the chosen format. The yii\web\Response::$acceptMimeType as well as yii\web\Response::$acceptParams will also be updated accordingly.

When the supported languages is specified, ContentNegotiator will support application language negotiation based on the value of the GET parameter $languageParam and the Accept-Language HTTP header. If a match is found, the yii\base\Application::$language property will be set as the chosen language.

You may use ContentNegotiator as a bootstrapping component as well as an action filter.

The following code shows how you can use ContentNegotiator as a bootstrapping component. Note that in this case, the content negotiation applies to the whole application.

// in application configuration
use yii\web\Response;

return [
    'bootstrap' => [
        [
            'class' => 'yii\filters\ContentNegotiator',
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
                'application/xml' => Response::FORMAT_XML,
            ],
            'languages' => [
                'en',
                'de',
            ],
        ],
    ],
];

The following code shows how you can use ContentNegotiator as an action filter in either a controller or a module. In this case, the content negotiation result only applies to the corresponding controller or module, or even specific actions if you configure the only or except property of the filter.

use yii\web\Response;

public function behaviors()
{
    return [
        [
            'class' => 'yii\filters\ContentNegotiator',
            'only' => ['view', 'index'],  // in a controller
            // if in a module, use the following IDs for user actions
            // 'only' => ['user/view', 'user/index']
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
            'languages' => [
                'en',
                'de',
            ],
        ],
    ];
}

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$except array List of action IDs that this filter should not apply to. yii\base\ActionFilter
$formatParam string The name of the GET parameter that specifies the response format. yii\filters\ContentNegotiator
$formats array List of supported response formats. yii\filters\ContentNegotiator
$languageParam string The name of the GET parameter that specifies the application language. yii\filters\ContentNegotiator
$languages array A list of supported languages. yii\filters\ContentNegotiator
$only array List of action IDs that this filter should apply to. yii\base\ActionFilter
$owner yii\base\Component|null The owner of this behavior yii\base\Behavior
$request yii\web\Request The current request. yii\filters\ContentNegotiator
$response yii\web\Response The response to be sent. yii\filters\ContentNegotiator

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
afterAction() This method is invoked right after an action is executed. yii\base\ActionFilter
afterFilter() yii\base\ActionFilter
attach() Attaches the behavior object to the component. yii\base\Behavior
beforeAction() This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action. yii\filters\ContentNegotiator
beforeFilter() yii\base\ActionFilter
bootstrap() Bootstrap method to be called during application bootstrap stage. yii\filters\ContentNegotiator
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
detach() Detaches the behavior object from the component. yii\base\Behavior
events() Declares event handlers for the $owner's events. yii\base\Behavior
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
negotiate() Negotiates the response format and application language. yii\filters\ContentNegotiator

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
getActionId() Returns an action ID by converting yii\base\Action::$uniqueId into an ID relative to the module. yii\base\ActionFilter
isActive() Returns a value indicating whether the filter is active for the given action. yii\base\ActionFilter
isLanguageSupported() Returns a value indicating whether the requested language matches the supported language. yii\filters\ContentNegotiator
negotiateContentType() Negotiates the response format. yii\filters\ContentNegotiator
negotiateLanguage() Negotiates the application language. yii\filters\ContentNegotiator

Property Details

$formatParam public property

The name of the GET parameter that specifies the response format. Note that if the specified format does not exist in $formats, a yii\web\NotAcceptableHttpException exception will be thrown. If the parameter value is empty or if this property is null, the response format will be determined based on the Accept HTTP header only.

See also $formats.

public string $formatParam '_format'
$formats public property

List of supported response formats. The keys are MIME types (e.g. application/json) while the values are the corresponding formats (e.g. html, json) which must be supported as declared in yii\web\Response::$formatters.

If this property is empty or not set, response format negotiation will be skipped.

public array $formats null
$languageParam public property

The name of the GET parameter that specifies the application language. Note that if the specified language does not match any of $languages, the first language in $languages will be used. If the parameter value is empty or if this property is null, the application language will be determined based on the Accept-Language HTTP header only.

See also $languages.

public string $languageParam '_lang'
$languages public property

A list of supported languages. The array keys are the supported language variants (e.g. en-GB, en-US), while the array values are the corresponding language codes (e.g. en, de) recognized by the application.

Array keys are not always required. When an array value does not have a key, the matching of the requested language will be based on a language fallback mechanism. For example, a value of en will match en, en_US, en-US, en-GB, etc.

If this property is empty or not set, language negotiation will be skipped.

public array $languages null
$request public property

The current request. If not set, the request application component will be used.

public yii\web\Request $request null
$response public property

The response to be sent. If not set, the response application component will be used.

Method Details

beforeAction() public method

This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.

public boolean beforeAction ( $action )
$action yii\base\Action

The action to be executed.

return boolean

Whether the action should continue to be executed.

bootstrap() public method

Bootstrap method to be called during application bootstrap stage.

public void bootstrap ( $app )
$app yii\base\Application

The application currently running

isLanguageSupported() protected method

Returns a value indicating whether the requested language matches the supported language.

protected boolean isLanguageSupported ( $requested, $supported )
$requested string

The requested language code

$supported string

The supported language code

return boolean

Whether the requested language is supported

negotiate() public method

Negotiates the response format and application language.

public void negotiate ( )
negotiateContentType() protected method

Negotiates the response format.

protected void negotiateContentType ( $request, $response )
$request yii\web\Request
$response yii\web\Response
throws yii\web\BadRequestHttpException

if an array received for GET parameter $formatParam.

throws yii\web\NotAcceptableHttpException

if none of the requested content types is accepted.

negotiateLanguage() protected method

Negotiates the application language.

protected string negotiateLanguage ( $request )
$request yii\web\Request
return string

The chosen language