Completed
Push — master ( 1056fe...110432 )
by Michael
05:27
created

JoinsTrait   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 12
c 0
b 0
f 0
lcom 1
cbo 4
dl 0
loc 124
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A relationJoinType() 0 9 3
A hasOneJoin() 0 7 1
A hasOneJoinSql() 0 14 1
A hasManyJoin() 0 17 3
A getJoinColumns() 0 13 2
A replaceColumnTables() 0 9 2
1
<?php
2
3
namespace Blasttech\EloquentRelatedPlus;
4
5
use DB;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
use Illuminate\Database\Eloquent\Relations\HasMany;
9
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
10
use Illuminate\Database\Eloquent\Relations\Relation;
11
use Illuminate\Database\Query\Expression;
12
use Illuminate\Database\Query\JoinClause;
13
14
/**
15
 * Trait JoinsTrait
16
 *
17
 * @property array order_fields
18
 * @property array order_defaults
19
 * @property array order_relations
20
 * @property array order_with
21
 * @property array search_fields
22
 * @property string connection
23
 */
24
trait JoinsTrait
25
{
26
    /**
27
     * Check relation type and join
28
     *
29
     * @param Relation $relation
30
     * @param JoinClause $join
31
     * @param \stdClass $table
32
     * @param string $operator
33
     * @param string $direction
0 ignored issues
show
Documentation introduced by
Should the type for parameter $direction not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
34
     * @return Builder|JoinClause
35
     */
36
    protected function relationJoinType($relation, $join, $table, $operator, $direction = null)
37
    {
38
        // If a HasOne relation and ordered - ie join to the latest/earliest
39
        if (class_basename($relation) === 'HasOne' && !empty($relation->toBase()->orders)) {
40
            return $this->hasOneJoin($relation, $join);
41
        } else {
42
            return $this->hasManyJoin($relation, $join, $table, $operator, $direction);
43
        }
44
    }
45
46
    /**
47
     * Join a HasOne relation which is ordered
48
     *
49
     * @param Relation $relation
50
     * @param JoinClause $join
51
     * @return JoinClause
52
     */
53
    protected function hasOneJoin($relation, $join)
54
    {
55
        // Get first relation order (should only be one)
56
        $order = $relation->toBase()->orders[0];
57
58
        return $join->on($order['column'], $this->hasOneJoinSql($relation, $order));
59
    }
60
61
    /**
62
     * Get join sql for a HasOne relation
63
     *
64
     * @param Relation $relation
65
     * @param array $order
66
     * @return Expression
67
     */
68
    protected function hasOneJoinSql($relation, $order)
69
    {
70
        // Build subquery for getting first/last record in related table
71
        $subQuery = $this
0 ignored issues
show
Bug introduced by
It seems like joinOne() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
72
            ->joinOne(
73
                $relation->getRelated()->newQuery(),
74
                $relation,
75
                $order['column'],
76
                $order['direction']
77
            )
78
            ->setBindings($relation->getBindings());
79
80
        return DB::raw('(' . $this->toSqlWithBindings($subQuery) . ')');
0 ignored issues
show
Bug introduced by
It seems like toSqlWithBindings() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
81
    }
82
83
    /**
84
     * Join a HasMany Relation
85
     *
86
     * @param Relation $relation
87
     * @param JoinClause $join
88
     * @param \stdClass $table
89
     * @param string $operator
90
     * @param string $direction
91
     * @return Builder|JoinClause
92
     */
93
    protected function hasManyJoin($relation, $join, $table, $operator, $direction)
94
    {
95
        // Get relation join columns
96
        $joinColumns = $this->getJoinColumns($relation);
97
        $joinColumns = $this->replaceColumnTables($joinColumns, $table);
98
99
        $join->on($joinColumns->first, $operator, $joinColumns->second);
100
101
        // Add any where clauses from the relationship
102
        $join = $this->addRelatedWhereConstraints($join, $relation, $table->alias);
0 ignored issues
show
Bug introduced by
It seems like addRelatedWhereConstraints() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
103
104
        if (!is_null($direction) && get_class($relation) === HasMany::class) {
105
            $join = $this->hasManyJoinWhere($join, $joinColumns->first, $relation, $table->alias, $direction);
0 ignored issues
show
Bug introduced by
The method hasManyJoinWhere() does not exist on Blasttech\EloquentRelatedPlus\JoinsTrait. Did you maybe mean hasManyJoin()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
106
        }
107
108
        return $join;
109
    }
110
111
    /**
112
     * Get the join columns for a relation
113
     *
114
     * @param Relation|BelongsTo|HasOneOrMany $relation
115
     * @return \stdClass
116
     */
117
    protected function getJoinColumns($relation)
118
    {
119
        // Get keys with table names
120
        if ($relation instanceof BelongsTo) {
121
            $first = $relation->getOwnerKey();
122
            $second = $relation->getForeignKey();
123
        } else {
124
            $first = $relation->getQualifiedParentKeyName();
125
            $second = $relation->getQualifiedForeignKeyName();
126
        }
127
128
        return (object)['first' => $first, 'second' => $second];
129
    }
130
131
    /**
132
     * Replace column table names with aliases
133
     *
134
     * @param \stdClass $joinColumns
135
     * @param \stdClass $table
136
     * @return \stdClass
137
     */
138
    protected function replaceColumnTables($joinColumns, $table)
139
    {
140
        if ($table->name !== $table->alias) {
141
            $joinColumns->first = str_replace($table->name, $table->alias, $joinColumns->first);
142
            $joinColumns->second = str_replace($table->name, $table->alias, $joinColumns->second);
143
        }
144
145
        return $joinColumns;
146
    }
147
}
148