HasEagerLimit   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 26
c 1
b 0
f 0
dl 0
loc 60
ccs 32
cts 32
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getEagerLimitGrammar() 0 21 4
A addGroupLimit() 0 21 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\EagerLimitGrammar;
9
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\MySqlGrammar;
10
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\PostgresGrammar;
11
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\SQLiteGrammar;
12
13
trait HasEagerLimit
14
{
15
    use HasLimit;
16
17
    /**
18
     * Add group limit.
19
     *
20
     * @param int $value
21
     * @return void
22
     */
23 32
    protected function addGroupLimit(int $value): void
24
    {
25 32
        $grammar = $this->getEagerLimitGrammar();
26
27 32
        $sql = $grammar->compileFirstPathSegment(
28 32
            $this->related->qualifyColumn(
29 32
                $this->related->getPathName()
30 32
            )
31 32
        );
32
33 32
        $column = new Expression($sql);
34
35 32
        $this->query->groupLimit($value, $column);
36
37 32
        $this->query->getQuery()->addBinding(
38 32
            array_fill(
39 32
                0,
40 32
                substr_count($sql, '?'),
41 32
                $this->related->getPathSeparator()
42 32
            ),
43 32
            'select'
44 32
        );
45
    }
46
47
    /**
48
     * Get the eager limit grammar.
49
     *
50
     * @return \Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Query\Grammars\EagerLimitGrammar
51
     */
52 40
    protected function getEagerLimitGrammar(): EagerLimitGrammar
53
    {
54 40
        $connection = $this->query->getQuery()->getConnection();
55 40
        $driver = $connection->getDriverName();
56
57
        switch ($driver) {
58 40
            case 'mysql':
59 20
                return $connection->withTablePrefix(
60 20
                    new MySqlGrammar()
61 20
                );
62 20
            case 'pgsql':
63 10
                return $connection->withTablePrefix(
64 10
                    new PostgresGrammar()
65 10
                );
66 10
            case 'sqlite':
67 10
                return $connection->withTablePrefix(
68 10
                    new SQLiteGrammar()
69 10
                );
70
        }
71
72
        throw new RuntimeException('This database is not supported.'); // @codeCoverageIgnore
73
    }
74
}
75