Passed
Push — main ( 57964c...ed3d7a )
by Jonas
04:22
created

HasEagerLimit::addGroupLimit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 21
ccs 11
cts 11
cp 1
rs 9.9
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Eloquent\Relations\Traits;
4
5
use Illuminate\Database\Query\Expression;
6
use RuntimeException;
7
use Staudenmeir\EloquentEagerLimit\Relations\HasLimit;
8
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\MySqlGrammar;
9
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\PostgresGrammar;
10
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\SQLiteGrammar;
11
12
trait HasEagerLimit
13
{
14
    use HasLimit;
15
16
    /**
17
     * Add group limit.
18
     *
19
     * @param int $value
20
     * @return void
21
     */
22 32
    protected function addGroupLimit($value)
23
    {
24 32
        $grammar = $this->getEagerLimitGrammar();
25
26 32
        $sql = $grammar->compileFirstPathSegment(
27 32
            $this->related->qualifyColumn(
28 32
                $this->related->getPathName()
29
            )
30
        );
31
32 32
        $column = new Expression($sql);
33
34 32
        $this->query->groupLimit($value, $column);
35
36 32
        $this->query->getQuery()->addBinding(
37 32
            array_fill(
38
                0,
39 32
                substr_count($sql, '?'),
40 32
                $this->related->getPathSeparator()
41
            ),
42
            'groupBy'
43
        );
44
    }
45
46
    /**
47
     * Get the eager limit grammar.
48
     *
49
     * @return \Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\EagerLimitGrammar
50
     */
51 32
    protected function getEagerLimitGrammar()
52
    {
53 32
        $connection = $this->query->getQuery()->getConnection();
54 32
        $driver = $connection->getDriverName();
55
56 32
        switch ($driver) {
57 32
            case 'mysql':
58 16
                return $connection->withTablePrefix(
59 16
                    new MySqlGrammar()
60
                );
61 16
            case 'pgsql':
62 8
                return $connection->withTablePrefix(
63 8
                    new PostgresGrammar()
64
                );
65 8
            case 'sqlite':
66 8
                return $connection->withTablePrefix(
67 8
                    new SQLiteGrammar()
68
                );
69
        }
70
71
        throw new RuntimeException('This database is not supported.'); // @codeCoverageIgnore
72
    }
73
}
74