2025-08-14 17:08:36 -04:00

67 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Models;
use function DragonKnight\db;
class Model
{
protected string $table_name = '';
protected array $original_data = [];
protected array $changes = [];
public function __construct(array $data)
{
$this->original_data = $data;
$this->changes = [];
}
public function __get(string $key): mixed
{
return array_key_exists($key, $this->changes) ? $this->changes[$key] : $this->original_data[$key] ?? false;
}
public function __set(string $key, mixed $value): void
{
if (array_key_exists($key, $this->original_data)) {
if ($value !== $this->original_data[$key]) {
$this->changes[$key] = $value;
}
} else {
throw new \InvalidArgumentException("Attempted to write to $key, which doesn't exist in the data for this model.");
}
}
public function save(): bool
{
if (empty($this->changes)) {
return true;
}
$placeholders = [];
$values = [];
foreach ($this->changes as $key => $value) {
$placeholders[] = "$key=?";
$values[] = $value;
}
$values[] = $this->id;
$query = 'UPDATE '.$this->table_name.' SET '.implode(', ', $placeholders).' WHERE id = ?;';
$result = db()->query($query, $values);
return $result === false ? false : true;
}
}