Completed
Push — master ( 33efdc...e98e88 )
by Avtandil
03:06
created

ManyToManyPreload::scopeLimitPerGroupViaUnion()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 48
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 32
nc 8
nop 3
dl 0
loc 48
ccs 0
cts 39
cp 0
crap 30
rs 8.551
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Laravel Lodash package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
declare(strict_types=1);
11
12
namespace Longman\LaravelLodash\Eloquent;
13
14
use Illuminate\Database\Eloquent\Builder;
15
use Illuminate\Database\Eloquent\Model;
16
17
/**
18
 * @mixin \Illuminate\Database\Eloquent\Model
19
 * @method $this limitPerGroupViaSubQuery(Builder $query, int $limit = 10)
20
 * @method $this limitPerGroupViaUnion(Builder $query, int $limit = 10, array $pivotColumns = [])
21
 */
22
trait ManyToManyPreload
23
{
24
    public function scopeLimitPerGroupViaSubQuery(Builder $query, int $limit = 10): Model
25
    {
26
        $table = $this->getTable();
0 ignored issues
show
Bug introduced by
It seems like getTable() 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...
27
        $queryKeyColumn = $query->getQuery()->wheres[0]['column'];
28
        $join = $query->getQuery()->joins;
29
        $newQuery = $this->newQueryWithoutScopes();
0 ignored issues
show
Bug introduced by
It seems like newQueryWithoutScopes() 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...
30
        $connection = $this->getConnection();
0 ignored issues
show
Bug introduced by
It seems like getConnection() 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...
31
32
        // Initialize MySQL variables inline
33
        $newQuery->from($connection->raw('(select @num:=0, @group:=0) as `vars`, ' . $this->quoteColumn($table)));
34
35
        // If no columns already selected, let's select *
36
        if (! $query->getQuery()->columns) {
37
            $newQuery->select($table . '.*');
38
        }
39
40
        // Make sure column aliases are unique
41
        $groupAlias = $table . '_grp';
42
        $numAlias = $table . '_rn';
43
44
        // Apply mysql variables
45
        $newQuery->addSelect($connection->raw(
46
            "@num := if(@group = {$this->quoteColumn($queryKeyColumn)}, @num+1, 1) as `{$numAlias}`, @group := {$this->quoteColumn($queryKeyColumn)} as `{$groupAlias}`"
47
        ));
48
49
        // Make sure first order clause is the group order
50
        $newQuery->getQuery()->orders = (array) $query->getQuery()->orders;
51
        array_unshift($newQuery->getQuery()->orders, [
52
            'column'    => $queryKeyColumn,
53
            'direction' => 'asc',
54
        ]);
55
56
        if ($join) {
57
            $leftKey = explode('.', $queryKeyColumn)[1];
58
            $leftKeyColumn = "`{$table}`.`{$leftKey}`";
59
            $newQuery->addSelect($queryKeyColumn);
60
            $newQuery->mergeBindings($query->getQuery());
61
            $newQuery->getQuery()->joins = (array) $query->getQuery()->joins;
62
            $query->whereRaw("{$leftKeyColumn} = {$this->quoteColumn($queryKeyColumn)}");
63
        }
64
65
        $query->from($connection->raw("({$newQuery->toSql()}) as `{$table}`"))
66
            ->where($numAlias, '<=', $limit);
67
68
        return $this;
69
    }
70
71
    private function quoteColumn(string $column): string
72
    {
73
74
        return '`' . str_replace('.', '`.`', $column) . '`';
75
    }
76
77
    public function scopeLimitPerGroupViaUnion(Builder $query, int $limit = 10, array $pivotColumns = []): Model
78
    {
79
        $table = $this->getTable();
0 ignored issues
show
Bug introduced by
It seems like getTable() 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...
80
        $queryKeyColumn = $query->getQuery()->wheres[0]['column'];
81
        $joins = $query->getQuery()->joins;
82
        $connection = $this->getConnection();
0 ignored issues
show
Bug introduced by
It seems like getConnection() 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...
83
84
        $queryKeyValues = $query->getQuery()->wheres[0]['values'];
85
        $pivotTable = explode('.', $queryKeyColumn)[0];
86
87
        $joinLeftColumn = $joins[0]->wheres[0]['first'];
88
        $joinRightColumn = $joins[0]->wheres[0]['second'];
89
        $joinOperator = $joins[0]->wheres[0]['operator'];
90
91
        foreach ($queryKeyValues as $value) {
92
            if (! isset($unionQuery1)) {
93
                $unionQuery1 = $connection->table($pivotTable)
94
                    ->select([$table . '.*'])
95
                    ->join($table, $joinLeftColumn, $joinOperator, $joinRightColumn)
96
                    ->where($queryKeyColumn, '=', $value)
97
                    ->limit($limit);
98
            } else {
99
                $select = [
100
                    $table . '.*',
101
                ];
102
103
                foreach ($pivotColumns as $pivotColumn) {
104
                    $select[] = $pivotTable . '.' . $pivotColumn . ' as pivot_' . $pivotColumn;
105
                }
106
107
                $unionQuery2 = $connection->table($pivotTable)
108
                    ->select($select)
109
                    ->join($table, $joinLeftColumn, $joinOperator, $joinRightColumn)
110
                    ->where($queryKeyColumn, '=', $value)
111
                    ->limit($limit);
112
113
                $unionQuery1->unionAll($unionQuery2);
114
            }
115
        }
116
117
        if (! isset($unionQuery1)) {
118
            throw new InvalidArgumentException('Union query does not found');
119
        }
120
121
        $query->setQuery($unionQuery1);
122
123
        return $this;
124
    }
125
}
126