Completed
Push — master ( 467d47...6f2bb4 )
by Anton
14s
created

RowRelations   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 45.45%

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 5
cts 11
cp 0.4545
c 0
b 0
f 0
rs 10
wmc 5
lcom 1
cbo 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setRelation() 0 5 1
A getRelation() 0 5 2
A getRelations() 0 8 2
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Db\Traits;
12
13
use Bluz\Db\Relations;
14
use Bluz\Db\Row;
15
use Bluz\Db\Exception\RelationNotFoundException;
16
use Bluz\Db\Exception\TableNotFoundException;
17
use Bluz\Db\RowInterface;
18
19
/**
20
 * RowRelations
21
 *
22
 * @package  Bluz\Db\Traits
23
 * @author   Anton Shevchuk
24
 */
25
trait RowRelations
26
{
27
    /**
28
     * @var array relations rows
29
     */
30
    protected $relations = [];
31
32
    /**
33
     * Set relation
34
     *
35
     * @param  Row $row
36
     *
37
     * @return void
38
     * @throws TableNotFoundException
39
     */
40
    public function setRelation(Row $row) : void
41
    {
42
        $modelName = $row->getTable()->getModel();
43
        $this->relations[$modelName] = [$row];
44
    }
45
46
    /**
47
     * Get relation by model name
48
     *
49
     * @param  string $modelName
50
     *
51
     * @return RowInterface
52
     * @throws RelationNotFoundException
53
     * @throws TableNotFoundException
54
     */
55 1
    public function getRelation($modelName) : ?RowInterface
56
    {
57 1
        $relations = $this->getRelations($modelName);
58
        return empty($relations) ? null : current($relations);
59
    }
60
61
    /**
62
     * Get relations by model name
63
     *
64
     * @param  string $modelName
65
     *
66
     * @return RowInterface[]
67
     * @throws RelationNotFoundException
68
     * @throws TableNotFoundException
69
     */
70 1
    public function getRelations($modelName) : array
71
    {
72 1
        if (!isset($this->relations[$modelName])) {
73 1
            $this->relations[$modelName] = Relations::findRelation($this, $modelName);
74
        }
75
76
        return $this->relations[$modelName];
77
    }
78
}
79