StaticModel::getByKey()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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