1<?php
2
3
4namespace ComboStrap;
5
6
7use Antlr\Antlr4\Runtime\CommonTokenStream;
8use Antlr\Antlr4\Runtime\Error\Listeners\DiagnosticErrorListener;
9use Antlr\Antlr4\Runtime\InputStream;
10use Antlr\Antlr4\Runtime\Tree\ParseTreeWalker;
11use ComboStrap\PageSqlParser\PageSqlLexer;
12use ComboStrap\PageSqlParser\PageSqlParser;
13
14
15require_once(__DIR__ . '/PluginUtility.php');
16
17class PageSql
18{
19    const CANONICAL = "sql";
20
21    private $sql;
22    /**
23     * @var PageSqlTreeListener
24     */
25    private $listener;
26
27
28
29    public function __construct($text)
30    {
31        $this->sql = $text;
32    }
33
34    public static function create(string $string): PageSql
35    {
36        $parser = new PageSql($string);
37        $parser->parse();
38        return $parser;
39    }
40
41    function parse(): PageSql
42    {
43        $input = InputStream::fromString($this->sql);
44        $lexer = new PageSqlLexer($input);
45        $tokens = new CommonTokenStream($lexer);
46        $parser = new PageSqlParser($tokens);
47        $parser->addErrorListener(new DiagnosticErrorListener());
48        $parser->setBuildParseTree(true);
49        $tree = $parser->pageSql();
50
51        /**
52         * Performs a walk on the given parse tree starting at the root
53         * and going down recursively with depth-first search.
54         */
55        $this->listener = new PageSqlTreeListener($lexer, $parser,$this->sql);
56        ParseTreeWalker::default()->walk($this->listener, $tree);
57        return $this;
58    }
59
60    public function getExecutableSql(): string
61    {
62        return $this->listener->getPhysicalSql();
63    }
64
65    public function getParameters(): array
66    {
67        return $this->listener->getParameters();
68    }
69
70    public function getColumns(): array
71    {
72        return $this->listener->getColumns();
73    }
74
75    public function __toString()
76    {
77        return $this->sql;
78    }
79
80}
81