HasRelationships::getRelation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
1
<?php
2
3
namespace Ronanchilvers\Orm\Features;
4
5
use Ronanchilvers\Orm\Features\Relationship\BelongsTo;
6
use Ronanchilvers\Orm\Features\Relationship\HasMany;
7
use Ronanchilvers\Orm\Features\Relationship\HasOne;
8
use Ronanchilvers\Utility\Str;
9
10
/**
11
 * Feature trait for model relations
12
 *
13
 * @author Ronan Chilvers <[email protected]>
14
 */
15
trait HasRelationships
16
{
17
    use BelongsTo,
18
        HasOne,
19
        HasMany;
20
21
    /**
22
     * Does this model have a relationship for a given field?
23
     *
24
     * @param string $attribute
25
     * @return boolean
26
     * @author Ronan Chilvers <[email protected]>
27
     */
28
    public function hasRelation($attribute)
29
    {
30
        $method = $this->getRelationMethod($attribute);
31
32
        return method_exists($this, $method);
33
    }
34
35
    /**
36
     * Get the relation for a given attribute
37
     *
38
     * @param string $attribute The attribute to check for a relationship
39
     * @author Ronan Chilvers <[email protected]>
40
     */
41 1
    public function getRelation($attribute)
42
    {
43 1
        $method = $this->getRelationMethod($attribute);
44 1
        if (method_exists($this, $method)) {
45
            return $this->$method();
46
        }
47
48 1
        return null;
49
    }
50
51
    /**
52
     * Create a relationship method for a given attribute name
53
     *
54
     * @param string
55
     * @return string
56
     * @author Ronan Chilvers <[email protected]>
57
     */
58 1
    protected function getRelationMethod($attribute)
59
    {
60 1
        $shortAttribute = static::unprefix($attribute);
61
62 1
        return 'relate' . Str::pascal($shortAttribute);
63
    }
64
}
65