16 $this->sql = trim(
$sql);
18 if (empty($this->sql)) {
19 $this->markInvalid(
"SQL-Statement darf nicht leer sein.");
23 if (preg_match(
'/^\s*(SELECT|DELETE|INSERT|UPDATE)\b/i', $this->sql, $matches)) {
24 $this->type = strtoupper($matches[1]);
26 $this->markInvalid(
"Unbekannter oder nicht unterstützter SQL-Typ.");
31 switch ($this->type) {
43 $this->where = $this->extractClause(
'WHERE');
44 $this->orderBy = $this->extractClause(
'ORDER BY');
45 $this->groupBy = $this->extractClause(
'GROUP BY');
46 $this->extractLimitAndOffset();
47 }
catch (Exception $e) {
48 $this->markInvalid($e->getMessage());
52 private function markInvalid($message) {
53 $this->isValid =
false;
54 $this->type =
'UNKNOWN';
63 error_log(
"SQL Analyzer Fehler: $message");
66 private function parseInsert() {
67 if (preg_match(
'/INSERT\s+INTO\s+([^\s(]+)(?:\s*\((.*?)\))?\s*VALUES\s*\((.*?)\)/i', $this->sql, $matches)) {
68 $this->table = $matches[1];
69 $this->fields = $matches[2] ??
'';
70 $this->values = $matches[3];
72 throw new InvalidArgumentException(
"Ungültige INSERT-Syntax.");
76 private function parseDelete() {
77 if (preg_match(
'/DELETE\s+FROM\s+([^\s]+)/i', $this->sql, $matches)) {
78 $this->table = $matches[1];
80 throw new InvalidArgumentException(
"Ungültige DELETE-Syntax.");
84 private function parseSelect() {
85 if (preg_match(
'/SELECT\s+(.*?)\s+FROM\s+([^\s]+)/i', $this->sql, $matches)) {
86 $this->fields = $matches[1];
87 $this->table = $matches[2];
89 throw new InvalidArgumentException(
"Ungültige SELECT-Syntax.");
93 private function extractClause($clause) {
94 if (preg_match(
"/\b$clause\b\s+(.*?)(?=\b(ORDER BY|GROUP BY|LIMIT|OFFSET|$))/i", $this->sql, $matches)) {
95 return trim($matches[1]);
100 private function extractLimitAndOffset() {
101 if (preg_match(
'/\bLIMIT\b\s+(\d+)(?:\s+\bOFFSET\b\s+(\d+))?/i', $this->sql, $matches)) {
102 $this->limit = (int) ($matches[1] ?? 100);
103 $this->offset = (int) ($matches[2] ?? 0);
107 private function getValue($property, $default) {
108 return $property !==
'' ? $property : $default;
111 public function getType($default =
'UNKNOWN') {
112 return $this->getValue($this->type, $default);
116 return $this->getValue($this->fields, $default);
120 return $this->getValue($this->table, $default);
124 return $this->getValue($this->where, $default);
128 return $this->getValue($this->orderBy, $default);
132 return $this->getValue($this->groupBy, $default);
136 return (
int) $this->getValue($this->limit, $default);
140 return (
int) $this->getValue($this->offset, $default);