Skip to content

Commit

Permalink
Added CreatedAt, UpdatedAt and DeletedAt
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianFun123 committed Jul 25, 2022
1 parent 52025ec commit 8018168
Show file tree
Hide file tree
Showing 14 changed files with 186 additions and 40 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ class User {

#[Column]
public ?string $description;

#[Column(sqlType: "TIMESTAMP")]
#[CreatedAt]
public ?string $createdAt;

#[Column(sqlType: "TIMESTAMP")]
#[UpdatedAt]
public ?string $updatedAt;

#[Column(sqlType: "TIMESTAMP")]
#[DeletedAt]
public ?string $deletedAt;
}
```
### example.php
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "interaapps/uloleorm",
"version": "3.1.2",
"version": "3.1.3",
"type": "library",
"authors": [
{
Expand Down
56 changes: 45 additions & 11 deletions de/interaapps/ulole/orm/ModelInformation.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
namespace de\interaapps\ulole\orm;

use de\interaapps\ulole\orm\attributes\Column;
use de\interaapps\ulole\orm\attributes\CreatedAt;
use de\interaapps\ulole\orm\attributes\DeletedAt;
use de\interaapps\ulole\orm\attributes\Identifier;
use de\interaapps\ulole\orm\attributes\Table;
use de\interaapps\ulole\orm\attributes\UpdatedAt;
use ReflectionClass;
use ReflectionException;

Expand All @@ -16,9 +20,13 @@ class ModelInformation {
* @var ColumnInformation[]
*/
private array $fields;
private ?string $name;
private ?string $name = null;
private bool $disableAutoMigrate = false;

private ?string $createdAt = null;
private ?string $updatedAt = null;
private ?string $deletedAt = null;

private const PHP_SQL_TYPES = [
"int" => "INTEGER",
"float" => "FLOAT",
Expand All @@ -38,9 +46,10 @@ public function __construct(

if (count($tableAttributes) > 0) {
$tableAttribute = $tableAttributes[0]->newInstance();
$this->name = $tableAttribute->value;
$this->name = $tableAttribute->name;
$this->disableAutoMigrate = $tableAttribute->disableAutoMigrate;
} else {
}
if ($this->name === null) {
$this->name = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $reflection->getShortName()));
if (!str_ends_with($this->name, "s"))
$this->name .= "s";
Expand All @@ -51,7 +60,21 @@ public function __construct(
$columnAttributes = $property->getAttributes(Column::class);
if (count($columnAttributes) > 0) {
$columnAttribute = $columnAttributes[0]->newInstance();
$this->fields[$property->getName()] = new ColumnInformation($columnAttribute->name ?? strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $property->getName())), $columnAttribute, $property);
$columnInfo = new ColumnInformation($columnAttribute->name ?? strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $property->getName())), $columnAttribute, $property);

$this->fields[$property->getName()] = $columnInfo;

if ($columnAttribute->id)
$this->identifier = $property->getName();

if (count($property->getAttributes(CreatedAt::class)))
$this->createdAt = $property->getName();

if (count($property->getAttributes(UpdatedAt::class)))
$this->updatedAt = $property->getName();

if (count($property->getAttributes(DeletedAt::class)))
$this->deletedAt = $property->getName();
}
}
}
Expand Down Expand Up @@ -94,8 +117,6 @@ public function getColumnInformation(string $name): ColumnInformation|null {
}

public function getFieldValue($obj, string $field): string {


return $obj->{$this->getFieldName($field)};
}

Expand All @@ -106,11 +127,11 @@ public function getIdentifierValue($obj): string {
public function isAutoMigrateDisabled(): bool {
return $this->disableAutoMigrate;
}
public function autoMigrate(array|null $databases = null) : ModelInformation {

public function autoMigrate(array|null $databases = null): ModelInformation {
if ($databases === null)
$databases = UloleORM::getDatabases();

foreach ($databases as $database) {
$tables = [];
foreach ($database->query("SHOW TABLES;")->fetchAll() as $r) {
Expand Down Expand Up @@ -138,7 +159,8 @@ public function autoMigrate(array|null $databases = null) : ModelInformation {
"identifier" => $isIdentifier,
"query" => "`" . $field->getFieldName() . "` "
. $type
. ($field->getType()->allowsNull() ? '' : ' NOT NULL')
. ($field->getType()->allowsNull() ? ' NULL' : ' NOT NULL')
. ($field->getColumnAttribute()->unique ? ' UNIQUE' : '')
. ($type == 'INTEGER' && $isIdentifier ? ' AUTO_INCREMENT' : '')
];
}, $fields);
Expand Down Expand Up @@ -182,7 +204,19 @@ public function autoMigrate(array|null $databases = null) : ModelInformation {
}
}


return $this;
}

public function getCreatedAt(): ?string {
return $this->createdAt;
}

public function getDeletedAt(): ?string {
return $this->deletedAt;
}

public function getUpdatedAt(): ?string {
return $this->updatedAt;
}
}
16 changes: 12 additions & 4 deletions de/interaapps/ulole/orm/ORMModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function save(string $database = 'main'): bool {
if (isset($this->{$fieldName}))
$query->set($modelInformation->getFieldName(), $this->{$fieldName});
}
return $query->where(UloleORM::getModelInformation(static::class)->getIdentifier(), UloleORM::getModelInformation(static::class)->getIdentifierValue($this))->update() !== false;
return $query->whereId(UloleORM::getModelInformation(static::class)->getIdentifierValue($this))->update();
} else {
return $this->insert($database);
}
Expand All @@ -34,9 +34,17 @@ public function save(string $database = 'main'): bool {
public function insert(string $database = 'main'): bool {
$fields = [];
$values = [];
foreach (UloleORM::getModelInformation(static::class)->getFields() as $fieldName => $modelInformation) {
$modelInfo = UloleORM::getModelInformation(static::class);

$createdAt = $modelInfo->getUpdatedAt();
if ($createdAt !== null && !isset($this->createdAt)) {
$fields[] = $modelInfo->getFieldName($createdAt);
$values[] = date("Y-m-d H:i:s");
}

foreach ($modelInfo->getFields() as $fieldName => $columnInformation) {
if (isset($this->{$fieldName})) {
$fields[] = $modelInformation->getFieldName();
$fields[] = $columnInformation->getFieldName();
$values[] = $this->{$fieldName};
}
}
Expand All @@ -63,7 +71,7 @@ public function insert(string $database = 'main'): bool {

public function delete(string $database = 'main'): bool {
return self::table($database)
->where(UloleORM::getModelInformation(static::class)->getIdentifier(), UloleORM::getModelInformation(static::class)->getIdentifierValue($this))
->whereId(UloleORM::getModelInformation(static::class)->getIdentifierValue($this))
->delete();
}

Expand Down
65 changes: 46 additions & 19 deletions de/interaapps/ulole/orm/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class Query {
private int|null $offset = null;
private array|null $orderBy = null;
private bool $temporaryQuery = false;
private bool $withDeleted = false;
private ModelInformation $modelInformation;

/**
Expand Down Expand Up @@ -49,7 +50,12 @@ public function where(string $field, mixed $var2, mixed $var3 = null): Query {
$operator = '=';
} else
$value = $var3;
return $this->whereRaw('`'.$this->modelInformation->getFieldName($field).'`', $operator, '?', [$value]);
return $this->whereRaw('`' . $this->modelInformation->getFieldName($field) . '`', $operator, '?', [$value]);
}

public function whereId($id): Query {
$this->whereRaw("`" . $this->modelInformation->getIdentifier() . "`", "=", "?", [$id]);
return $this;
}

public function whereDay(string $field, mixed $val): Query {
Expand Down Expand Up @@ -96,17 +102,17 @@ public function whereColumns(string $field1Table, string $field1Name, string $op
$this->queries[] = [
'type' => 'AND',
'query' =>
UloleORM::getTableName($field1Table) . '.`' . UloleORM::getModelInformation($field1Table)->getFieldName($field1Name) . '` '
UloleORM::getTableName($field1Table) . '.`' . UloleORM::getModelInformation($field1Table)->getFieldName($field1Name) . '` '
. $operator . ' '
. UloleORM::getTableName($field2Table) . '.`' . UloleORM::getModelInformation($field2Table)->getFieldName($field2Name).'`'];
. UloleORM::getTableName($field2Table) . '.`' . UloleORM::getModelInformation($field2Table)->getFieldName($field2Name) . '`'];
return $this;
}

/**
* @return $this
*/
public function orWhere(string $var1, mixed $var2, mixed $var3 = null): Query {
return $this->or(fn ($q) => $q->where($var1, $var2, $var3));
return $this->or(fn($q) => $q->where($var1, $var2, $var3));
}

/**
Expand Down Expand Up @@ -190,7 +196,7 @@ public function whereExists(string $table, callable $callable): Query {
* @throws Null
*/
public function in(string $field, callable|array $var, string|null $table = null): Query {
$query = ['type' => 'WHERE_IN', "column" => '`'.$this->modelInformation->getFieldName($field).'`', "not" => false];
$query = ['type' => 'WHERE_IN', "column" => '`' . $this->modelInformation->getFieldName($field) . '`', "not" => false];
if (is_array($var)) {
$query["query"] = implode(",", array_map(fn() => "?", $var));
$query["vars"] = $var;
Expand All @@ -206,6 +212,7 @@ public function in(string $field, callable|array $var, string|null $table = null

return $this;
}

public function notIn(string $field, callable|array $var, string|null $table = null): Query {
$this->in($field, $var, $table);
$this->queries[count($this->queries) - 1]["not"] = true;
Expand Down Expand Up @@ -240,14 +247,15 @@ public function first(): mixed {
if ($this->limit === null)
$this->limit(1);

return $this->get()[0] ?? null;
return $this->all()[0] ?? null;
}

/**
* @return T[]
*/
public function all(): array {
$vars = [];

$query = $this->buildQuery();
$vars = array_merge($vars, $query->vars);

Expand Down Expand Up @@ -283,7 +291,7 @@ private function selectNumber(string $f): int|float {
$vars = [];
$query = $this->buildQuery();
$vars = array_merge($vars, $query->vars);
$statement = $this->run('SELECT '.$f.' as num FROM ' . UloleORM::getTableName($this->model) . $query->query . ';', $vars);
$statement = $this->run('SELECT ' . $f . ' as num FROM ' . UloleORM::getTableName($this->model) . $query->query . ';', $vars);
$statement->setFetchMode(PDO::FETCH_NUM);
$result = $statement->fetch();
if ($result === false)
Expand All @@ -297,39 +305,49 @@ public function count(): int {
}

public function sum(string $field): float|int {
return $this->selectNumber("SUM(`".$this->modelInformation->getFieldName($field)."`)");
return $this->selectNumber("SUM(`" . $this->modelInformation->getFieldName($field) . "`)");
}

public function sub(string $field): float|int {
return $this->selectNumber("SUM(-`".$this->modelInformation->getFieldName($field)."`)");
return $this->selectNumber("SUM(-`" . $this->modelInformation->getFieldName($field) . "`)");
}

public function avg(string $field): float|int {
return $this->selectNumber("AVG(`".$this->modelInformation->getFieldName($field)."`)");
return $this->selectNumber("AVG(`" . $this->modelInformation->getFieldName($field) . "`)");
}

public function min(string $field): float|int {
return $this->selectNumber("MIN(`".$this->modelInformation->getFieldName($field)."`)");
return $this->selectNumber("MIN(`" . $this->modelInformation->getFieldName($field) . "`)");
}

public function max(string $field): float|int {
return $this->selectNumber("MAX(`".$this->modelInformation->getFieldName($field)."`)");
return $this->selectNumber("MAX(`" . $this->modelInformation->getFieldName($field) . "`)");
}

public function update(): bool {
$vars = [];

$updatedAt = $this->modelInformation->getUpdatedAt();
if ($updatedAt !== null) {
$this->set($updatedAt, date("Y-m-d H:i:s"));
}

$query = $this->buildQuery();
$vars = array_merge($vars, $query->vars);

return $this->run('UPDATE `' . UloleORM::getTableName($this->model) . '`' . $query->query . ';', $vars, true);
return $this->run('UPDATE `' . UloleORM::getTableName($this->model) . '`' . $query->query . ';', $vars, true) !== false;
}

public function delete(): bool {
$vars = [];
$query = $this->buildQuery();
$vars = array_merge($vars, $query->vars);

return $this->run('DELETE FROM `' . UloleORM::getTableName($this->model) . '`' . $query->query . ';', $vars, true);
$deletedAt = $this->modelInformation->getDeletedAt();
if ($deletedAt !== null)
$this->set($this->modelInformation->getFieldName($deletedAt), date("Y-m-d H:i:s"))->update();

return $this->run('DELETE FROM `' . UloleORM::getTableName($this->model) . '`' . $query->query . ';', $vars, true) !== false;
}

public function run(string $query, array $vars = [], bool $returnResult = false): PDOStatement|bool|null {
Expand All @@ -345,13 +363,17 @@ public function run(string $query, array $vars = [], bool $returnResult = false)
}

protected function buildQuery(): object {
$deletedAt = $this->modelInformation->getDeletedAt();
if ($deletedAt !== null && !$this->withDeleted)
$this->isNull($this->modelInformation->getFieldName($deletedAt));

$out = (object)["query" => '', 'vars' => []];

$usedWhere = $this->temporaryQuery;
$usedSet = false;
$useCondition = false;

foreach (array_filter($this->queries, fn ($q) => $q["type"] == "SET") as $query) {
foreach (array_filter($this->queries, fn($q) => $q["type"] == "SET") as $query) {
if (!$usedSet) {
$out->query .= " SET ";
$usedSet = true;
Expand Down Expand Up @@ -390,10 +412,10 @@ protected function buildQuery(): object {
$out->query .= $where->query;
$out->query .= ') ';
}
} else if ($query["type"] == 'WHERE_EXISTS' || $query["type"] == 'WHERE_NOT_EXISTS') {
$out->query .= " WHERE " . ($query["type"] == 'WHERE_NOT_EXISTS' ? "NOT " : "") . "EXISTS (".$query["query"].")";
} else if ($query["type"] == 'WHERE_IN') {
$out->query .= " WHERE " . $query["column"] . ($query["not"] ? " NOT " : ' ')." IN (".$query["query"].")";
} else if ($query["type"] == 'WHERE_EXISTS' || $query["type"] == 'WHERE_NOT_EXISTS') {
$out->query .= " WHERE " . ($query["type"] == 'WHERE_NOT_EXISTS' ? "NOT " : "") . "EXISTS (" . $query["query"] . ")";
} else if ($query["type"] == 'WHERE_IN') {
$out->query .= " WHERE " . $query["column"] . ($query["not"] ? " NOT " : ' ') . " IN (" . $query["query"] . ")";
$out->vars = $query["vars"];
}
}
Expand All @@ -411,6 +433,11 @@ public function getQueries(): array {
return $this->queries;
}

public function withDeleted($withDeleted = true): Query {
$this->withDeleted = $withDeleted;
return $this;
}

/**
* @return $this
*/
Expand Down
2 changes: 1 addition & 1 deletion de/interaapps/ulole/orm/UloleORM.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public static function getTableName($modelClazz): string {
*/
public static function getModelInformation($model): ModelInformation {
if (!isset(self::$modelInformation[$model]))
throw new \Exception("Register the model first with UloleORM::register(".$model."::class);");
throw new \Exception("Register the model first with UloleORM::register(" . $model . "::class);");
return self::$modelInformation[$model];
}

Expand Down
4 changes: 3 additions & 1 deletion de/interaapps/ulole/orm/attributes/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

use Attribute;

#[Attribute]
#[Attribute(Attribute::TARGET_PROPERTY)]
class Column {
public function __construct(
public ?string $name = null,
public ?string $sqlType = null,
public string|int|null $size = null,
public bool $index = false,
public bool $id = false,
public bool $unique = false,
) {
}
}
Loading

0 comments on commit 8018168

Please sign in to comment.