Passed
Branch master (324b48)
by Tõnis
04:36
created

StaticModel::allModels()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 0
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace andmemasin\myabstract;
4
5
use yii\base\Model;
6
use andmemasin\helpers\MyArrayHelper;
7
8
class StaticModel extends Model
9
{
10
    public static $keyColumn = 'key';
11
12
    /**
13
     * @return array
14
     */
15
    public function getModelAttributes() {
16
        return [];
17
    }
18
19
    /**
20
     * @return static[]
21
     */
22
    public function allModels()
23
    {
24
        $models = [];
25
        $data = $this->getModelAttributes();
26
        if (!empty($data)) {
27
            foreach ($data as $attributes) {
28
                $models[] = new static($attributes);
29
            }
30
        }
31
        return $models;
32
    }
33
34
    /**
35
     * @param $id
36
     * @return static
37
     */
38
    public static function getById($id) {
39
        $models = (new static)->getModelAttributes();
40
        if (isset($models[$id])) {
41
            return new static($models[$id]);
42
        }
43
        return null;
44
    }
45
    /**
46
     * @param $key
47
     * @return static
48
     */
49
    public static function getByKey($key) {
50
        $arr = MyArrayHelper::indexByColumn((new static)->getModelAttributes(), static::$keyColumn);
51
52
        if (isset($arr[$key])) {
53
            return new static($arr[$key]);
54
        }
55
        return null;
56
    }
57
58
}