|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
/** |
|
3
|
|
|
* @license MIT |
|
4
|
|
|
* @author Samuel Adeshina <[email protected]> |
|
5
|
|
|
* |
|
6
|
|
|
* This file is part of the EmmetBlue project, please read the license document |
|
7
|
|
|
* available in the root level of the project |
|
8
|
|
|
*/ |
|
9
|
|
|
namespace EmmetBlue\Core\Factory; |
|
10
|
|
|
|
|
11
|
|
|
use EmmetBlue\Core\Builder\BuilderFactory as Builder; |
|
12
|
|
|
use EmmetBlue\Core\Factory\DatabaseConnectionFactory as DBConnectionFactory; |
|
13
|
|
|
use EmmetBlue\Core\Builder\QueryBuilder\QueryBuilder as QB; |
|
14
|
|
|
use EmmetBlue\Core\Exception\SQLException; |
|
15
|
|
|
use EmmetBlue\Core\Exception\UndefinedValueException; |
|
16
|
|
|
use EmmetBlue\Core\Session\Session; |
|
17
|
|
|
use EmmetBlue\Core\Logger\DatabaseLog; |
|
18
|
|
|
use EmmetBlue\Core\Logger\ErrorLog; |
|
19
|
|
|
use EmmetBlue\Core\Constant; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Class DatabaseQueryFactory. |
|
23
|
|
|
* |
|
24
|
|
|
* @author Samuel Adeshina <[email protected]> |
|
25
|
|
|
* |
|
26
|
|
|
* @since v0.0.1 08/06/2016 14:20 |
|
27
|
|
|
*/ |
|
28
|
|
|
class DatabaseQueryFactory |
|
29
|
|
|
{ |
|
30
|
|
|
public static function insert(string $table, array $data) |
|
31
|
|
|
{ |
|
32
|
|
|
$insertBuilder = (new Builder("QueryBuilder","Insert"))->getBuilder(); |
|
33
|
|
|
$columns = []; |
|
34
|
|
|
$values = []; |
|
35
|
|
|
|
|
36
|
|
|
foreach ($data as $index=>$datum) |
|
37
|
|
|
{ |
|
38
|
|
|
$columns[] = $index; |
|
39
|
|
|
$values[] = $datum; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$columns = "(".implode(", ", $columns).")"; |
|
43
|
|
|
$values = "(".implode(", ", $values).")"; |
|
44
|
|
|
$insertBuilder->into($table.$columns); |
|
45
|
|
|
|
|
46
|
|
|
$query = (string)$insertBuilder." VALUES ".$values; |
|
47
|
|
|
// die($query); |
|
48
|
|
|
try |
|
49
|
|
|
{ |
|
50
|
|
|
$parts = explode(".", $table); |
|
51
|
|
|
$schemaName = $parts[0]; |
|
52
|
|
|
$tableName = $parts[1]; |
|
53
|
|
|
|
|
54
|
|
|
$connection = DBConnectionFactory::getConnection(); |
|
55
|
|
|
|
|
56
|
|
|
$result = $connection->prepare((string)$query)->execute(); |
|
57
|
|
|
|
|
58
|
|
|
DatabaseLog::log(Session::get('USER_ID'), Constant::EVENT_INSERT, $schemaName, $tableName, $query); |
|
59
|
|
|
|
|
60
|
|
|
$lastInsertId = ($connection->query("SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) as id")->fetchColumn()); |
|
61
|
|
|
|
|
62
|
|
|
return [$result, "lastInsertId"=>$lastInsertId]; |
|
63
|
|
|
} |
|
64
|
|
|
catch (\PDOException $e) |
|
65
|
|
|
{ |
|
66
|
|
|
throw new SQLException(sprintf( |
|
67
|
|
|
"%s", |
|
68
|
|
|
$e->getMessage() |
|
69
|
|
|
), Constant::UNDEFINED); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
} |