Passed
Push — master ( 9b6500...1e2780 )
by Jonas
08:34
created

MySqlGrammar::compileOrderByPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 22
ccs 11
cts 11
cp 1
rs 9.8333
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Staudenmeir\LaravelAdjacencyList\Query\Grammars;
4
5
use Illuminate\Database\Query\Builder;
6
use Illuminate\Database\Query\Grammars\MySqlGrammar as Base;
7
8
class MySqlGrammar extends Base implements ExpressionGrammar
9
{
10
    use OrdersByPath;
11
12
    /**
13
     * Compile an initial path.
14
     *
15
     * @param string $column
16
     * @param string $alias
17
     * @return string
18
     */
19 132
    public function compileInitialPath($column, $alias)
20
    {
21 132
        return 'cast(' . $this->wrap($column) . ' as char(65535)) as ' . $this->wrap($alias);
22
    }
23
24
    /**
25
     * Compile a recursive path.
26
     *
27
     * @param string $column
28
     * @param string $alias
29
     * @return string
30
     */
31 132
    public function compileRecursivePath($column, $alias)
32
    {
33 132
        return 'concat(' . $this->wrap($alias) . ', ?, ' . $this->wrap($column) . ')';
34
    }
35
36
    /**
37
     * Get the recursive path bindings.
38
     *
39
     * @param string $separator
40
     * @return array
41
     */
42 132
    public function getRecursivePathBindings($separator)
43
    {
44 132
        return [$separator];
45
    }
46
47
    /**
48
     * Select a concatenated list of paths.
49
     *
50
     * @param \Illuminate\Database\Query\Builder $query
51
     * @param string $expression
52
     * @param string $column
53
     * @param string $pathSeparator
54
     * @param string $listSeparator
55
     * @return \Illuminate\Database\Query\Builder
56
     */
57 32
    public function selectPathList(Builder $query, $expression, $column, $pathSeparator, $listSeparator)
58
    {
59 32
        return $query->selectRaw(
60 32
            'group_concat(' . $this->wrap($column) . " separator '$listSeparator')"
61 32
        )->from($expression);
62
    }
63
64
    /**
65
     * Compile an "order by path" clause.
66
     *
67
     * @return string
68
     */
69 4
    public function compileOrderByPath()
70
    {
71 4
        $column = $this->model->getLocalKeyName();
72
73 4
        $path = $this->wrap(
74 4
            $this->model->getPathName()
75
        );
76
77 4
        $pathSeparator = $this->model->getPathSeparator();
78
79 4
        if (!$this->model->isIntegerAttribute($column)) {
80 1
            return "$path asc";
81
        }
82
83
        return <<<SQL
84 3
regexp_replace(
85
    regexp_replace(
86 3
        $path,
87 3
        '(^|[$pathSeparator])(\\\\d+)',
88
        '$100000000000000000000$2'
89
    ),
90 3
    '0+(\\\\d\{20\})([$pathSeparator]|$)',
91
    '$1$2'
92
) asc
93
SQL;
94
    }
95
}
96