Completed
Push — master ( d0bd4d...b4b0fd )
by Igor
23:04
created

ModelTrait::asJsonModelErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
1
<?php
2
3
namespace app\traits;
4
5
use Yii;
6
use yii\helpers\Html;
7
use yii\web\NotFoundHttpException;
8
use yii\db\ActiveRecord;
9
use yii\web\Response;
10
11
trait ModelTrait
12
{
13
    /**
14
     * Find the model based on its primary key value or WHERE condition.
15
     * If the model is not found or access denied, a 404 HTTP exception will be thrown.
16
     *
17
     * @param ActiveRecord $model
18
     * @param mixed $id primary key or WHERE condition
19
     * @param string $checkAccess
20
     * @return ActiveRecord
21
     * @throws NotFoundHttpException
22
     */
23
    public function findModel(ActiveRecord $model, $id, string $checkAccess = null): ActiveRecord
24
    {
25
        $model = $model::findOne($id);
26
27
        if ($model === null || ($checkAccess !== null && !$model->$checkAccess())) {
28
            throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
29
        } // @codeCoverageIgnore
30
31
        return $model;
32
    }
33
34
    /**
35
     * Returns an error messages as an array indexed by the ID.
36
     * This is a helper method that simplifies the way of writing AJAX validation code
37
     *
38
     * @param yii\base\Model $model
39
     * @return yii\web\Response
40
     */
41
    public function asJsonModelErrors(\yii\base\Model $model): Response
42
    {
43
        $response = Yii::$app->getResponse();
44
        $response->format = Response::FORMAT_JSON;
45
        $response->statusCode = 422;
46
47
        $result = [];
48
        foreach ($model->getErrors() as $attribute => $errors) {
49
            $result[Html::getInputId($model, $attribute)] = $errors;
50
        }
51
52
        $response->data = $result;
53
        return $response;
54
    }
55
}
56