Completed
Push — master ( bbcbbc...8c42c0 )
by Timo
07:53
created

Relationship::addJoin()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
crap 1
1
<?php
2
3
namespace hamburgscleanest\DataTables\Models;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Model;
7
8
/**
9
 * Class Relationship
10
 * @package hamburgscleanest\hamburgscleanest\DataTables\Models
11
 */
12
class Relationship {
13
14
    /** @var string */
15
    public $name;
16
    /** @var string */
17
    private $_baseTable;
18
    /** @var string */
19
    private $_relatedTable;
20
    /** @var string */
21
    private $_baseKey;
22
    /** @var string */
23
    private $_foreignKey;
24
25
    /**
26
     * Relationship constructor.
27
     * @param string $name
28
     * @param Model $baseModel
29
     */
30 4
    public function __construct(string $name, Model $baseModel)
31
    {
32
        /** @var Model $related */
33 4
        $related = $baseModel->$name()->getRelated();
34
35 4
        $this->name = $name;
36 4
        $this->_baseTable = $baseModel->getTable();
37 4
        $this->_relatedTable = $related->getTable();
38 4
        $this->_baseKey = $baseModel->getKeyName();
39 4
        $this->_foreignKey = $related->getForeignKey();
40 4
    }
41
42
    /**
43
     * @param Model $baseModel
44
     * @param array $relations
45
     * @return array
46
     */
47
    public static function createFromArray(Model $baseModel, array $relations) : array
48
    {
49 4
        return \array_map(function($relation) use ($baseModel) {
50 4
            return new static($relation, $baseModel);
51 4
        }, $relations);
52
    }
53
54
    /**
55
     * Add the join for the relation to the query.
56
     *
57
     * @param Builder $queryBuilder
58
     * @return void
59
     */
60 4
    public function addJoin(Builder $queryBuilder) : void
61
    {
62 4
        $queryBuilder->join(
63 4
            $this->_relatedTable . ' AS ' . $this->name,
64 4
            $this->_baseTable . '.' . $this->_baseKey,
65 4
            '=',
66 4
            $this->name . '.' . $this->_foreignKey
67
        );
68
    }
69
}