Completed
Push — master ( 89be15...80fd60 )
by Igor
11:15
created

ControllerTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 63
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A findModel() 0 10 2
A findModelByQuery() 0 10 2
A asJsonModelErrors() 0 14 2
1
<?php
2
3
namespace app\traits;
4
5
use Yii;
6
use yii\helpers\Html;
7
use yii\web\{Response, NotFoundHttpException};
8
use yii\db\ActiveRecord;
9
10
trait ControllerTrait
11
{
12
    /**
13
     * Find the model based on its primary key value or WHERE condition.
14
     * If the model is not found, then 404 HTTP exception will be thrown
15
     *
16
     * @param string $model Class name
17
     * @param mixed $condition primary key or WHERE condition
18
     * @return ActiveRecord
19
     * @throws NotFoundHttpException
20
     */
21
    public function findModel(string $model, $condition): ActiveRecord
22
    {
23
        $model = $model::findOne($condition);
24
25
        if ($model === null) {
26
            throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
27
        }
28
29
        return $model;
30
    }
31
32
    /**
33
     * Find the model based on prepared ActiveQuery
34
     * If the model is not found, then 404 HTTP exception will be thrown
35
     *
36
     * @param ActiveQuery $query
37
     * @return ActiveRecord
38
     * @throws NotFoundHttpException
39
     */
40
    public function findModelByQuery($query): ActiveRecord
41
    {
42
        $model = $query->one();
43
44
        if ($model === null) {
45
            throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
46
        }
47
48
        return $model;
49
    }
50
51
    /**
52
     * Returns an error messages as an array indexed by the ID.
53
     * This is a helper method that simplifies the way of writing AJAX validation code
54
     *
55
     * @param yii\base\Model $model
56
     * @return yii\web\Response
57
     */
58
    public function asJsonModelErrors(\yii\base\Model $model): Response
59
    {
60
        $response = Yii::$app->getResponse();
61
        $response->format = Response::FORMAT_JSON;
62
        $response->statusCode = 422;
63
64
        $result = [];
65
        foreach ($model->getErrors() as $attribute => $errors) {
66
            $result[Html::getInputId($model, $attribute)] = $errors;
67
        }
68
69
        $response->data = $result;
70
        return $response;
71
    }
72
}
73