Trait luya\traits\RestBehaviorsTrait

Implemented byluya\admin\apis\ApiUserController, luya\admin\apis\CommonController, luya\admin\apis\ConfigController, luya\admin\apis\EffectController, luya\admin\apis\FilterController, luya\admin\apis\GroupController, luya\admin\apis\LangController, luya\admin\apis\LoggerController, luya\admin\apis\MenuController, luya\admin\apis\NgrestLogController, luya\admin\apis\PropertyController, luya\admin\apis\ProxyBuildController, luya\admin\apis\ProxyController, luya\admin\apis\ProxyMachineController, luya\admin\apis\QueueLogController, luya\admin\apis\QueueLogErrorController, luya\admin\apis\RemoteController, luya\admin\apis\SearchController, luya\admin\apis\StorageController, luya\admin\apis\StorageImageController, luya\admin\apis\TagController, luya\admin\apis\TimestampController, luya\admin\apis\UserController, luya\admin\base\RestActiveController, luya\admin\base\RestController, luya\admin\controllers\UptimeController, luya\admin\ngrest\base\Api, luya\cms\admin\apis\AdminController, luya\cms\admin\apis\BlockController, luya\cms\admin\apis\BlockgroupController, luya\cms\admin\apis\LayoutController, luya\cms\admin\apis\LogController, luya\cms\admin\apis\MenuController, luya\cms\admin\apis\NavContainerController, luya\cms\admin\apis\NavController, luya\cms\admin\apis\NavItemBlockController, luya\cms\admin\apis\NavItemController, luya\cms\admin\apis\NavItemPageBlockItemController, luya\cms\admin\apis\NavItemPageController, luya\cms\admin\apis\RedirectController, luya\cms\admin\apis\ThemeController, luya\cms\admin\apis\WebsiteController, luya\rest\ActiveController, luya\rest\Controller
Available since version1.0.0

Rest Behaviors Trait.

This class overrides the default behaviors method of {{yii\rest\Controller}} controllers.

The following changes are differ to the base implementation:

  • If {{luya\rest\UserBehaviorInterface}} is not implemented, the authenticator behavior ({{yii\filters\auth\CompositeAuth}}) is removed.
  • If {{luya\rest\UserBehaviorInterface}} is implemented, the authenticator behavior ({{yii\filters\auth\CompositeAuth}}) is enabled.
  • If {{luya\rest\UserBehaviorInterface}} is implemented, the contentNegotiator behavior ({{yii\filters\ContentNegotiator}}) is enabled.
  • The rateLimiter behavior filter is removed by default.

Read the {{luya\rest\UserBehaviorInterface}} about the configuration ability to protect the controller.

Public Properties

Hide inherited properties

Property Type Description Defined By
$authOptional array List of action IDs that this filter will be applied to, but auth failure will not lead to error. luya\traits\RestBehaviorsTrait
$enableCors boolean Whether CORS should be enabled or not. luya\traits\RestBehaviorsTrait
$jsonCruft boolean Whether a unparsable cruf should be added to the json response or not. luya\traits\RestBehaviorsTrait
$languages array An array with languages which are passed to {{yii\filters\ContentNegotiator::$languages}}. luya\traits\RestBehaviorsTrait

Public Methods

Hide inherited methods

Method Description Defined By
behaviors() Override the default {{yii\rest\Controller::behaviors()}} method. luya\traits\RestBehaviorsTrait
getCompositeAuthMethods() Return all Auth methods for Composite Auth. luya\traits\RestBehaviorsTrait
sendArrayError() Send Array validation error. luya\traits\RestBehaviorsTrait
sendModelError() Send Model errors with correct headers. luya\traits\RestBehaviorsTrait

Property Details

Hide inherited properties

$authOptional public property (available since version 1.0.21)

List of action IDs that this filter will be applied to, but auth failure will not lead to error. It may be used for actions, that are allowed for public, but return some additional data for authenticated users. Defaults to empty, meaning authentication is not optional for any action. Since version 2.0.10 action IDs can be specified as wildcards, e.g. site/*.

public array $authOptional = []
$enableCors public property

Whether CORS should be enabled or not.

public boolean $enableCors false
$jsonCruft public property (available since version 1.0.7)

Whether a unparsable cruf should be added to the json response or not. When enabled you have to parse the json response first before interpreting as json.

public boolean $jsonCruft false
$languages public property (available since version 1.0.7)

An array with languages which are passed to {{yii\filters\ContentNegotiator::$languages}}. Example

'languages' => [
    'en',
    'de',
],
public array $languages = []

Method Details

Hide inherited methods

behaviors() public method

Override the default {{yii\rest\Controller::behaviors()}} method.

The following changes are differ to the base implementation:

  • If {{luya\rest\UserBehaviorInterface}} is not implemented, the authenticator behavior ({{yii\filters\auth\CompositeAuth}}) is removed.
  • If {{luya\rest\UserBehaviorInterface}} is implemented, the authenticator behavior ({{yii\filters\auth\CompositeAuth}}) is enabled.
  • If {{luya\rest\UserBehaviorInterface}} is implemented, the contentNegotiator behavior ({{yii\filters\ContentNegotiator}}) is enabled.
  • The rateLimiter behavior filter is removed by default.
public array behaviors ( )
return array

Returns an array with registered behavior filters based on the implementation type.

                public function behaviors()
{
    $behaviors = parent::behaviors();
    if ($this->enableCors) {
        $behaviors['cors'] = Yii::$app->corsConfig;
    }
    unset($behaviors['authenticator']);
    if ($this->getUserAuthClass()) {
        
        // change to admin user auth class
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'user' => $this->getUserAuthClass(),
            'authMethods' => $this->getCompositeAuthMethods(),
            'optional' => $this->authOptional,
        ];
        
        if ($this->enableCors) {
            $behaviors['authenticator']['except'] = ['options'];
        }
    }
    $behaviors['contentNegotiator'] = [
        'class' => ContentNegotiator::class,
        'formats' => [
            'application/json' => Response::FORMAT_JSON,
            'application/xml' => Response::FORMAT_XML,
        ],
        'languages' => $this->languages,
    ];
    
    // by default rate limiter behavior is removed as it requires a database
    // user given from the admin module.
    if (isset($behaviors['rateLimiter'])) {
        unset($behaviors['rateLimiter']);
    }
    if ($this->jsonCruft) {
        $behaviors['cruft'] = JsonCruftFilter::class;
    }
    
    return $behaviors;
}

            
getCompositeAuthMethods() public method (available since version 1.0.21)

Return all Auth methods for Composite Auth.

public array getCompositeAuthMethods ( )

                public function getCompositeAuthMethods()
{
    return [
        QueryParamAuth::class,
        HttpBearerAuth::class,
    ];
}

            
sendArrayError() public method (available since version 1.0.3)

Send Array validation error.

Example input:

return $this->sendArrayError(['firstname' => 'Firstname cannot be blank']);

Example return value:

Array
(
    [0] => Array
        (
            [field] => firstname
            [message] => Firstname cannot be blank.
        )
)
public array sendArrayError ( array $errors )
$errors array

Provide an array with messages. Where key is the field and value the message.

return array

Returns an array with field and message keys for each item.

                public function sendArrayError(array $errors)
{
    return RestHelper::sendArrayError($errors);
}

            
sendModelError() public method

Send Model errors with correct headers.

Helper method to correctly send model errors with the correct response headers.

Example return value:

Array
(
    [0] => Array
        (
            [field] => firstname
            [message] => Firstname cannot be blank.
        )
    [1] => Array
        (
            [field] => email
            [message] => Email cannot be blank.
        )
)
public array sendModelError ( yii\base\Model $model )
$model yii\base\Model

The model to find the first error.

return array

If the model has errors InvalidParamException will be thrown, otherwise an array with message and field key.

throws yii\base\InvalidParamException

                public function sendModelError(Model $model)
{
    return RestHelper::sendModelError($model);
}