Class luya\helpers\RestHelper
Inheritance | luya\helpers\RestHelper » luya\yii\helpers\RestHelper |
---|---|
Available since version | 1.0.20 |
Source Code | https://github.com/luyadev/luya/blob/master/core/helpers/RestHelper.php |
Rest API Helper.
Public Methods
Method | Description | Defined By |
---|---|---|
sendArrayError() | Send Array validation error. | luya\yii\helpers\RestHelper |
sendModelError() | Send Model errors with correct headers. | luya\yii\helpers\RestHelper |
Method Details
Defined in: luya\yii\helpers\RestHelper::sendArrayError()
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 static 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 static function sendArrayError(array $errors)
{
Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
$result = [];
foreach ($errors as $key => $value) {
$messages = (array) $value;
foreach ($messages as $msg) {
$result[] = ['field' => $key, 'message' => $msg];
}
}
return $result;
}
Defined in: luya\yii\helpers\RestHelper::sendModelError()
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 static 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 static function sendModelError(Model $model)
{
if (!$model->hasErrors()) {
throw new InvalidParamException('The model as thrown an uknown Error.');
}
Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
$result = [];
foreach ($model->getFirstErrors() as $name => $message) {
$result[] = [
'field' => $name,
'message' => $message,
];
}
return $result;
}