|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace CoffeeCode\DataLayer; |
|
4
|
|
|
|
|
5
|
|
|
trait CrudTrait |
|
6
|
|
|
{ |
|
7
|
|
|
protected function create(array $data): ?int |
|
8
|
|
|
{ |
|
9
|
|
|
try { |
|
10
|
|
|
$columns = implode(", ", array_keys($data)); |
|
11
|
|
|
$values = ":" . implode(", :", array_keys($data)); |
|
12
|
|
|
|
|
13
|
|
|
$stmt = Connect::getInstance()->prepare("INSERT INTO {$this->entity} ({$columns}) VALUES ({$values})"); |
|
14
|
|
|
$stmt->execute($this->filter($data)); |
|
15
|
|
|
|
|
16
|
|
|
return Connect::getInstance()->lastInsertId(); |
|
|
|
|
|
|
17
|
|
|
} catch (\PDOException $exception) { |
|
18
|
|
|
$this->fail = $exception; |
|
|
|
|
|
|
19
|
|
|
return null; |
|
20
|
|
|
} |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
protected function update(array $data, string $terms, string $params): ?int |
|
24
|
|
|
{ |
|
25
|
|
|
try { |
|
26
|
|
|
$dateSet = []; |
|
27
|
|
|
foreach ($data as $bind => $value) { |
|
28
|
|
|
$dateSet[] = "{$bind} = :{$bind}"; |
|
29
|
|
|
} |
|
30
|
|
|
$dateSet = implode(", ", $dateSet); |
|
31
|
|
|
parse_str($params, $params); |
|
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
$stmt = Connect::getInstance()->prepare("UPDATE {$this->entity} SET {$dateSet} WHERE {$terms}"); |
|
34
|
|
|
$stmt->execute($this->filter(array_merge($data, $params))); |
|
35
|
|
|
return ($stmt->rowCount() ?? 1); |
|
36
|
|
|
} catch (\PDOException $exception) { |
|
37
|
|
|
$this->fail = $exception; |
|
|
|
|
|
|
38
|
|
|
return null; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public function delete(string $terms, ?string $params): bool |
|
43
|
|
|
{ |
|
44
|
|
|
try { |
|
45
|
|
|
$stmt = Connect::getInstance()->prepare("DELETE FROM {$this->entity} WHERE {$terms}"); |
|
46
|
|
|
if ($params) { |
|
47
|
|
|
parse_str($params, $params); |
|
|
|
|
|
|
48
|
|
|
$stmt->execute($params); |
|
49
|
|
|
return true; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$stmt->execute(); |
|
53
|
|
|
return true; |
|
54
|
|
|
} catch (\PDOException $exception) { |
|
55
|
|
|
$this->fail = $exception; |
|
|
|
|
|
|
56
|
|
|
return false; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
private function filter(array $data): ?array |
|
61
|
|
|
{ |
|
62
|
|
|
$filter = []; |
|
63
|
|
|
foreach ($data as $key => $value) { |
|
64
|
|
|
$filter[$key] = (is_null($value) ? null : filter_var($value, FILTER_DEFAULT)); |
|
65
|
|
|
} |
|
66
|
|
|
return $filter; |
|
67
|
|
|
} |
|
68
|
|
|
} |