Marcel Völkel пре 5 година
комит
a32978189f
7 измењених фајлова са 587 додато и 0 уклоњено
  1. 1
    0
      .gitignore
  2. 6
    0
      README.md
  3. 21
    0
      composer.json
  4. 27
    0
      src/Database.php
  5. 275
    0
      src/QueryBuilder.php
  6. 47
    0
      src/QueryFilter.php
  7. 210
    0
      src/SQLBuilder.php

+ 1
- 0
.gitignore Прегледај датотеку

@@ -0,0 +1 @@
1
+.idea

+ 6
- 0
README.md Прегледај датотеку

@@ -0,0 +1,6 @@
1
+<h1>Simple DBAL</h1>
2
+Ein Simpler Database Abstraction Layer der eine rudimentäre funktionalität bietet.
3
+Dieser DBAL ermöglicht es Datenbank Queries zu erzeugen ohne SQL Code direkt im eigenen Code zu schreiben.
4
+
5
+<br /><br />
6
+Eine genaue erklärung wird hier noch folgen ^^

+ 21
- 0
composer.json Прегледај датотеку

@@ -0,0 +1,21 @@
1
+{
2
+    "name": "scavenger/simple-dbal",
3
+    "version": "0.2.0",
4
+    "description": "A Simple Database Abstraction Layer with a few simple Classes to prevent writing raw SQL in your Code",
5
+    "type": "library",
6
+    "authors": [
7
+        {
8
+            "name": "Marcel Voelkel",
9
+            "email": "m.voelkel@scav-media.com"
10
+        }
11
+    ],
12
+    "minimum-stability": "dev",
13
+    "require": {
14
+        "php": ">=7.1"
15
+    },
16
+    "autoload": {
17
+        "psr-0": {
18
+            "SimpleDBAL": "src/"
19
+        }
20
+    }
21
+}

+ 27
- 0
src/Database.php Прегледај датотеку

@@ -0,0 +1,27 @@
1
+<?php
2
+
3
+namespace SimpleDBAL;
4
+
5
+use PDO;
6
+use PDOException;
7
+
8
+class Database extends PDO {
9
+    private $db;
10
+
11
+    private $stmt;
12
+
13
+    /**
14
+     * Database constructor.
15
+     * @param array $config
16
+     */
17
+    public function __construct($config)
18
+    {
19
+        $dsn = $config['dbext']. ":host=".$config['dbhost'].";dbname=".$config['dbname'].";charset=".$config['dbchar'];
20
+
21
+        try {
22
+             parent::__construct($dsn, $config['dbuser'], $config['dbpass']);
23
+        } catch (PDOException $e) {
24
+            print($e);
25
+        }
26
+    }
27
+}

+ 275
- 0
src/QueryBuilder.php Прегледај датотеку

@@ -0,0 +1,275 @@
1
+<?php
2
+
3
+namespace SimpleDBAL;
4
+
5
+
6
+class QueryBuilder
7
+{
8
+
9
+    private $db;
10
+
11
+    private $select = [];
12
+
13
+    private $table = null;
14
+
15
+    private $values = [];
16
+
17
+    private $where = [];
18
+
19
+    private $orderBy = [];
20
+
21
+    private $join = [];
22
+
23
+    private $paramters = [];
24
+
25
+    private $groupBy = null;
26
+
27
+    private $qType;
28
+
29
+    public const IS_SELECT = 1;
30
+    public const IS_INSERT = 2;
31
+    public const IS_UPDATE = 3;
32
+    public const IS_DELETE = 4;
33
+    public const IS_TRUNCATE = 5;
34
+
35
+    public function __construct(Database $db)
36
+    {
37
+        $this->db = $db;
38
+    }
39
+
40
+    public function Execute($fetchArray = false)
41
+    {
42
+        echo var_dump(SQLBuilder::Build($this));
43
+        $query = $this->db->prepare(SQLBuilder::Build($this));
44
+        if ($this->paramters) {
45
+            foreach ($this->paramters as $paraKey => $paraValue) {
46
+                $query->bindValue($paraKey, $paraValue);
47
+            }
48
+        }
49
+        $query->execute();
50
+            if ($query->rowCount() > 1 || $fetchArray == true) {
51
+                return $query->fetchAll($this->db::FETCH_ASSOC);
52
+            } else {
53
+                return $query->fetch($this->db::FETCH_ASSOC);
54
+            }
55
+    }
56
+
57
+    public function Reset()
58
+    {
59
+        $this->select = [];
60
+        $this->table = null;
61
+        $this->values = [];
62
+        $this->where = [];
63
+        $this->orderBy = [];
64
+        $this->join = [];
65
+        $this->paramters = [];
66
+        $this->groupBy = null;
67
+    }
68
+
69
+    /**
70
+     * Nötig für ein SELECT Query. Speichert in einem Array die benötigten Felder des SQL Statements
71
+     * @param mixed ...$select
72
+     * @return QueryBuilder
73
+     */
74
+    public function Select(...$select): QueryBuilder
75
+    {
76
+        foreach ($select as $item)
77
+            $this->select[] = $item;
78
+        $this->qType = self::IS_SELECT;
79
+        return $this;
80
+    }
81
+
82
+    /**
83
+     * Nötig für ein UPDATE Query. Speichert in einem Array die benötigten Felder des SQL Statements
84
+     * @param array $update
85
+     * @return QueryBuilder
86
+     */
87
+    public function Update(array $update): QueryBuilder
88
+    {
89
+        $this->select = $update;
90
+        $this->qType = self::IS_UPDATE;
91
+        return $this;
92
+    }
93
+
94
+    /**
95
+     * Nötig für einen INSERT Query. Speichert in einem Array die nötigen felder des SQL Statements
96
+     * @param array $insert
97
+     * @return QueryBuilder
98
+     */
99
+    public function Insert(array $insert): QueryBuilder
100
+    {
101
+        $this->select = $insert;
102
+        $this->qType = self::IS_INSERT;
103
+        return $this;
104
+    }
105
+
106
+    /**
107
+     * Nötig für ein DELETE Query.
108
+     * @return QueryBuilder
109
+     */
110
+    public function Delete(): QueryBuilder
111
+    {
112
+        $this->qType = self::IS_DELETE;
113
+        return $this;
114
+    }
115
+
116
+    public function Truncate(): QueryBuilder
117
+    {
118
+        $this->qType = self::IS_TRUNCATE;
119
+        return $this;
120
+    }
121
+
122
+    /**
123
+     * Nötig um die Tabelle der Datenbank auszuwählen die benötigt wird
124
+     * @param string $table
125
+     * @return QueryBuilder
126
+     */
127
+    public function Table(string $table): QueryBuilder
128
+    {
129
+        $this->table = $table;
130
+        return $this;
131
+    }
132
+
133
+    public function InsertValues(array $insertValues): QueryBuilder
134
+    {
135
+        $this->values = $insertValues;
136
+        return $this;
137
+    }
138
+
139
+    /**
140
+     * Nötig wenn man auf eine andere Tabelle Joinen möchte. Speichert
141
+     * Die nötigen Angaben in einem Array welches vom SQLBuilder verarbeitet wird.
142
+     * @param $joinType
143
+     * @param mixed ...$jArgs Following order: joinTable, joinColumn, originTable, originColumn
144
+     * @return QueryBuilder
145
+     */
146
+    public function Join($joinType, ...$jArgs): QueryBuilder
147
+    {
148
+        $this->join[$joinType] = $jArgs;
149
+        return $this;
150
+    }
151
+
152
+    /**
153
+     * Nötig für SET Angaben im UPDATE Segment eines SQL Statements.
154
+     * Nutzt das Select-Array, da während eines UPDATE keine SELECT Angaben getätigt werden
155
+     * @param $column
156
+     * @param $value
157
+     * @return QueryBuilder
158
+     */
159
+    public function Set(string $column, $value): QueryBuilder
160
+    {
161
+        $this->select[$column] = $value;
162
+        return $this;
163
+    }
164
+
165
+    /**
166
+     * Nötig für WHERE Teil des SQL Statements. Speichert die Angaben in dem Array $this->where für weitere Verarbeitung
167
+     * @param $column
168
+     * @param $value
169
+     * @param string $operator
170
+     * @return QueryBuilder
171
+     */
172
+    public function Where($column, $value, $operator = "="): QueryBuilder
173
+    {
174
+        $this->where[] = (new QueryFilter($column, $value))->setOperator($operator);
175
+        return $this;
176
+    }
177
+
178
+    /**
179
+     * Angabe nach welchen Spalten sortiert werden soll
180
+     * @param $order
181
+     * @param bool $desc
182
+     * @return QueryBuilder
183
+     */
184
+    public function OrderBy($order, bool $desc = false): QueryBuilder
185
+    {
186
+        if (is_array($order)) {
187
+            foreach ($order as $column => $desc) {
188
+                if (is_bool($desc))
189
+                    $this->orderBy[$column] = $desc;
190
+                else
191
+                    $this->orderBy[$desc] = false;
192
+            }
193
+        } else {
194
+            $this->orderBy[$order] = $desc;
195
+        }
196
+        return $this;
197
+    }
198
+
199
+    public function GroupBy($value)
200
+    {
201
+        $this->groupBy = $value;
202
+        return $this;
203
+    }
204
+
205
+    public function setParameter($param, $value)
206
+    {
207
+        $this->paramters[$param] = $value;
208
+        return $this;
209
+    }
210
+
211
+    /**
212
+     * @return array
213
+     */
214
+    public function getSelect(): array
215
+    {
216
+        return $this->select;
217
+    }
218
+
219
+    /**
220
+     * @return null
221
+     */
222
+    public function getTable()
223
+    {
224
+        return $this->table;
225
+    }
226
+
227
+    /**
228
+     * @return array
229
+     */
230
+    public function getValues(): array
231
+    {
232
+        return $this->values;
233
+    }
234
+
235
+    /**
236
+     * @return array
237
+     */
238
+    public function getWhere(): array
239
+    {
240
+        return $this->where;
241
+    }
242
+
243
+    /**
244
+     * @return array
245
+     */
246
+    public function getJoin(): array
247
+    {
248
+        return $this->join;
249
+    }
250
+
251
+    /**
252
+     * @return array
253
+     */
254
+    public function getOrderBy(): array
255
+    {
256
+        return $this->orderBy;
257
+    }
258
+
259
+    /**
260
+     * @return string
261
+     */
262
+    public function getGroupBy()
263
+    {
264
+        return $this->groupBy;
265
+    }
266
+
267
+    /**
268
+     * @return mixed
269
+     */
270
+    public function getQType()
271
+    {
272
+        return $this->qType;
273
+    }
274
+
275
+}

+ 47
- 0
src/QueryFilter.php Прегледај датотеку

@@ -0,0 +1,47 @@
1
+<?php
2
+
3
+namespace SimpleDBAL;
4
+
5
+class QueryFilter {
6
+
7
+    private $column;
8
+    private $value;
9
+    private $operator = "=";
10
+
11
+    public function __construct(string $column, $value)
12
+    {
13
+        $this->column = $column;
14
+        $this->value = $value;
15
+    }
16
+
17
+    public function setOperator(string $operator): QueryFilter
18
+    {
19
+        $this->operator = $operator;
20
+        return $this;
21
+    }
22
+
23
+    /**
24
+     * @return string
25
+     */
26
+    public function getOperator(): string
27
+    {
28
+        return $this->operator;
29
+    }
30
+
31
+    /**
32
+     * @return string
33
+     */
34
+    public function getColumn(): string
35
+    {
36
+        return $this->column;
37
+    }
38
+
39
+    /**
40
+     * @return mixed
41
+     */
42
+    public function getValue()
43
+    {
44
+        return $this->value;
45
+    }
46
+
47
+}

+ 210
- 0
src/SQLBuilder.php Прегледај датотеку

@@ -0,0 +1,210 @@
1
+<?php
2
+
3
+namespace SimpleDBAL;
4
+
5
+
6
+abstract class SQLBuilder
7
+{
8
+
9
+    private static function Quote($value, string $quote = "'")
10
+    {
11
+        if(strpos($value, "COUNT") !== false && strpos($value, "`") === false || $value == "NOW()") {
12
+            $output = $value;
13
+        } else {
14
+            $output = (is_numeric($value) ? $value : ($value[0] == ":" && !strpos($value, "`") ? $value : $quote . $value . $quote));
15
+        }
16
+        return $output;
17
+    }
18
+
19
+    public static function Build(QueryBuilder $query)
20
+    {
21
+        switch ($query->getQType()) {
22
+            case QueryBuilder::IS_SELECT:
23
+                return self::GenerateSelect($query);
24
+                break;
25
+            case QueryBuilder::IS_UPDATE:
26
+                return self::GenerateUpdate($query);
27
+                break;
28
+            case QueryBuilder::IS_INSERT:
29
+                return self::GenerateInsert($query);
30
+                break;
31
+            case QueryBuilder::IS_TRUNCATE:
32
+                return self::GenerateTruncate($query);
33
+                break;
34
+            case QueryBuilder::IS_DELETE:
35
+                return self::GenerateDelete($query);
36
+                break;
37
+
38
+        }
39
+    }
40
+
41
+
42
+    /**
43
+     * Generiert einen mit Kommata getrennten String
44
+     * @param array $list
45
+     * @param string $quote
46
+     * @return string
47
+     */
48
+    private static function generateListItems(array $list, string $quote = "'")
49
+    {
50
+        $out = "";
51
+        foreach ($list as $item)
52
+            $out .= self::Quote($item, $quote) . ", ";
53
+
54
+        return rtrim($out, ", ");
55
+    }
56
+
57
+    /**
58
+     * Erzeugt eine Liste aus Schlüsseln und Werten
59
+     * @param array $list
60
+     * @param string $operator
61
+     * @param string $seperator
62
+     * @return string
63
+     */
64
+    private static function KeyValues(array $list, string $operator = " = ", string $seperator = ", ")
65
+    {
66
+        $out = "";
67
+        foreach ($list as $key => $value)
68
+            $out .= self::Quote($key, "`") . $operator . self::Quote($value, "'");
69
+
70
+        return rtrim($out, $seperator);
71
+    }
72
+
73
+    /**
74
+     * Erzeugt einen gültigen String für eine SELECT-Ausgabe eines SQL Statements
75
+     * @param array $columns
76
+     * @return string
77
+     */
78
+    private static function SelectConstruct(array $columns): string
79
+    {
80
+        return (count($columns) > 0) ? self::generateListItems($columns, "`") : "*";
81
+    }
82
+
83
+    private static function InsertConstruct(array $columns): string
84
+    {
85
+        return (count($columns) > 0) ? self::generateListItems($columns, "`") : "";
86
+    }
87
+
88
+    private static function ValueConstruct(array $values): string
89
+    {
90
+        return self::generateListItems($values);
91
+    }
92
+
93
+    private static function JoinConstruct(array $joins): string
94
+    {
95
+        $outJoin = "";
96
+        foreach ($joins as $key => $value)
97
+            $outJoin .= $key . " JOIN " . $value[0] . " ON `" . $value[0] . "`.`" . $value[1] . "` = `" . $value[2] . "`.`" . $value[3] . "`";
98
+
99
+        return $outJoin;
100
+    }
101
+
102
+    /**
103
+     * Erzeugt einen gültigen String für eine WHERE-Ausgabe eines SQL Statements
104
+     * @param array $where
105
+     * @return string
106
+     */
107
+    private static function WhereConstruct(array $where): string
108
+    {
109
+        if (count($where) === 0)
110
+            return "";
111
+
112
+        $out = "";
113
+        foreach ($where as $item) {
114
+            if($item->getOperator() == "BETWEEN") {
115
+                $values = explode("#", $item->getValue());
116
+                $out .= "`".$item->getColumn()."` ". $item->getOperator(). " " . self::Quote($values[0], "") ." AND ". self::Quote($values[1], "") ." AND ";
117
+            }
118
+            else {
119
+                $out .= "`" . $item->getColumn() . "` " . $item->getOperator() . " " . self::Quote($item->getValue()) . " AND ";
120
+            }
121
+        }
122
+
123
+        return rtrim($out, " AND ");
124
+    }
125
+
126
+    /**
127
+     * Erzeugt das ORDER BY anhand eines Arrays das die Spaltennahmen als Array-Schlüssel und den boolischen Wert als Value enthält
128
+     * True = Descending; False = Ascending;
129
+     * @param array $orderBy
130
+     * @return string
131
+     */
132
+    private static function OrderByConstruct(array $orderBy): string
133
+    {
134
+        if (count($orderBy) === 0)
135
+            return "";
136
+
137
+        $orderCols = [];
138
+        foreach ($orderBy as $cols => $order)
139
+            $orderCols[] = "`{$cols}`" . ($order === true ? " DESC" : "");
140
+
141
+        return " ORDER BY " . self::generateListItems($orderCols, "");
142
+    }
143
+
144
+    /**
145
+     * Erzeugt den GROUP BY Part des SQL Statements
146
+     * @param $groupBy
147
+     * @return string
148
+     */
149
+    private static function GroupByConstruct($groupBy): string
150
+    {
151
+        return " GROUP BY " . $groupBy;
152
+    }
153
+
154
+    /**
155
+     * Erzeugt ein SELECT Statement welches mit JOINs, WHEREs, GROUP BYs und ORDER BYs erstellt wird
156
+     * @param QueryBuilder $query
157
+     * @return string
158
+     */
159
+    private static function GenerateSelect(QueryBuilder $query): string
160
+    {
161
+        return "SELECT " . self::SelectConstruct($query->getSelect()) . " FROM " . $query->getTable() .
162
+            (!empty($query->getJoin()) ? " " . self::JoinConstruct($query->getJoin()) : "") .
163
+            (!empty($query->getWhere()) ? " WHERE " . self::WhereConstruct($query->getWhere()) : "") .
164
+            (!empty($query->getGroupBy()) ? self::GroupByConstruct($query->getGroupBy()) : "") .
165
+            (!empty($query->getOrderBy()) ? self::OrderByConstruct($query->getOrderBy()) : "");
166
+    }
167
+
168
+    /**
169
+     * Erzeugt ein UPDATE Statement
170
+     * @param QueryBuilder $query
171
+     * @return string
172
+     */
173
+    private static function GenerateUpdate(QueryBuilder $query): string
174
+    {
175
+        return "UPDATE " . $query->getTable() . " SET " . self::KeyValues($query->getSelect(), " = ", ",") .
176
+            " WHERE " . self::WhereConstruct($query->getWhere());
177
+    }
178
+
179
+    /**
180
+     * Erzeugt ein INSERT INTO Statement
181
+     * @param QueryBuilder $query
182
+     * @return string
183
+     */
184
+    private static function GenerateInsert(QueryBuilder $query): string
185
+    {
186
+        return "INSERT INTO " . $query->getTable() . " (" . self::InsertConstruct($query->getSelect()) . ") VALUES (" . self::ValueConstruct($query->getValues()) . ")";
187
+    }
188
+
189
+    /**
190
+     * Erzeugt ein TRUNCATE TABLE Statement
191
+     * @param QueryBuilder $query
192
+     * @return string
193
+     */
194
+    private function GenerateTruncate(QueryBuilder $query): string
195
+    {
196
+        return "TRUNCATE TABLE ".$query->getTable();
197
+    }
198
+
199
+    /**
200
+     * Erzeugt ein DELETE FROM Statement
201
+     * @param QueryBuilder $query
202
+     * @return string
203
+     */
204
+    private function GenerateDelete(QueryBuilder $query): string
205
+    {
206
+        return "DELETE FROM ". $query->getTable() . " WHERE " . self::WhereConstruct($query->getWhere());
207
+    }
208
+
209
+
210
+}

Loading…
Откажи
Сачувај