ControllerTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 2
dl 0
loc 28
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A asJsonModelErrors() 0 18 4
1
<?php
2
3
namespace app\controllers;
4
5
use Yii;
6
use yii\helpers\Html;
7
use yii\web\Response;
8
9
trait ControllerTrait
10
{
11
    /**
12
     * Returns an error messages as an array indexed by the ID.
13
     * This is a helper method that simplifies the way of writing AJAX validation code.
14
     *
15
     * @param yii\base\Model|yii\base\Model[] $model
16
     * @return yii\web\Response
17
     */
18
    public function asJsonModelErrors($model): Response
19
    {
20
        $models = is_array($model) ? $model : [$model];
21
22
        $response = Yii::$app->getResponse();
23
        $response->format = Response::FORMAT_JSON;
24
        $response->statusCode = 422;
25
26
        $result = [];
27
        foreach ($models as $model) {
28
            foreach ($model->getErrors() as $attribute => $errors) {
29
                $result[Html::getInputId($model, $attribute)] = $errors;
30
            }    
31
        }     
32
33
        $response->data = $result;
34
        return $response;
35
    }
36
}
37