PopulateObjectTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 49
ccs 0
cts 25
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
createObject() 0 1 ?
A populate() 0 18 4
A createObjects() 0 10 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember/
7
 */
8
9
namespace flipbox\craft\ember\queries;
10
11
use yii\base\BaseObject;
12
13
/**
14
 * @property string|callable $indexBy
15
 *
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 2.0.0
18
 */
19
trait PopulateObjectTrait
20
{
21
    /**
22
     * @param $row
23
     *
24
     * @return BaseObject
25
     */
26
    abstract protected function createObject($row): BaseObject;
27
28
    /**
29
     * @inheritdoc
30
     *
31
     * @return BaseObject[]|array The resulting elements.
32
     */
33
    public function populate($rows)
34
    {
35
        $indexBy = $this->indexBy;
36
37
        if ($indexBy === null) {
38
            return $this->createObjects($rows);
39
        }
40
        $result = [];
41
        foreach ($rows as $row) {
42
            if (is_string($indexBy)) {
43
                $key = $row[$indexBy];
44
            } else {
45
                $key = call_user_func($indexBy, $row);
46
            }
47
            $result[$key] = $this->createObject($row);
48
        }
49
        return $result;
50
    }
51
52
    /**
53
     * @param $rows
54
     *
55
     * @return mixed
56
     */
57
    protected function createObjects($rows)
58
    {
59
        $models = [];
60
61
        foreach ($rows as $key => $row) {
62
            $models[$key] = $this->createObject($row);
63
        }
64
65
        return $models;
66
    }
67
}
68