commit | author | age
|
766451
|
1 |
<?php |
F |
2 |
namespace Framework; |
|
3 |
|
|
4 |
use App\Database; |
|
5 |
use PDO; |
|
6 |
abstract class Model |
|
7 |
{ |
4dbbdf
|
8 |
protected array $errors = []; |
d7a326
|
9 |
protected ?string $table; |
4dbbdf
|
10 |
|
F |
11 |
abstract protected function validate (array $data): void; |
|
12 |
|
|
13 |
public function __construct(private Database $database) { |
|
14 |
} |
|
15 |
|
bd886f
|
16 |
public function update(string $id, array $data): bool { |
F |
17 |
$this->validate($data); |
|
18 |
|
|
19 |
if(!empty($this->errors)) { |
|
20 |
return false; |
|
21 |
} |
|
22 |
|
|
23 |
return true; |
|
24 |
|
|
25 |
} |
4dbbdf
|
26 |
|
F |
27 |
protected function addError(string $field, string $message): void { |
|
28 |
$this->errors[$field] = $message; |
|
29 |
} |
|
30 |
|
|
31 |
public function getErrors(): array { |
|
32 |
return $this->errors; |
|
33 |
} |
766451
|
34 |
|
a26040
|
35 |
private function getTable() { |
F |
36 |
$parts = explode("\\", $this::class); |
|
37 |
return strtolower(array_pop($parts)); |
766451
|
38 |
} |
6704d0
|
39 |
public function getInsertID(): string { |
F |
40 |
$conn = $this->database->getConnection(); |
|
41 |
return $conn->lastInsertId(); |
|
42 |
} |
766451
|
43 |
public function findAll(): array|bool |
F |
44 |
{ |
|
45 |
$pdo = $this->database->getConnection(); |
|
46 |
|
a26040
|
47 |
$sql = "SELECT * FROM {$this->getTable()}"; |
d7a326
|
48 |
|
F |
49 |
$stmt = $pdo->query($sql); |
766451
|
50 |
|
F |
51 |
return $stmt->fetchAll(PDO::FETCH_ASSOC); |
|
52 |
} |
|
53 |
|
|
54 |
public function find(string $id) { |
|
55 |
$conn = $this->database->getConnection(); |
|
56 |
$sql = "SELECT * |
a26040
|
57 |
FROM {$this->getTable()} |
766451
|
58 |
WHERE id = :id"; |
F |
59 |
$stmt = $conn->prepare($sql); |
|
60 |
$stmt->bindValue(":id", $id, PDO::PARAM_INT); |
|
61 |
$stmt->execute(); |
|
62 |
return $stmt->fetch(PDO::FETCH_ASSOC); |
|
63 |
} |
fc5ee7
|
64 |
|
F |
65 |
public function insert(array $data) : bool { |
4dbbdf
|
66 |
$this->validate($data); |
F |
67 |
|
|
68 |
if(!empty($this->errors)) { |
7a2549
|
69 |
return false; |
F |
70 |
} |
6f90bf
|
71 |
$columns = implode(", " , array_keys($data)); |
F |
72 |
$placeholders = implode(", ", array_fill(0, count($data), "?")); |
|
73 |
|
|
74 |
$sql = "INSERT INTO {$this->getTable()} ($columns) VALUES ($placeholders)"; |
|
75 |
|
fc5ee7
|
76 |
$conn = $this->database->getConnection(); |
F |
77 |
$stmt = $conn->prepare($sql); |
b1d4d1
|
78 |
|
F |
79 |
$i = 1; |
|
80 |
foreach ($data as $value) { |
|
81 |
$type = match(gettype($value)) { |
|
82 |
"boolean" => PDO::PARAM_BOOL, |
|
83 |
"integer"=> PDO::PARAM_INT, |
|
84 |
"NULL"=> PDO::PARAM_NULL, |
|
85 |
default => PDO::PARAM_STR |
|
86 |
}; |
|
87 |
|
|
88 |
|
|
89 |
$stmt->bindValue($i++, $value, PDO::PARAM_STR); |
|
90 |
} |
|
91 |
|
fc5ee7
|
92 |
|
F |
93 |
return $stmt->execute(); |
|
94 |
} |
766451
|
95 |
} |
F |
96 |
|
|
97 |
|
|
98 |
?> |