126 lines
3.1 KiB
PHP
126 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace Kletellier\PdoWrapper;
|
|
|
|
class Model
|
|
{
|
|
protected mixed $values;
|
|
protected array $updated;
|
|
protected string $table;
|
|
protected string $connection = "";
|
|
protected string $pk;
|
|
private bool $new;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->new = true;
|
|
$this->values = array();
|
|
$this->updated = array();
|
|
$this->pk = "id";
|
|
$this->table = $this->getDefaultTableName();
|
|
}
|
|
|
|
public function getTable(): string
|
|
{
|
|
return $this->table;
|
|
}
|
|
|
|
public function setTable(string $table): self
|
|
{
|
|
$this->table = $table;
|
|
return $this;
|
|
}
|
|
|
|
public function getPk(): string
|
|
{
|
|
return $this->pk;
|
|
}
|
|
|
|
public function setPk(string $pk): self
|
|
{
|
|
$this->pk = $pk;
|
|
return $this;
|
|
}
|
|
|
|
public function getConnection()
|
|
{
|
|
return $this->connection;
|
|
}
|
|
|
|
public function setConnection($connection)
|
|
{
|
|
$this->connection = $connection;
|
|
return $this;
|
|
}
|
|
|
|
public function fillData(mixed $data): self
|
|
{
|
|
$this->values = $data;
|
|
$this->new = false;
|
|
$this->updated = [];
|
|
return $this;
|
|
}
|
|
|
|
public function save(): bool
|
|
{
|
|
$ret = false;
|
|
$qb = $this->newQueryBuilder();
|
|
if ($this->new) {
|
|
$query = $qb->getPreparedQuery($this->values);
|
|
$id = Connection::getInstance($this->connection)->insertQuery($query);
|
|
if ($id !== false) {
|
|
$this->values[$this->pk] = $id;
|
|
$this->new = false;
|
|
$ret = true;
|
|
}
|
|
} else {
|
|
if (isset($this->values[$this->pk])) {
|
|
if (count($this->updated) > 0) {
|
|
$data = [];
|
|
$data[$this->pk] = $this->values[$this->pk];
|
|
foreach ($this->updated as $updatecol) {
|
|
$data[$updatecol] = $this->values[$updatecol];
|
|
}
|
|
$query = $qb->getPreparedQuery($data, false);
|
|
$ret = Connection::getInstance($this->connection)->updateQuery($query);
|
|
if ($ret) {
|
|
$this->updated = [];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return $ret;
|
|
}
|
|
|
|
public function newQueryBuilder(): QueryBuilder
|
|
{
|
|
return new QueryBuilder($this->table, $this->pk, $this->connection);
|
|
}
|
|
|
|
public function __set($name, $value): void
|
|
{
|
|
$this->values[$name] = $value;
|
|
if (!$this->new && !in_array($name, $this->updated)) {
|
|
$this->updated[] = $name;
|
|
}
|
|
}
|
|
|
|
public function __get($name): mixed
|
|
{
|
|
if (isset($this->values[$name])) {
|
|
return $this->values[$name];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private function getDefaultTableName(): string
|
|
{
|
|
$className = get_class($this);
|
|
$classNameParts = explode('\\', $className);
|
|
$classNameWithoutNamespace = end($classNameParts);
|
|
$table = strtolower($classNameWithoutNamespace);
|
|
|
|
return $table;
|
|
}
|
|
}
|