1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MartinGeorgiev\Doctrine\ORM\Query\AST\Functions; |
6
|
|
|
|
7
|
|
|
use Doctrine\ORM\Query\AST\Functions\FunctionNode; |
8
|
|
|
use Doctrine\ORM\Query\AST\Node; |
9
|
|
|
use Doctrine\ORM\Query\Lexer; |
10
|
|
|
use Doctrine\ORM\Query\Parser; |
11
|
|
|
use Doctrine\ORM\Query\SqlWalker; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @since 0.1 |
15
|
|
|
* @author Martin Georgiev <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
abstract class BaseFunction extends FunctionNode |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
protected $functionPrototype; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var string[] |
26
|
|
|
*/ |
27
|
|
|
protected $nodesMapping = []; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var Node[] |
31
|
|
|
*/ |
32
|
|
|
protected $nodes = []; |
33
|
|
|
|
34
|
|
|
abstract protected function customiseFunction(): void; |
35
|
|
|
|
36
|
|
|
protected function setFunctionPrototype(string $functionPrototype): void |
37
|
|
|
{ |
38
|
|
|
$this->functionPrototype = $functionPrototype; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
protected function addNodeMapping(string $parserMethod): void |
42
|
|
|
{ |
43
|
|
|
$this->nodesMapping[] = $parserMethod; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function parse(Parser $parser): void |
47
|
|
|
{ |
48
|
|
|
$this->customiseFunction(); |
49
|
|
|
|
50
|
|
|
$parser->match(Lexer::T_IDENTIFIER); |
51
|
|
|
$parser->match(Lexer::T_OPEN_PARENTHESIS); |
52
|
|
|
$this->feedParserWithNodes($parser); |
53
|
|
|
$parser->match(Lexer::T_CLOSE_PARENTHESIS); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Feeds given parser with previously set nodes |
58
|
|
|
*/ |
59
|
|
|
protected function feedParserWithNodes(Parser $parser): void |
60
|
|
|
{ |
61
|
|
|
$nodesMappingCount = count($this->nodesMapping); |
62
|
|
|
$lastNode = $nodesMappingCount - 1; |
63
|
|
|
for ($i = 0; $i < $nodesMappingCount; $i++) { |
64
|
|
|
$parserMethod = $this->nodesMapping[$i]; |
65
|
|
|
$this->nodes[$i] = $parser->$parserMethod(); |
66
|
|
|
if ($i < $lastNode) { |
67
|
|
|
$parser->match(Lexer::T_COMMA); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
View Code Duplication |
public function getSql(SqlWalker $sqlWalker): string |
|
|
|
|
73
|
|
|
{ |
74
|
|
|
$dispatched = []; |
75
|
|
|
foreach ($this->nodes as $node) { |
76
|
|
|
$dispatched[] = $node->dispatch($sqlWalker); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return vsprintf($this->functionPrototype, $dispatched); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.