BuilderClass::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace BigShark\SQLToBuilder;
4
5
use BigShark\SQLToBuilder\Converter\Factory;
6
use PHPSQLParser\PHPSQLParser;
7
8
class BuilderClass
9
{
10
    /**
11
     * @var string
12
     */
13
    protected $sql;
14
15
    /**
16
     * @var PHPSQLParser
17
     */
18
    protected $sqlParser;
19
20
    /**
21
     * @var Factory
22
     */
23
    protected $converterFactory;
24
25
    /**
26
     * @var Generator
27
     */
28
    protected $generator;
29
30
    /**
31
     * @param string $sql
32
     */
33 99
    public function __construct($sql)
34
    {
35 99
        $this->sql = $sql;
36 99
        $this->sqlParser = new PHPSQLParser();
37 99
        $this->converterFactory = new Factory();
38 99
        $this->generator = new Generator('DB');
39 99
    }
40
41
    /**
42
     * @throws \Exception
43
     *
44
     * @return string
45
     */
46 99
    public function convert()
47
    {
48 99
        $parsed = $this->sqlParser->parse($this->sql);
49
50 99
        if (false === $parsed) {
51 3
            throw new \Exception('SQL query is not valid');
52
        }
53
54 96
        $results = [];
55 96
        foreach ($parsed as $section => $data) {
56 96
            if ($this->converterFactory->canCreate($section)) {
57 96
                $converter = $this->converterFactory->create($section);
58 96
                $results = array_merge($results, $converter->convert($data));
59
            }
60
        }
61
62
        $table = current(array_filter($results, function ($item) {
63 96
            return 'table' === $item['name'];
64 96
        }));
65 96
        unset($results[array_search($table, $results)]);
66 96
        array_unshift($results, $table);
67
68 96
        foreach ($results as $function) {
69 96
            $args = isset($function['args']) ? $function['args'] : [];
70 96
            $this->generator->addFunction($function['name'], $args);
71
        }
72
73 96
        $this->generator->addFunction('get');
74
75 96
        return $this->generator->generate();
76
    }
77
}
78