-
Notifications
You must be signed in to change notification settings - Fork 2
/
YesqlParser.php
75 lines (58 loc) · 2.09 KB
/
YesqlParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace Ox\YesqlBundle;
class YesqlParser
{
public function parse($file)
{
$blocks = [];
$comment = '';
$sql = '';
$state = 'comment';
$trim = " \t\n\r\0\x0B;";
foreach (file($file) as $row) {
$isComment = strpos($row, '--') === 0;
if ($isComment) {
if ($state != 'comment' && trim($comment) && trim($sql, $trim)) {
$blocks[] = [trim($comment), trim($sql, $trim)];
$comment = '';
$sql = '';
}
$state = 'comment';
$comment .= $row;
} else {
$sql .= $row;
$state = '$sql';
}
}
if ($state != 'comment' && trim($comment) && trim($sql, $trim)) {
$blocks[] = [trim($comment), trim($sql, $trim)];
}
$queries = [];
foreach ($blocks as list ($comment, $sql)) {
$query = ['sql' => $sql];
if (!preg_match('/--\s*name:\s*(\S+)/', $comment, $matches)) {
throw new \LogicException('Query name not found: ' . $file);
}
$query['name'] = $matches[1];
if (!preg_match('/^\s*(select|insert|update|delete|with)/i', $sql, $matches)) {
throw new \LogicException('Query type not detected: ' . $file);
}
$type = strtolower($matches[1]);
if ($type == 'insert') {
$query['return'] = 'lastInsertId';
} else if ($type == 'select' || $type == 'with') {
$query['return'] = 'fetch';
} else {
$query['return'] = 'rowCount';
}
if (preg_match('/--\s*return:\s*(\S+)\s*(\S.*)?/', $comment, $matches)) {
$query['return'] = $matches[1];
if (isset($matches[2]) && preg_match_all('/(\S+)\s*/', $matches[2], $matches)) {
$query['arguments'] = $matches[1];
}
}
$queries[] = $query;
}
return $queries;
}
}