PopulateObjectTrait::createObject()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
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