1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Keep; |
4
|
|
|
|
5
|
|
|
use PDO; |
6
|
|
|
use stdClass; |
7
|
|
|
use Exception; |
8
|
|
|
|
9
|
|
|
class Model |
10
|
|
|
{ |
11
|
|
|
public $attributes = []; |
12
|
|
|
|
13
|
|
|
public function __set($key, $value): void |
14
|
|
|
{ |
15
|
|
|
$this->attributes[$key] = $value; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function __get($key) |
19
|
|
|
{ |
20
|
|
|
if (array_key_exists($key, $this->attributes)) { |
21
|
|
|
return $this->attributes[$key]; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
return null; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public static function __callStatic($findBy, $attributes) |
28
|
|
|
{ |
29
|
|
|
$findBy = str_replace('find_by_', '', $findBy); |
30
|
|
|
|
31
|
|
|
$explode = explode('_', $findBy); |
32
|
|
|
|
33
|
|
|
$operator = $explode[1]; |
34
|
|
|
|
35
|
|
|
$obj = get_called_class(); |
36
|
|
|
$obj = new $obj; |
37
|
|
|
|
38
|
|
|
$find = DB::all(self::getTable()) |
|
|
|
|
39
|
|
|
->where(array_values(array_filter($explode))[0], $attributes[0]) |
40
|
|
|
->$operator(@array_values(array_filter($explode))[2], @$attributes[1]) |
41
|
|
|
->execute(); |
42
|
|
|
|
43
|
|
|
if ($find->rowCount() === 0) { |
44
|
|
|
return null; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
foreach ($find->fetch(PDO::FETCH_OBJ) as $key => $value) { |
48
|
|
|
$obj->$key = $value; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $obj; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function save() |
55
|
|
|
{ |
56
|
|
|
return DB::create(self::getTable(), $this->attributes)->execute(); |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public static function find(int $id) |
60
|
|
|
{ |
61
|
|
|
$obj = get_called_class(); |
62
|
|
|
$obj = new $obj; |
63
|
|
|
|
64
|
|
|
$find = DB::all(self::getTable())->where('id', $id)->execute(); |
65
|
|
|
|
66
|
|
|
if ($find->rowCount() === 0) { |
67
|
|
|
return null; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
foreach ($find->fetch(PDO::FETCH_OBJ) as $key => $value) { |
71
|
|
|
$obj->$key = $value; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $obj; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
public static function all() |
78
|
|
|
{ |
79
|
|
|
$find = DB::all(self::getTable())->execute(); |
80
|
|
|
|
81
|
|
|
if ($find) { |
82
|
|
|
return $find->fetchAll(PDO::FETCH_OBJ); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return false; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
public function delete() |
89
|
|
|
{ |
90
|
|
|
return DB::delete(self::getTable())->where('id', $this->id)->execute(); |
|
|
|
|
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
public function update() |
94
|
|
|
{ |
95
|
|
|
$attributes = $this->attributes; |
96
|
|
|
unset($attributes['id']); |
97
|
|
|
|
98
|
|
|
return DB::update(self::getTable(), $attributes)->where('id', $this->id)->execute(); |
|
|
|
|
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
private static function getTable(): string |
102
|
|
|
{ |
103
|
|
|
return strtolower(get_called_class()); |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|