aboutsummaryrefslogtreecommitdiffhomepage
path: root/WpfTest/Model.php
diff options
context:
space:
mode:
authorwinter2024-12-07 21:44:42 +0000
committerwinter2024-12-07 21:44:42 +0000
commita84232811dadccf7047424f27340a7f9847bedff (patch)
treea6a0823c8b9485b6a5b60ea7ae854f9511a6ae1e /WpfTest/Model.php
parente1ad307b531c27ec6bfaf8b4d018991b0d4a78f3 (diff)
many many changes but actors are loaded from db now
Diffstat (limited to 'WpfTest/Model.php')
-rw-r--r--WpfTest/Model.php73
1 files changed, 73 insertions, 0 deletions
diff --git a/WpfTest/Model.php b/WpfTest/Model.php
new file mode 100644
index 0000000..26a7b49
--- /dev/null
+++ b/WpfTest/Model.php
@@ -0,0 +1,73 @@
+<?php
+namespace WpfTest;
+
+abstract class Model {
+ private static function mangleName(string $name): string {
+ if ($name == 'self')
+ return 'uri';
+ $chars = str_split($name);
+ $chars[0] = strtolower($chars[0]);
+ for ($i = 0; $i < count($chars); $i++) {
+ $c = $chars[$i];
+ if (ctype_upper($c)) {
+ array_splice($chars, $i, 1, ['_', strtolower($c)]);
+ }
+ }
+ return implode($chars);
+ }
+
+ private static function unmangleName(string $name): string {
+ if ($name == 'uri')
+ return 'self';
+ $chars = str_split($name);
+ for ($i = 0; $i < count($chars); $i++) {
+ if ($chars[$i] == '_') {
+ array_splice($chars, $i, 2, [strtoupper($chars[$i + 1])]);
+ }
+ }
+ return implode($chars);
+ }
+
+ public function toDbRow(): array {
+ $refl = new \ReflectionObject($this);
+ $props = $refl->getProperties();
+ $result = [];
+ foreach ($props as $p) {
+ $result[self::mangleName($p->getName())] = $p->getValue();
+ }
+ return $result;
+ }
+
+ public static function fromDbRow(array|false $columns): ?static {
+ if ($columns === false)
+ return null;
+ $obj = new static();
+ $refl = new \ReflectionObject($obj);
+ foreach (array_keys($columns) as $name) {
+ $value = $columns[$name];
+ $name = self::unmangleName($name);
+ try {
+ $obj->{$name} = $value;
+ } catch (\TypeError $e) {
+ $type = $refl->getProperty($name)->getType();
+ if ($type == null || !is_a($type, \ReflectionNamedType::class))
+ throw $e;
+ $obj->{$name} = new ($type->getName())($value);
+ }
+ }
+ return $obj;
+ }
+
+ public static function findWhere(string $whereClause, array $parameters): ?static {
+ $classNameParts = explode('\\', static::class);
+ $className = $classNameParts[count($classNameParts) - 1];
+ $tableName = self::mangleName($className);
+ $stmt = Db::getInstance()->getPdo()->prepare("SELECT * FROM $tableName WHERE $whereClause");
+ $stmt->execute($parameters);
+ return static::fromDbRow($stmt->fetch(\PDO::FETCH_ASSOC));
+ }
+
+ public static function find(int $id): ?static {
+ return static::findWhere('id = ?', [$id]);
+ }
+} \ No newline at end of file