Passed
Push — update-dev-dependencies ( ac0b1d...13ec54 )
by Martin
04:45 queued 02:55
created

StringAgg   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 25
c 1
b 0
f 0
dl 0
loc 61
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 22 3
A getSql() 0 10 3
A customiseFunction() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MartinGeorgiev\Doctrine\ORM\Query\AST\Functions;
6
7
use Doctrine\ORM\Query\AST\Node;
8
use Doctrine\ORM\Query\AST\OrderByClause;
9
use Doctrine\ORM\Query\Lexer;
10
use Doctrine\ORM\Query\Parser;
11
use Doctrine\ORM\Query\SqlWalker;
12
13
/**
14
 * Implementation of PostgreSql STRING_AGG().
15
 *
16
 * @see https://www.postgresql.org/docs/9.5/functions-aggregate.html
17
 * @since 1.4
18
 *
19
 * @author Martin Georgiev <[email protected]>
20
 */
21
class StringAgg extends BaseFunction
22
{
23
    /**
24
     * @var bool
25
     */
26
    private $isDistinct = false;
27
28
    /**
29
     * @var Node
30
     */
31
    private $expression;
32
33
    /**
34
     * @var Node
35
     */
36
    private $delimiter;
37
38
    /**
39
     * @var OrderByClause|null
40
     */
41
    private $orderBy;
42
43
    protected function customiseFunction(): void
44
    {
45
        $this->setFunctionPrototype('string_agg(%s%s, %s%s)');
46
    }
47
48
    public function parse(Parser $parser): void
49
    {
50
        $this->customiseFunction();
51
52
        $parser->match(Lexer::T_IDENTIFIER);
53
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
54
55
        $lexer = $parser->getLexer();
56
        if ($lexer->isNextToken(Lexer::T_DISTINCT)) {
57
            $parser->match(Lexer::T_DISTINCT);
58
            $this->isDistinct = true;
59
        }
60
61
        $this->expression = $parser->StringPrimary();
62
        $parser->match(Lexer::T_COMMA);
63
        $this->delimiter = $parser->StringPrimary();
64
65
        if ($lexer->isNextToken(Lexer::T_ORDER)) {
66
            $this->orderBy = $parser->OrderByClause();
67
        }
68
69
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
70
    }
71
72
    public function getSql(SqlWalker $sqlWalker): string
73
    {
74
        $dispatched = [
75
            $this->isDistinct ? 'distinct ' : '',
76
            $this->expression->dispatch($sqlWalker),
77
            $this->delimiter->dispatch($sqlWalker),
78
            $this->orderBy ? $this->orderBy->dispatch($sqlWalker) : '',
79
        ];
80
81
        return \vsprintf($this->functionPrototype, $dispatched);
82
    }
83
}
84