Completed
Branch develop (cd8f66)
by Nate
03:44
created

ActiveRecord::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 6
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\ember\services\traits\records;
10
11
use flipbox\ember\helpers\QueryHelper;
12
use yii\db\ActiveQuery;
13
use yii\db\ActiveRecord as Record;
14
use yii\db\Connection;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 1.0.0
19
 */
20
trait ActiveRecord
21
{
22
    /**
23
     * @return string
24
     */
25
    public abstract static function recordClass(): string;
26
27
    /**
28
     * @return Connection
29
     */
30
    protected static function getDb(): Connection
31
    {
32
        /** @var Record $recordClass */
33
        $recordClass = static::recordClass();
34
35
        return $recordClass::getDb();
36
    }
37
38
    /*******************************************
39
     * CREATE
40
     *******************************************/
41
42
    /**
43
     * @param array $attributes
44
     * @return Record
45
     */
46
    public function create(array $attributes = []): Record
47
    {
48
        /** @var string $recordClass */
49
        $recordClass = static::recordClass();
50
51
        /** @var Record $record */
52
        $record = new $recordClass();
53
54
        // Do we need to set properties too
55
        if (!empty($attributes)) {
56
            $record->setAttributes($attributes);
57
        }
58
59
        return $record;
60
    }
61
62
    /*******************************************
63
     * QUERY
64
     *******************************************/
65
66
    /**
67
     * @param array $config
68
     * @return \yii\db\ActiveQuery
69
     */
70
    public function getQuery($config = []): ActiveQuery
71
    {
72
        /** @var Record $recordClass */
73
        $recordClass = static::recordClass();
74
75
        $query = $recordClass::find();
76
77
        QueryHelper::configure(
78
            $query,
79
            $this->prepareQueryConfig($config)
80
        );
81
82
        return $query;
83
    }
84
85
    /**
86
     * @param array $config
87
     * @return array
88
     */
89
    protected function prepareQueryConfig($config = [])
90
    {
91
        return $config;
92
    }
93
}
94