Completed
Push — master ( 05f0c6...d5b4df )
by Dmitry
03:21
created

AbstractModel::getRelatedAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
ccs 0
cts 10
cp 0
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 6
1
<?php
2
3
namespace hiqdev\billing\hiapi\models;
4
5
use yii\base\InvalidConfigException;
6
7
abstract class AbstractModel implements ModelInterface
8
{
9
    public function hasAttribute($name): bool
10
    {
11
        return isset($this->attributes()[$name]);
12
    }
13
14
    public function hasRelation($name): bool
15
    {
16
        return isset($this->relations()[$name]);
17
    }
18
19
    /**
20
     * @param $name
21
     * @return string
22
     * @throws InvalidConfigException
23
     */
24
    public function getRelation($name)
25
    {
26 View Code Duplication
        if (!$this->hasRelation($name)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
27
            throw new InvalidConfigException('Model ' . static::class . ' does not have relation ' . $name);
28
        }
29
30
        return $this->relations()[$name];
31
    }
32
33
    public function getAttribute($name)
34
    {
35 View Code Duplication
        if (!$this->hasAttribute($name)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
36
            throw new InvalidConfigException('Attribute ' . $name . ' is not available within ' . static::class);
37
        }
38
39
        $className = $this->attributes()[$name];
40
        return new $className;
41
    }
42
43
    public function getRelatedAttribute($name)
44
    {
45
        list($relationName, $attribute) = explode('-', $name, 2);
46
47
        $className = $this->getRelation($relationName);
48
        /** @var ModelInterface $relation */
49
        $relation = new $className();
50
        if ($relation->hasAttribute($attribute)) {
51
            return $relation->getAttribute($attribute);
52
        }
53
54
        return $relation->getRelatedAttribute($attribute);
55
    }
56
}
57