BelongsTo   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 10
c 1
b 0
f 0
dl 0
loc 60
ccs 14
cts 14
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getForeignKey() 0 3 1
A getForeignKeyName() 0 3 1
A __construct() 0 8 1
A getResults() 0 9 2
A getChild() 0 3 1
1
<?php
2
3
namespace Spinen\Halo\Support\Relations;
4
5
use GuzzleHttp\Exception\GuzzleException;
6
use Spinen\Halo\Exceptions\InvalidRelationshipException;
7
use Spinen\Halo\Exceptions\NoClientException;
8
use Spinen\Halo\Exceptions\TokenException;
9
use Spinen\Halo\Support\Builder;
10
use Spinen\Halo\Support\Model;
11
12
/**
13
 * Class BelongsTo
14
 */
15
class BelongsTo extends Relation
16
{
17
    /**
18
     * Create a new belongs to relationship instance.
19
     *
20
     * @return void
21
     *
22
     * @throws InvalidRelationshipException
23
     */
24 12
    public function __construct(protected Builder $builder, protected Model $child, protected $foreignKey)
25
    {
26
        // In the underlying base relationship class, the "child" variable is
27
        // referred to as the "parentModel" since most relationships are not
28
        // inversed. But, since this one is we will create a "child" variable
29
        // for much better readability.
30
31 12
        parent::__construct($builder->whereId($this->getForeignKey()), $this->getChild());
32
    }
33
34
    /**
35
     * Get the child Model
36
     */
37 12
    public function getChild(): Model
38
    {
39 12
        return $this->child;
40
    }
41
42
    /**
43
     * Get the foreign key's name
44
     */
45 12
    public function getForeignKey(): int|string|null
46
    {
47 12
        return $this->getChild()->{$this->getForeignKeyName()};
48
    }
49
50
    /**
51
     * Get the name of the foreign key's name
52
     */
53 12
    public function getForeignKeyName(): string
54
    {
55 12
        return $this->foreignKey;
56
    }
57
58
    /**
59
     * Get the results of the relationship.
60
     *
61
     * @throws GuzzleException
62
     * @throws InvalidRelationshipException
63
     * @throws NoClientException
64
     * @throws TokenException
65
     */
66 2
    public function getResults(): ?Model
67
    {
68 2
        if (! $this->getForeignKey()) {
69 1
            return null;
70
        }
71
72 1
        return $this->getBuilder()
73 1
                    ->get()
74 1
                    ->first();
75
    }
76
}
77