Completed
Push — master ( 6214df...f7ef88 )
by Igor
03:39
created

ModelTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 0
cbo 2
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A findModel() 0 10 4
A collectErrors() 0 12 3
1
<?php
2
3
namespace app\traits;
4
5
use yii\helpers\Html;
6
use yii\web\NotFoundHttpException;
7
8
trait ModelTrait
9
{
10
    /**
11
     * Find the model based on its primary key value or WHERE condition.
12
     * If the model is not found or access denied, a 404 HTTP exception will be thrown.
13
     *
14
     * @param ActiveRecord $model
15
     * @param int|array $id primary key or WHERE condition
16
     * @param callable $checkAccess
17
     * @return ActiveRecord
18
     * @throws NotFoundHttpException
19
     */
20
    public function findModel($model, $id, $checkAccess = null)
21
    {
22
        $model = $model::findOne($id);
23
24
        if ($model === null || ($checkAccess !== null && !$model->$checkAccess())) {
25
            throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
26
        } // @codeCoverageIgnore
27
28
        return $model;
29
    }
30
31
    /**
32
     * Collect model errors
33
     *
34
     * @param Model $model the model to be validated
35
     * @return array the error message array indexed by the attribute IDs.
36
     */
37
     public static function collectErrors($model)
38
     {
39
         $result = [];
40
         /* @var $model Model */
41
         $models = [$model];
42
         foreach ($models as $model) {
43
             foreach ($model->getErrors() as $attribute => $errors) {
44
                 $result[Html::getInputId($model, $attribute)] = $errors;
45
             }
46
         }
47
         return $result;
48
     }
49
}
50