Completed
Push — master ( b011b0...d9d0f6 )
by Tõnis
02:28
created

DActiveRecord::primaryKeySingle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace dameter\abstracts;
4
5
6
use yii\base\NotSupportedException;
7
use yii\db\ActiveRecord;
8
9
class DActiveRecord extends ActiveRecord
10
{
11
    /** in case we would need to customize stuff */
12
13
    /**
14
     * Get the primary key column as string if the one-column PK
15
     * @return string
16
     * @throws NotSupportedException if multi-column PrimaryKey is used
17
     */
18
    public static function primaryKeySingle()
19
    {
20
        if (count(self::primaryKey()) === 1) {
21
            return static::tableName() . "_id";
22
        }
23
        throw new NotSupportedException('Not supported for multi-column primary keys');
24
    }
25
26
27
    /** {@inheritdoc} */
28
    public function hasMany($class, $link = null)
29
    {
30
31
        if (empty($link)) {
32
            /** @var DActiveRecord $class */
33
            $link = [$class::primaryKeySingle() => $class::primaryKeySingle()];
34
        }
35
        return parent::hasMany($class, $link);
36
    }
37
38
    /** {@inheritdoc} */
39
    public function hasOne($class, $link = null)
40
    {
41
        if (empty($link)) {
42
            /** @var DActiveRecord $class */
43
            $link = [$class::primaryKeySingle() => $class::primaryKeySingle()];
44
        }
45
        return parent::hasOne($class, $link);
46
    }
47
}